Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.96
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.96! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.95 2018/09/02 02:13:59 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.492 albertel 2881: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2882:
2883: sub allowuploaded {
2884: my ($srcurl,$url)=@_;
2885: $url=&clutter(&declutter($url));
2886: my $dir=$url;
2887: $dir=~s/\/[^\/]+$//;
2888: my %httpref=();
2889: my $httpurl=&hreflocation('',$url);
2890: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2891: &Apache::lonnet::appenv(\%httpref);
1.254 www 2892: }
1.477 raeburn 2893:
1.1172.2.13 raeburn 2894: #
2895: # Determine if the current user should be able to edit a particular resource,
2896: # when viewing in course context.
2897: # (a) When viewing resource used to determine if "Edit" item is included in
2898: # Functions.
2899: # (b) When displaying folder contents in course editor, used to determine if
2900: # "Edit" link will be displayed alongside resource.
2901: #
2902: # input: six args -- filename (decluttered), course number, course domain,
2903: # url, symb (if registered) and group (if this is a group
2904: # item -- e.g., bulletin board, group page etc.).
2905: # output: array of five scalars --
2906: # $cfile -- url for file editing if editable on current server
2907: # $home -- homeserver of resource (i.e., for author if published,
2908: # or course if uploaded.).
2909: # $switchserver -- 1 if server switch will be needed.
2910: # $forceedit -- 1 if icon/link should be to go to edit mode
2911: # $forceview -- 1 if icon/link should be to go to view mode
2912: #
2913:
2914: sub can_edit_resource {
2915: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2916: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2917: #
2918: # For aboutme pages user can only edit his/her own.
2919: #
2920: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2921: my ($sdom,$sname) = ($1,$2);
2922: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2923: $home = $env{'user.home'};
2924: $cfile = $resurl;
2925: if ($env{'form.forceedit'}) {
2926: $forceview = 1;
2927: } else {
2928: $forceedit = 1;
2929: }
2930: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2931: } else {
2932: return;
2933: }
2934: }
2935:
2936: if ($env{'request.course.id'}) {
2937: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2938: if ($group ne '') {
2939: # if this is a group homepage or group bulletin board, check group privs
2940: my $allowed = 0;
2941: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2942: if ((&allowed('mdg',$env{'request.course.id'}.
2943: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2944: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2945: $allowed = 1;
2946: }
2947: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2948: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2949: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2950: $allowed = 1;
2951: }
2952: }
2953: if ($allowed) {
2954: $home=&homeserver($cnum,$cdom);
2955: if ($env{'form.forceedit'}) {
2956: $forceview = 1;
2957: } else {
2958: $forceedit = 1;
2959: }
2960: $cfile = $resurl;
2961: } else {
2962: return;
2963: }
2964: } else {
1.1172.2.15 raeburn 2965: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2966: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2967: return;
2968: }
2969: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2970: #
2971: # No edit allowed where CC has switched to student role.
2972: #
2973: return;
2974: }
2975: }
2976: }
2977:
2978: if ($file ne '') {
2979: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2980: if (&is_course_upload($file,$cnum,$cdom)) {
2981: $uploaded = 1;
2982: $incourse = 1;
2983: if ($file =~/\.(htm|html|css|js|txt)$/) {
2984: $cfile = &hreflocation('',$file);
2985: if ($env{'form.forceedit'}) {
2986: $forceview = 1;
2987: } else {
2988: $forceedit = 1;
2989: }
2990: }
2991: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2992: $incourse = 1;
2993: if ($env{'form.forceedit'}) {
2994: $forceview = 1;
2995: } else {
2996: $forceedit = 1;
2997: }
2998: $cfile = $resurl;
2999: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3000: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3001: $incourse = 1;
3002: if ($env{'form.forceedit'}) {
3003: $forceview = 1;
3004: } else {
3005: $forceedit = 1;
3006: }
3007: $cfile = $resurl;
3008: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3009: $incourse = 1;
3010: $cfile = $resurl.'/smpedit';
3011: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3012: $incourse = 1;
3013: if ($env{'form.forceedit'}) {
3014: $forceview = 1;
3015: } else {
3016: $forceedit = 1;
3017: }
3018: $cfile = $resurl;
1.1172.2.15 raeburn 3019: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3020: $incourse = 1;
3021: if ($env{'form.forceedit'}) {
3022: $forceview = 1;
3023: } else {
3024: $forceedit = 1;
3025: }
3026: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3027: }
3028: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3029: my $template = '/res/lib/templates/simpleproblem.problem';
3030: if (&is_on_map($template)) {
3031: $incourse = 1;
3032: $forceview = 1;
3033: $cfile = $template;
3034: }
3035: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3036: $incourse = 1;
3037: if ($env{'form.forceedit'}) {
3038: $forceview = 1;
3039: } else {
3040: $forceedit = 1;
3041: }
3042: $cfile = $resurl;
3043: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3044: $incourse = 1;
3045: $forceview = 1;
3046: if ($symb) {
3047: my ($map,$id,$res)=&decode_symb($symb);
3048: $env{'request.symb'} = $symb;
3049: $cfile = &clutter($res);
3050: } else {
3051: $cfile = $env{'form.suppurl'};
3052: $cfile =~ s{^http://}{};
3053: $cfile = '/adm/wrapper/ext/'.$cfile;
3054: }
1.1172.2.31 raeburn 3055: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3056: if ($env{'form.forceedit'}) {
3057: $forceview = 1;
3058: } else {
3059: $forceedit = 1;
3060: }
3061: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3062: }
3063: }
3064: if ($uploaded || $incourse) {
3065: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3066: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3067: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3068: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3069: # Check that the user has permission to edit this resource
3070: my $setpriv = 1;
3071: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3072: if (defined($cfudom)) {
3073: $home=&homeserver($cfuname,$cfudom);
3074: $cfile=$file;
3075: }
3076: }
3077: if (($cfile ne '') && (!$incourse || $uploaded) &&
3078: (($home ne '') && ($home ne 'no_host'))) {
3079: my @ids=¤t_machine_ids();
3080: unless (grep(/^\Q$home\E$/,@ids)) {
3081: $switchserver=1;
3082: }
3083: }
3084: }
3085: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3086: }
3087:
3088: sub is_course_upload {
3089: my ($file,$cnum,$cdom) = @_;
3090: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3091: $uploadpath =~ s{^\/}{};
3092: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3093: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3094: return 1;
3095: }
3096: return;
3097: }
3098:
3099: sub in_course {
3100: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3101: if ($hideprivileged) {
3102: my $skipuser;
1.1172.2.23 raeburn 3103: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3104: my @possdoms = ($cdom);
3105: if ($coursehash{'checkforpriv'}) {
3106: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3107: }
3108: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3109: $skipuser = 1;
3110: if ($coursehash{'nothideprivileged'}) {
3111: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3112: my $user;
3113: if ($item =~ /:/) {
3114: $user = $item;
3115: } else {
3116: $user = join(':',split(/[\@]/,$item));
3117: }
3118: if ($user eq $uname.':'.$udom) {
3119: undef($skipuser);
3120: last;
3121: }
3122: }
3123: }
3124: if ($skipuser) {
3125: return 0;
3126: }
3127: }
3128: }
3129: $type ||= 'any';
3130: if (!defined($cdom) || !defined($cnum)) {
3131: my $cid = $env{'request.course.id'};
3132: $cdom = $env{'course.'.$cid.'.domain'};
3133: $cnum = $env{'course.'.$cid.'.num'};
3134: }
3135: my $typesref;
3136: if (($type eq 'any') || ($type eq 'all')) {
3137: $typesref = ['active','previous','future'];
3138: } elsif ($type eq 'previous' || $type eq 'future') {
3139: $typesref = [$type];
3140: }
3141: my %roles = &get_my_roles($uname,$udom,'userroles',
3142: $typesref,undef,[$cdom]);
3143: my ($tmp) = keys(%roles);
3144: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3145: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3146: if (@course_roles > 0) {
3147: return 1;
3148: }
3149: return 0;
3150: }
3151:
1.478 albertel 3152: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3153: # input: action, courseID, current domain, intended
1.637 raeburn 3154: # path to file, source of file, instruction to parse file for objects,
3155: # ref to hash for embedded objects,
3156: # ref to hash for codebase of java objects.
1.1095 raeburn 3157: # reference to scalar to accommodate mime type determined
3158: # from File::MMagic if $parser = parse.
1.637 raeburn 3159: #
1.485 raeburn 3160: # output: url to file (if action was uploaddoc),
3161: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3162: #
1.478 albertel 3163: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3164: # course.
1.477 raeburn 3165: #
1.478 albertel 3166: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3167: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3168: # course's home server.
1.477 raeburn 3169: #
1.478 albertel 3170: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3171: # be copied from $source (current location) to
3172: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3173: # and will then be copied to
3174: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3175: # course's home server.
1.485 raeburn 3176: #
1.481 raeburn 3177: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3178: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3179: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3180: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3181: # in course's home server.
1.637 raeburn 3182: #
1.477 raeburn 3183:
3184: sub process_coursefile {
1.1095 raeburn 3185: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3186: $mimetype)=@_;
1.477 raeburn 3187: my $fetchresult;
1.638 albertel 3188: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3189: if ($action eq 'propagate') {
1.638 albertel 3190: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3191: $home);
1.481 raeburn 3192: } else {
1.477 raeburn 3193: my $fpath = '';
3194: my $fname = $file;
1.478 albertel 3195: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3196: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3197: my $filepath = &build_filepath($fpath);
1.481 raeburn 3198: if ($action eq 'copy') {
3199: if ($source eq '') {
3200: $fetchresult = 'no source file';
3201: return $fetchresult;
3202: } else {
3203: my $destination = $filepath.'/'.$fname;
3204: rename($source,$destination);
3205: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3206: $home);
1.481 raeburn 3207: }
3208: } elsif ($action eq 'uploaddoc') {
1.1172.2.96! raeburn 3209: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3210: print $fh $env{'form.'.$source};
1.481 raeburn 3211: close($fh);
1.637 raeburn 3212: if ($parser eq 'parse') {
1.1024 raeburn 3213: my $mm = new File::MMagic;
1.1095 raeburn 3214: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3215: if ($type eq 'text/html') {
1.1024 raeburn 3216: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3217: unless ($parse_result eq 'ok') {
3218: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3219: }
1.637 raeburn 3220: }
1.1095 raeburn 3221: if (ref($mimetype)) {
3222: $$mimetype = $type;
3223: }
1.637 raeburn 3224: }
1.477 raeburn 3225: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3226: $home);
1.481 raeburn 3227: if ($fetchresult eq 'ok') {
3228: return '/uploaded/'.$fpath.'/'.$fname;
3229: } else {
3230: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3231: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3232: return '/adm/notfound.html';
3233: }
1.477 raeburn 3234: }
3235: }
1.485 raeburn 3236: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3237: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3238: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3239: }
3240: return $fetchresult;
3241: }
3242:
1.637 raeburn 3243: sub build_filepath {
3244: my ($fpath) = @_;
3245: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3246: unless ($fpath eq '') {
3247: my @parts=split('/',$fpath);
3248: foreach my $part (@parts) {
3249: $filepath.= '/'.$part;
3250: if ((-e $filepath)!=1) {
3251: mkdir($filepath,0777);
3252: }
3253: }
3254: }
3255: return $filepath;
3256: }
3257:
3258: sub store_edited_file {
1.638 albertel 3259: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3260: my $file = $primary_url;
3261: $file =~ s#^/uploaded/$docudom/$docuname/##;
3262: my $fpath = '';
3263: my $fname = $file;
3264: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3265: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3266: my $filepath = &build_filepath($fpath);
1.1172.2.96! raeburn 3267: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3268: print $fh $content;
3269: close($fh);
1.638 albertel 3270: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3271: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3272: $home);
1.637 raeburn 3273: if ($$fetchresult eq 'ok') {
3274: return '/uploaded/'.$fpath.'/'.$fname;
3275: } else {
1.638 albertel 3276: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3277: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3278: return '/adm/notfound.html';
3279: }
3280: }
3281:
1.531 albertel 3282: sub clean_filename {
1.831 albertel 3283: my ($fname,$args)=@_;
1.315 www 3284: # Replace Windows backslashes by forward slashes
1.257 www 3285: $fname=~s/\\/\//g;
1.831 albertel 3286: if (!$args->{'keep_path'}) {
3287: # Get rid of everything but the actual filename
3288: $fname=~s/^.*\/([^\/]+)$/$1/;
3289: }
1.315 www 3290: # Replace spaces by underscores
3291: $fname=~s/\s+/\_/g;
3292: # Replace all other weird characters by nothing
1.831 albertel 3293: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3294: # Replace all .\d. sequences with _\d. so they no longer look like version
3295: # numbers
3296: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3297: return $fname;
3298: }
1.1051 raeburn 3299: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3300: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3301: # image with the same aspect ratio as the original, but with dimensions which do
3302: # not exceed $resizewidth and $resizeheight.
3303:
1.984 neumanie 3304: sub resizeImage {
1.1051 raeburn 3305: my ($img_path,$resizewidth,$resizeheight) = @_;
3306: my $ima = Image::Magick->new;
3307: my $resized;
3308: if (-e $img_path) {
3309: $ima->Read($img_path);
3310: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3311: my $width = $ima->Get('width');
3312: my $height = $ima->Get('height');
3313: if ($width > $resizewidth) {
3314: my $factor = $width/$resizewidth;
3315: my $newheight = $height/$factor;
3316: $ima->Scale(width=>$resizewidth,height=>$newheight);
3317: $resized = 1;
3318: }
3319: }
3320: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3321: my $width = $ima->Get('width');
3322: my $height = $ima->Get('height');
3323: if ($height > $resizeheight) {
3324: my $factor = $height/$resizeheight;
3325: my $newwidth = $width/$factor;
3326: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3327: $resized = 1;
3328: }
3329: }
3330: if ($resized) {
3331: $ima->Write($img_path);
3332: }
3333: }
3334: return;
1.977 amueller 3335: }
3336:
1.608 albertel 3337: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3338: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3339: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3340: # $context - possible values: coursedoc, existingfile, overwrite,
3341: # canceloverwrite, or ''.
3342: # if 'coursedoc': upload to the current course
3343: # if 'existingfile': write file to tmp/overwrites directory
3344: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3345: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3346: # $subdir - directory in userfile to store the file into
1.858 raeburn 3347: # $parser - instruction to parse file for objects ($parser = parse)
3348: # $allfiles - reference to hash for embedded objects
3349: # $codebase - reference to hash for codebase of java objects
3350: # $desuname - username for permanent storage of uploaded file
3351: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3352: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3353: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3354: # $resizewidth - width (pixels) to which to resize uploaded image
3355: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3356: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3357: # from File::MMagic.
1.858 raeburn 3358: #
1.686 albertel 3359: # output: url of file in userspace, or error: <message>
3360: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3361:
1.531 albertel 3362: sub userfileupload {
1.1090 raeburn 3363: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3364: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3365: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3366: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3367: $fname=&clean_filename($fname);
1.1090 raeburn 3368: # See if there is anything left
1.257 www 3369: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3370: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3371: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3372: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3373: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3374: my $now = time;
1.1090 raeburn 3375: my $filepath;
1.1095 raeburn 3376: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3377: $filepath = 'tmp/helprequests/'.$now;
3378: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3379: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3380: '_'.$env{'user.domain'}.'/pending';
3381: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3382: my ($docuname,$docudom);
1.1172.2.96! raeburn 3383: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3384: $docudom = $destudom;
3385: } else {
3386: $docudom = $env{'user.domain'};
3387: }
1.1172.2.96! raeburn 3388: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3389: $docuname = $destuname;
3390: } else {
3391: $docuname = $env{'user.name'};
3392: }
3393: if (exists($env{'form.group'})) {
3394: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3395: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3396: }
3397: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3398: if ($context eq 'canceloverwrite') {
3399: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3400: if (-e $tempfile) {
3401: my @info = stat($tempfile);
3402: if ($info[9] eq $env{'form.timestamp'}) {
3403: unlink($tempfile);
3404: }
3405: }
3406: return;
1.523 raeburn 3407: }
3408: }
1.1090 raeburn 3409: # Create the directory if not present
1.741 raeburn 3410: my @parts=split(/\//,$filepath);
3411: my $fullpath = $perlvar{'lonDaemons'};
3412: for (my $i=0;$i<@parts;$i++) {
3413: $fullpath .= '/'.$parts[$i];
3414: if ((-e $fullpath)!=1) {
3415: mkdir($fullpath,0777);
3416: }
3417: }
1.1172.2.96! raeburn 3418: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3419: print $fh $env{'form.'.$formname};
3420: close($fh);
1.1090 raeburn 3421: if ($context eq 'existingfile') {
3422: my @info = stat($fullpath.'/'.$fname);
3423: return ($fullpath.'/'.$fname,$info[9]);
3424: } else {
3425: return $fullpath.'/'.$fname;
3426: }
1.523 raeburn 3427: }
1.995 raeburn 3428: if ($subdir eq 'scantron') {
3429: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3430: } else {
1.995 raeburn 3431: $fname="$subdir/$fname";
3432: }
1.1090 raeburn 3433: if ($context eq 'coursedoc') {
1.638 albertel 3434: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3435: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3436: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3437: return &finishuserfileupload($docuname,$docudom,
3438: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3439: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3440: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3441: } else {
1.1172.2.21 raeburn 3442: if ($env{'form.folder'}) {
3443: $fname=$env{'form.folder'}.'/'.$fname;
3444: }
1.638 albertel 3445: return &process_coursefile('uploaddoc',$docuname,$docudom,
3446: $fname,$formname,$parser,
1.1095 raeburn 3447: $allfiles,$codebase,$mimetype);
1.481 raeburn 3448: }
1.719 banghart 3449: } elsif (defined($destuname)) {
3450: my $docuname=$destuname;
3451: my $docudom=$destudom;
1.860 raeburn 3452: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3453: $parser,$allfiles,$codebase,
1.1051 raeburn 3454: $thumbwidth,$thumbheight,
1.1095 raeburn 3455: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3456: } else {
1.638 albertel 3457: my $docuname=$env{'user.name'};
3458: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3459: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3460: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3461: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3462: }
1.860 raeburn 3463: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3464: $parser,$allfiles,$codebase,
1.1051 raeburn 3465: $thumbwidth,$thumbheight,
1.1095 raeburn 3466: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3467: }
1.271 www 3468: }
3469:
3470: sub finishuserfileupload {
1.860 raeburn 3471: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3472: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3473: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3474: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3475:
1.860 raeburn 3476: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3477: $file=$fname;
3478: if ($fname=~m|/|) {
3479: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3480: $path.=$fnamepath.'/';
3481: }
1.259 www 3482: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3483: my $count;
3484: for ($count=4;$count<=$#parts;$count++) {
3485: $filepath.="/$parts[$count]";
3486: if ((-e $filepath)!=1) {
3487: mkdir($filepath,0777);
3488: }
3489: }
1.984 neumanie 3490:
1.258 www 3491: # Save the file
3492: {
1.1172.2.96! raeburn 3493: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3494: &logthis('Failed to create '.$filepath.'/'.$file);
3495: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3496: return '/adm/notfound.html';
3497: }
1.1090 raeburn 3498: if ($context eq 'overwrite') {
1.1117 foxr 3499: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3500: my $target = $filepath.'/'.$file;
3501: if (-e $source) {
3502: my @info = stat($source);
3503: if ($info[9] eq $env{'form.timestamp'}) {
3504: unless (&File::Copy::move($source,$target)) {
3505: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3506: return "Moving from $source failed";
3507: }
3508: } else {
3509: return "Temporary file: $source had unexpected date/time for last modification";
3510: }
3511: } else {
3512: return "Temporary file: $source missing";
3513: }
3514: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3515: &logthis('Failed to write to '.$filepath.'/'.$file);
3516: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3517: return '/adm/notfound.html';
3518: }
1.570 albertel 3519: close(FH);
1.1051 raeburn 3520: if ($resizewidth && $resizeheight) {
3521: my $mm = new File::MMagic;
3522: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3523: if ($mime_type =~ m{^image/}) {
3524: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3525: }
1.977 amueller 3526: }
1.258 www 3527: }
1.1152 raeburn 3528: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3529: if (ref($mimetype)) {
3530: if ($$mimetype eq '') {
3531: my $mm = new File::MMagic;
3532: my $type = $mm->checktype_filename($filepath.'/'.$file);
3533: $$mimetype = $type;
3534: }
3535: }
3536: }
1.637 raeburn 3537: if ($parser eq 'parse') {
1.1152 raeburn 3538: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3539: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3540: $allfiles,$codebase);
3541: unless ($parse_result eq 'ok') {
3542: &logthis('Failed to parse '.$filepath.$file.
3543: ' for embedded media: '.$parse_result);
3544: }
1.637 raeburn 3545: }
3546: }
1.860 raeburn 3547: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3548: my $input = $filepath.'/'.$file;
3549: my $output = $filepath.'/'.'tn-'.$file;
3550: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96! raeburn 3551: my @args = ('convert','-sample',$thumbsize,$input,$output);
! 3552: system({$args[0]} @args);
1.860 raeburn 3553: if (-e $filepath.'/'.'tn-'.$file) {
3554: $fetchthumb = 1;
3555: }
3556: }
1.858 raeburn 3557:
1.259 www 3558: # Notify homeserver to grep it
3559: #
1.984 neumanie 3560: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3561: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3562: if ($fetchresult eq 'ok') {
1.860 raeburn 3563: if ($fetchthumb) {
3564: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3565: if ($thumbresult ne 'ok') {
3566: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3567: $docuhome.': '.$thumbresult);
3568: }
3569: }
1.259 www 3570: #
1.258 www 3571: # Return the URL to it
1.494 albertel 3572: return '/uploaded/'.$path.$file;
1.263 www 3573: } else {
1.494 albertel 3574: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3575: ': '.$fetchresult);
1.263 www 3576: return '/adm/notfound.html';
1.858 raeburn 3577: }
1.493 albertel 3578: }
3579:
1.637 raeburn 3580: sub extract_embedded_items {
1.961 raeburn 3581: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3582: my @state = ();
1.1164 raeburn 3583: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3584: my %javafiles = (
3585: codebase => '',
3586: code => '',
3587: archive => ''
3588: );
3589: my %mediafiles = (
3590: src => '',
3591: movie => '',
3592: );
1.648 raeburn 3593: my $p;
3594: if ($content) {
3595: $p = HTML::LCParser->new($content);
3596: } else {
1.961 raeburn 3597: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3598: }
1.641 albertel 3599: while (my $t=$p->get_token()) {
1.640 albertel 3600: if ($t->[0] eq 'S') {
3601: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3602: push(@state, $tagname);
1.648 raeburn 3603: if (lc($tagname) eq 'allow') {
3604: &add_filetype($allfiles,$attr->{'src'},'src');
3605: }
1.640 albertel 3606: if (lc($tagname) eq 'img') {
3607: &add_filetype($allfiles,$attr->{'src'},'src');
3608: }
1.886 albertel 3609: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3610: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3611: &add_filetype($allfiles,$attr->{'href'},'href');
3612: }
1.886 albertel 3613: }
1.645 raeburn 3614: if (lc($tagname) eq 'script') {
1.1164 raeburn 3615: my $src;
1.645 raeburn 3616: if ($attr->{'archive'} =~ /\.jar$/i) {
3617: &add_filetype($allfiles,$attr->{'archive'},'archive');
3618: } else {
1.1164 raeburn 3619: if ($attr->{'src'} ne '') {
3620: $src = $attr->{'src'};
3621: &add_filetype($allfiles,$src,'src');
3622: }
3623: }
3624: my $text = $p->get_trimmed_text();
3625: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3626: my @swfargs = split(/,/,$1);
3627: foreach my $item (@swfargs) {
3628: $item =~ s/["']//g;
3629: $item =~ s/^\s+//;
3630: $item =~ s/\s+$//;
3631: }
3632: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3633: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3634: push(@{$related{$swfargs[0]}},$swfargs[2]);
3635: } else {
3636: $related{$swfargs[0]} = [$swfargs[2]];
3637: }
3638: }
1.645 raeburn 3639: }
3640: }
3641: if (lc($tagname) eq 'link') {
3642: if (lc($attr->{'rel'}) eq 'stylesheet') {
3643: &add_filetype($allfiles,$attr->{'href'},'href');
3644: }
3645: }
1.640 albertel 3646: if (lc($tagname) eq 'object' ||
3647: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3648: foreach my $item (keys(%javafiles)) {
3649: $javafiles{$item} = '';
3650: }
1.1164 raeburn 3651: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3652: $lastids{lc($tagname)} = $attr->{'id'};
3653: }
1.640 albertel 3654: }
3655: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3656: my $name = lc($attr->{'name'});
3657: foreach my $item (keys(%javafiles)) {
3658: if ($name eq $item) {
3659: $javafiles{$item} = $attr->{'value'};
3660: last;
3661: }
3662: }
1.1164 raeburn 3663: my $pathfrom;
1.640 albertel 3664: foreach my $item (keys(%mediafiles)) {
3665: if ($name eq $item) {
1.1164 raeburn 3666: $pathfrom = $attr->{'value'};
3667: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3668: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3669: last;
3670: }
3671: }
1.1164 raeburn 3672: if ($name eq 'flashvars') {
3673: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3674: }
3675: if ($pathfrom ne '') {
3676: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3677: $pathfrom);
3678: }
1.640 albertel 3679: }
3680: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3681: foreach my $item (keys(%javafiles)) {
3682: if ($attr->{$item}) {
3683: $javafiles{$item} = $attr->{$item};
3684: last;
3685: }
3686: }
3687: foreach my $item (keys(%mediafiles)) {
3688: if ($attr->{$item}) {
3689: &add_filetype($allfiles,$attr->{$item},$item);
3690: last;
3691: }
3692: }
1.1164 raeburn 3693: if (lc($tagname) eq 'embed') {
3694: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3695: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3696: $attr->{'src'});
3697: }
3698: }
1.640 albertel 3699: }
1.1172.2.35 raeburn 3700: if (lc($tagname) eq 'iframe') {
3701: my $src = $attr->{'src'} ;
3702: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3703: &add_filetype($allfiles,$src,'src');
3704: } elsif ($src =~ m{^/}) {
3705: if ($env{'request.course.id'}) {
3706: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3707: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3708: my $url = &hreflocation('',$fullpath);
3709: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3710: my $relpath = $1;
3711: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3712: &add_filetype($allfiles,$1,'src');
3713: }
3714: }
3715: }
3716: }
3717: }
1.1164 raeburn 3718: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3719: pop(@state);
1.1164 raeburn 3720: }
1.640 albertel 3721: } elsif ($t->[0] eq 'E') {
3722: my ($tagname) = ($t->[1]);
3723: if ($javafiles{'codebase'} ne '') {
3724: $javafiles{'codebase'} .= '/';
3725: }
3726: if (lc($tagname) eq 'applet' ||
3727: lc($tagname) eq 'object' ||
3728: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3729: ) {
3730: foreach my $item (keys(%javafiles)) {
3731: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3732: my $file=$javafiles{'codebase'}.$javafiles{$item};
3733: &add_filetype($allfiles,$file,$item);
3734: }
3735: }
3736: }
3737: pop @state;
3738: }
3739: }
1.1164 raeburn 3740: foreach my $id (sort(keys(%flashvars))) {
3741: if ($shockwave{$id} ne '') {
3742: my @pairs = split(/\&/,$flashvars{$id});
3743: foreach my $pair (@pairs) {
3744: my ($key,$value) = split(/\=/,$pair);
3745: if ($key eq 'thumb') {
3746: &add_filetype($allfiles,$value,$key);
3747: } elsif ($key eq 'content') {
3748: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3749: my ($ext) = ($value =~ /\.([^.]+)$/);
3750: if ($ext ne '') {
3751: &add_filetype($allfiles,$path.$value,$ext);
3752: }
3753: }
3754: }
3755: }
3756: }
1.637 raeburn 3757: return 'ok';
3758: }
3759:
1.639 albertel 3760: sub add_filetype {
3761: my ($allfiles,$file,$type)=@_;
3762: if (exists($allfiles->{$file})) {
3763: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3764: push(@{$allfiles->{$file}}, &escape($type));
3765: }
3766: } else {
3767: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3768: }
3769: }
3770:
1.1164 raeburn 3771: sub embedded_dependency {
3772: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3773: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3774: if (($identifier ne '') &&
3775: (ref($related->{$identifier}) eq 'ARRAY') &&
3776: ($pathfrom ne '')) {
3777: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3778: foreach my $dep (@{$related->{$identifier}}) {
3779: &add_filetype($allfiles,$path.$dep,'object');
3780: }
3781: }
3782: }
3783: return;
3784: }
3785:
1.493 albertel 3786: sub removeuploadedurl {
1.984 neumanie 3787: my ($url)=@_;
3788: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3789: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3790: }
3791:
3792: sub removeuserfile {
3793: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3794: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3795: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3796: if ($result eq 'ok') {
1.798 raeburn 3797: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3798: my $metafile = $fname.'.meta';
3799: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3800: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3801: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3802: my $sqlresult =
1.823 albertel 3803: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3804: 'portfolio_metadata',$group,
3805: 'delete');
1.798 raeburn 3806: }
3807: }
3808: return $result;
1.257 www 3809: }
1.15 www 3810:
1.530 albertel 3811: sub mkdiruserfile {
3812: my ($docuname,$docudom,$dir)=@_;
3813: my $home=&homeserver($docuname,$docudom);
3814: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3815: }
3816:
1.531 albertel 3817: sub renameuserfile {
3818: my ($docuname,$docudom,$old,$new)=@_;
3819: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3820: my $result = &reply("renameuserfile:$docudom:$docuname:".
3821: &escape("$old").':'.&escape("$new"),$home);
3822: if ($result eq 'ok') {
3823: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3824: my $oldmeta = $old.'.meta';
3825: my $newmeta = $new.'.meta';
3826: my $metaresult =
3827: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3828: my $url = "/uploaded/$docudom/$docuname/$old";
3829: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3830: my $sqlresult =
1.823 albertel 3831: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3832: 'portfolio_metadata',$group,
3833: 'delete');
1.798 raeburn 3834: }
3835: }
3836: return $result;
1.531 albertel 3837: }
3838:
1.14 www 3839: # ------------------------------------------------------------------------- Log
3840:
3841: sub log {
3842: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3843: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3844: }
3845:
3846: # ------------------------------------------------------------------ Course Log
1.352 www 3847: #
3848: # This routine flushes several buffers of non-mission-critical nature
3849: #
1.157 www 3850:
3851: sub flushcourselogs {
1.352 www 3852: &logthis('Flushing log buffers');
3853: #
3854: # course logs
3855: # This is a log of all transactions in a course, which can be used
3856: # for data mining purposes
3857: #
3858: # It also collects the courseid database, which lists last transaction
3859: # times and course titles for all courseids
3860: #
3861: my %courseidbuffer=();
1.921 raeburn 3862: foreach my $crsid (keys(%courselogs)) {
1.352 www 3863: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3864: &escape($courselogs{$crsid}),
3865: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3866: delete $courselogs{$crsid};
3867: } else {
3868: &logthis('Failed to flush log buffer for '.$crsid);
3869: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3870: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3871: " exceeded maximum size, deleting.</font>");
3872: delete $courselogs{$crsid};
3873: }
1.352 www 3874: }
1.920 raeburn 3875: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3876: 'description' => $coursedescrbuf{$crsid},
3877: 'inst_code' => $courseinstcodebuf{$crsid},
3878: 'type' => $coursetypebuf{$crsid},
3879: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3880: };
1.191 harris41 3881: }
1.352 www 3882: #
3883: # Write course id database (reverse lookup) to homeserver of courses
3884: # Is used in pickcourse
3885: #
1.840 albertel 3886: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3887: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3888: $courseidbuffer{$crs_home},
3889: $crs_home,'timeonly');
1.352 www 3890: }
3891: #
3892: # File accesses
3893: # Writes to the dynamic metadata of resources to get hit counts, etc.
3894: #
1.449 matthew 3895: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3896: if ($entry =~ /___count$/) {
3897: my ($dom,$name);
1.807 albertel 3898: ($dom,$name,undef)=
1.811 albertel 3899: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3900: if (! defined($dom) || $dom eq '' ||
3901: ! defined($name) || $name eq '') {
1.620 albertel 3902: my $cid = $env{'request.course.id'};
3903: $dom = $env{'request.'.$cid.'.domain'};
3904: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3905: }
1.450 matthew 3906: my $value = $accesshash{$entry};
3907: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3908: my %temphash=($url => $value);
1.449 matthew 3909: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3910: if ($result eq 'ok') {
3911: delete $accesshash{$entry};
3912: }
3913: } else {
1.811 albertel 3914: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3915: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3916: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3917: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3918: delete $accesshash{$entry};
3919: }
1.185 www 3920: }
1.191 harris41 3921: }
1.352 www 3922: #
3923: # Roles
3924: # Reverse lookup of user roles for course faculty/staff and co-authorship
3925: #
1.800 albertel 3926: foreach my $entry (keys(%userrolehash)) {
1.351 www 3927: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3928: split(/\:/,$entry);
3929: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3930: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3931: $rudom,$runame) eq 'ok') {
3932: delete $userrolehash{$entry};
3933: }
3934: }
1.662 raeburn 3935: #
1.1172.2.90 raeburn 3936: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 3937: #
3938: my %domrolebuffer = ();
1.1000 raeburn 3939: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3940: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3941: if ($domrolebuffer{$rudom}) {
3942: $domrolebuffer{$rudom}.='&'.&escape($entry).
3943: '='.&escape($domainrolehash{$entry});
3944: } else {
3945: $domrolebuffer{$rudom}.=&escape($entry).
3946: '='.&escape($domainrolehash{$entry});
3947: }
3948: delete $domainrolehash{$entry};
3949: }
3950: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 3951: my %servers;
3952: if (defined(&domain($dom,'primary'))) {
3953: my $primary=&domain($dom,'primary');
3954: my $hostname=&hostname($primary);
3955: $servers{$primary} = $hostname;
3956: } else {
3957: %servers = &get_servers($dom,'library');
3958: }
1.841 albertel 3959: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 3960: if (&reply('domroleput:'.$dom.':'.
3961: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3962: last;
3963: } else {
1.841 albertel 3964: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3965: }
1.662 raeburn 3966: }
3967: }
1.186 www 3968: $dumpcount++;
1.157 www 3969: }
3970:
3971: sub courselog {
3972: my $what=shift;
1.158 www 3973: $what=time.':'.$what;
1.620 albertel 3974: unless ($env{'request.course.id'}) { return ''; }
3975: $coursedombuf{$env{'request.course.id'}}=
3976: $env{'course.'.$env{'request.course.id'}.'.domain'};
3977: $coursenumbuf{$env{'request.course.id'}}=
3978: $env{'course.'.$env{'request.course.id'}.'.num'};
3979: $coursehombuf{$env{'request.course.id'}}=
3980: $env{'course.'.$env{'request.course.id'}.'.home'};
3981: $coursedescrbuf{$env{'request.course.id'}}=
3982: $env{'course.'.$env{'request.course.id'}.'.description'};
3983: $courseinstcodebuf{$env{'request.course.id'}}=
3984: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3985: $courseownerbuf{$env{'request.course.id'}}=
3986: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3987: $coursetypebuf{$env{'request.course.id'}}=
3988: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3989: if (defined $courselogs{$env{'request.course.id'}}) {
3990: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3991: } else {
1.620 albertel 3992: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3993: }
1.620 albertel 3994: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3995: &flushcourselogs();
3996: }
1.158 www 3997: }
3998:
3999: sub courseacclog {
4000: my $fnsymb=shift;
1.620 albertel 4001: unless ($env{'request.course.id'}) { return ''; }
4002: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4003: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4004: $what.=':POST';
1.583 matthew 4005: # FIXME: Probably ought to escape things....
1.800 albertel 4006: foreach my $key (keys(%env)) {
4007: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4008: my $formitem = $1;
4009: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4010: $what.=':'.$formitem.'='.$env{$key};
4011: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4012: $what.=':'.$formitem.'='.$env{$key};
4013: }
1.158 www 4014: }
1.191 harris41 4015: }
1.583 matthew 4016: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4017: # FIXME: We should not be depending on a form parameter that someone
4018: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4019: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4020: $what.= ':POST';
4021: # FIXME: Probably ought to escape things....
4022: foreach my $element ('courseexp','crsfulltext','crsrelated',
4023: 'crsdiscuss') {
1.620 albertel 4024: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4025: }
4026: }
1.158 www 4027: }
4028: &courselog($what);
1.149 www 4029: }
4030:
1.185 www 4031: sub countacc {
4032: my $url=&declutter(shift);
1.458 matthew 4033: return if (! defined($url) || $url eq '');
1.620 albertel 4034: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4035: #
4036: # Mark that this url was used in this course
4037: #
1.620 albertel 4038: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4039: #
4040: # Increase the access count for this resource in this child process
4041: #
1.281 www 4042: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4043: $accesshash{$key}++;
1.185 www 4044: }
1.349 www 4045:
1.361 www 4046: sub linklog {
4047: my ($from,$to)=@_;
4048: $from=&declutter($from);
4049: $to=&declutter($to);
4050: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4051: $accesshash{$to.'___'.$from.'___goto'}=1;
4052: }
1.1160 www 4053:
4054: sub statslog {
4055: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4056: if ($users<2) { return; }
4057: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4058: 'course' => $env{'request.course.id'},
4059: 'sections' => '"all"',
4060: 'num_students' => $users,
4061: 'part' => $part,
4062: 'symb' => $symb,
4063: 'mean_tries' => $av_attempts,
4064: 'deg_of_diff' => $degdiff});
4065: foreach my $key (keys(%dynstore)) {
4066: $accesshash{$key}=$dynstore{$key};
4067: }
4068: }
1.361 www 4069:
1.349 www 4070: sub userrolelog {
4071: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4072: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4073: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4074: $userrolehash
4075: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4076: =$tend.':'.$tstart;
1.662 raeburn 4077: }
1.1169 droeschl 4078: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4079: $userrolehash
4080: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4081: =$tend.':'.$tstart;
4082: }
1.1172.2.90 raeburn 4083: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4084: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4085: $domainrolehash
4086: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4087: = $tend.':'.$tstart;
4088: }
1.351 www 4089: }
4090:
1.957 raeburn 4091: sub courserolelog {
4092: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4093: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4094: my $cdom = $1;
4095: my $cnum = $2;
4096: my $sec = $3;
4097: my $namespace = 'rolelog';
4098: my %storehash = (
4099: role => $trole,
4100: start => $tstart,
4101: end => $tend,
4102: selfenroll => $selfenroll,
4103: context => $context,
4104: );
4105: if ($trole eq 'gr') {
4106: $namespace = 'groupslog';
4107: $storehash{'group'} = $sec;
4108: } else {
4109: $storehash{'section'} = $sec;
4110: }
4111: &write_log('course',$namespace,\%storehash,$delflag,$username,
4112: $domain,$cnum,$cdom);
4113: if (($trole ne 'st') || ($sec ne '')) {
4114: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4115: }
4116: }
4117: return;
4118: }
4119:
1.1172.2.9 raeburn 4120: sub domainrolelog {
4121: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4122: if ($area =~ m{^/($match_domain)/$}) {
4123: my $cdom = $1;
4124: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4125: my $namespace = 'rolelog';
4126: my %storehash = (
4127: role => $trole,
4128: start => $tstart,
4129: end => $tend,
4130: context => $context,
4131: );
4132: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4133: $domain,$domconfiguser,$cdom);
4134: }
4135: return;
4136:
4137: }
4138:
4139: sub coauthorrolelog {
4140: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4141: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4142: my $audom = $1;
4143: my $auname = $2;
4144: my $namespace = 'rolelog';
4145: my %storehash = (
4146: role => $trole,
4147: start => $tstart,
4148: end => $tend,
4149: context => $context,
4150: );
4151: &write_log('author',$namespace,\%storehash,$delflag,$username,
4152: $domain,$auname,$audom);
4153: }
4154: return;
4155: }
4156:
1.351 www 4157: sub get_course_adv_roles {
1.948 raeburn 4158: my ($cid,$codes) = @_;
1.620 albertel 4159: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4160: my %coursehash=&coursedescription($cid);
1.988 raeburn 4161: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4162: my %nothide=();
1.800 albertel 4163: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4164: if ($user !~ /:/) {
4165: $nothide{join(':',split(/[\@]/,$user))}=1;
4166: } else {
4167: $nothide{$user}=1;
4168: }
1.470 www 4169: }
1.1172.2.23 raeburn 4170: my @possdoms = ($coursehash{'domain'});
4171: if ($coursehash{'checkforpriv'}) {
4172: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4173: }
1.351 www 4174: my %returnhash=();
4175: my %dumphash=
4176: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4177: my $now=time;
1.997 raeburn 4178: my %privileged;
1.1000 raeburn 4179: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4180: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4181: if (($tstart) && ($tstart<0)) { next; }
4182: if (($tend) && ($tend<$now)) { next; }
4183: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4184: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4185: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4186: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4187: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4188: if ($role eq 'cr') { next; }
1.948 raeburn 4189: if ($codes) {
4190: if ($section) { $role .= ':'.$section; }
4191: if ($returnhash{$role}) {
4192: $returnhash{$role}.=','.$username.':'.$domain;
4193: } else {
4194: $returnhash{$role}=$username.':'.$domain;
4195: }
1.351 www 4196: } else {
1.988 raeburn 4197: my $key=&plaintext($role,$crstype);
1.973 bisitz 4198: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4199: if ($returnhash{$key}) {
4200: $returnhash{$key}.=','.$username.':'.$domain;
4201: } else {
4202: $returnhash{$key}=$username.':'.$domain;
4203: }
1.351 www 4204: }
1.948 raeburn 4205: }
1.400 www 4206: return %returnhash;
4207: }
4208:
4209: sub get_my_roles {
1.937 raeburn 4210: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4211: unless (defined($uname)) { $uname=$env{'user.name'}; }
4212: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4213: my (%dumphash,%nothide);
1.1086 raeburn 4214: if ($context eq 'userroles') {
1.1166 raeburn 4215: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4216: } else {
1.1172.2.23 raeburn 4217: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4218: if ($hidepriv) {
4219: my %coursehash=&coursedescription($udom.'_'.$uname);
4220: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4221: if ($user !~ /:/) {
4222: $nothide{join(':',split(/[\@]/,$user))} = 1;
4223: } else {
4224: $nothide{$user} = 1;
4225: }
4226: }
4227: }
1.858 raeburn 4228: }
1.400 www 4229: my %returnhash=();
4230: my $now=time;
1.999 raeburn 4231: my %privileged;
1.800 albertel 4232: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4233: my ($role,$tend,$tstart);
4234: if ($context eq 'userroles') {
1.1149 raeburn 4235: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4236: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4237: } else {
4238: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4239: }
1.400 www 4240: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4241: my $status = 'active';
1.939 raeburn 4242: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4243: $status = 'previous';
4244: }
4245: if (($tstart) && ($now<$tstart)) {
4246: $status = 'future';
4247: }
4248: if (ref($types) eq 'ARRAY') {
4249: if (!grep(/^\Q$status\E$/,@{$types})) {
4250: next;
4251: }
4252: } else {
4253: if ($status ne 'active') {
4254: next;
4255: }
4256: }
1.867 raeburn 4257: my ($rolecode,$username,$domain,$section,$area);
4258: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4259: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4260: (undef,$domain,$username,$section) = split(/\//,$area);
4261: } else {
4262: ($role,$username,$domain,$section) = split(/\:/,$entry);
4263: }
1.832 raeburn 4264: if (ref($roledoms) eq 'ARRAY') {
4265: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4266: next;
4267: }
4268: }
4269: if (ref($roles) eq 'ARRAY') {
4270: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4271: if ($role =~ /^cr\//) {
4272: if (!grep(/^cr$/,@{$roles})) {
4273: next;
4274: }
1.1104 raeburn 4275: } elsif ($role =~ /^gr\//) {
4276: if (!grep(/^gr$/,@{$roles})) {
4277: next;
4278: }
1.922 raeburn 4279: } else {
4280: next;
4281: }
1.832 raeburn 4282: }
1.867 raeburn 4283: }
1.937 raeburn 4284: if ($hidepriv) {
1.1172.2.23 raeburn 4285: my @privroles = ('dc','su');
1.999 raeburn 4286: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4287: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4288: } else {
1.1172.2.23 raeburn 4289: my $possdoms = [$domain];
4290: if (ref($roledoms) eq 'ARRAY') {
4291: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4292: }
1.1172.2.23 raeburn 4293: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4294: if (!$nothide{$username.':'.$domain}) {
4295: next;
4296: }
4297: }
1.937 raeburn 4298: }
4299: }
1.933 raeburn 4300: if ($withsec) {
4301: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4302: $tstart.':'.$tend;
4303: } else {
4304: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4305: }
1.832 raeburn 4306: }
1.373 www 4307: return %returnhash;
1.399 www 4308: }
4309:
1.1172.2.89 raeburn 4310: sub get_all_adhocroles {
4311: my ($dom) = @_;
4312: my @roles_by_num = ();
4313: my %domdefaults = &get_domain_defaults($dom);
4314: my (%description,%access_in_dom,%access_info);
4315: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4316: my $count = 0;
4317: my %domcurrent = %{$domdefaults{'adhocroles'}};
4318: my %ordered;
4319: foreach my $role (sort(keys(%domcurrent))) {
4320: my ($order,$desc,$access_in_dom);
4321: if (ref($domcurrent{$role}) eq 'HASH') {
4322: $order = $domcurrent{$role}{'order'};
4323: $desc = $domcurrent{$role}{'desc'};
4324: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4325: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4326: }
4327: if ($order eq '') {
4328: $order = $count;
4329: }
4330: $ordered{$order} = $role;
4331: if ($desc ne '') {
4332: $description{$role} = $desc;
4333: } else {
4334: $description{$role}= $role;
4335: }
4336: $count++;
4337: }
4338: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4339: push(@roles_by_num,$ordered{$item});
4340: }
4341: }
4342: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4343: }
4344:
4345: sub get_my_adhocroles {
4346: my ($cid,$checkreg) = @_;
4347: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4348: if ($env{'request.course.id'} eq $cid) {
4349: $cdom = $env{'course.'.$cid.'.domain'};
4350: $cnum = $env{'course.'.$cid.'.num'};
4351: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4352: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4353: $cdom = $1;
4354: $cnum = $2;
4355: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4356: $cdom,$cnum);
4357: }
4358: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4359: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4360: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4361: if ($rosterhash{$user} ne '') {
4362: my $type = (split(/:/,$rosterhash{$user}))[5];
4363: return ([],{}) if ($type eq 'auto');
4364: }
4365: }
4366: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4367: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4368: my $then=$env{'user.login.time'};
4369: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4370: if (!$update) {
4371: $update = $then;
4372: }
4373: my @liveroles;
4374: foreach my $role ('dh','da') {
4375: if ($env{"user.role.$role./$cdom/"}) {
4376: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4377: my $limit = $update;
4378: if ($env{'request.role'} eq "$role./$cdom/") {
4379: $limit = $then;
4380: }
4381: my $activerole = 1;
4382: if ($tstart && $tstart>$limit) { $activerole = 0; }
4383: if ($tend && $tend <$limit) { $activerole = 0; }
4384: if ($activerole) {
4385: push(@liveroles,$role);
4386: }
4387: }
4388: }
4389: if (@liveroles) {
1.1172.2.89 raeburn 4390: if (&homeserver($cnum,$cdom) ne 'no_host') {
4391: my ($accessref,$accessinfo,%access_in_dom);
4392: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4393: if (ref($roles_by_num) eq 'ARRAY') {
4394: if (@{$roles_by_num}) {
4395: my %settings;
4396: if ($env{'request.course.id'} eq $cid) {
4397: foreach my $envkey (keys(%env)) {
4398: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4399: $settings{$1} = $env{$envkey};
4400: }
4401: }
4402: } else {
4403: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4404: }
4405: my %setincrs;
4406: if ($settings{'internal.adhocaccess'}) {
4407: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4408: }
4409: my @statuses;
4410: if ($env{'environment.inststatus'}) {
4411: @statuses = split(/,/,$env{'environment.inststatus'});
4412: }
4413: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4414: if (ref($accessref) eq 'HASH') {
4415: %access_in_dom = %{$accessref};
4416: }
4417: foreach my $role (@{$roles_by_num}) {
4418: my ($curraccess,@okstatus,@personnel);
4419: if ($setincrs{$role}) {
4420: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4421: if ($curraccess eq 'status') {
4422: @okstatus = split(/\&/,$rest);
4423: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4424: @personnel = split(/\&/,$rest);
4425: }
4426: } else {
4427: $curraccess = $access_in_dom{$role};
4428: if (ref($accessinfo) eq 'HASH') {
4429: if ($curraccess eq 'status') {
4430: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4431: @okstatus = @{$accessinfo->{$role}};
4432: }
4433: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4434: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4435: @personnel = @{$accessinfo->{$role}};
4436: }
4437: }
4438: }
4439: }
4440: if ($curraccess eq 'none') {
4441: next;
4442: } elsif ($curraccess eq 'all') {
4443: push(@possroles,$role);
1.1172.2.90 raeburn 4444: } elsif ($curraccess eq 'dh') {
4445: if (grep(/^dh$/,@liveroles)) {
4446: push(@possroles,$role);
4447: } else {
4448: next;
4449: }
4450: } elsif ($curraccess eq 'da') {
4451: if (grep(/^da$/,@liveroles)) {
4452: push(@possroles,$role);
4453: } else {
4454: next;
4455: }
1.1172.2.89 raeburn 4456: } elsif ($curraccess eq 'status') {
4457: if (@okstatus) {
4458: if (!@statuses) {
4459: if (grep(/^default$/,@okstatus)) {
4460: push(@possroles,$role);
4461: }
4462: } else {
4463: foreach my $status (@okstatus) {
4464: if (grep(/^\Q$status\E$/,@statuses)) {
4465: push(@possroles,$role);
4466: last;
4467: }
4468: }
4469: }
4470: }
4471: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4472: if (grep(/^\Q$user\E$/,@personnel)) {
4473: if ($curraccess eq 'exc') {
4474: push(@possroles,$role);
4475: }
4476: } elsif ($curraccess eq 'inc') {
4477: push(@possroles,$role);
4478: }
4479: }
4480: }
4481: }
4482: }
4483: }
4484: }
4485: }
4486: }
4487: unless (ref($description) eq 'HASH') {
4488: if (ref($roles_by_num) eq 'ARRAY') {
4489: my %desc;
4490: map { $desc{$_} = $_; } (@{$roles_by_num});
4491: $description = \%desc;
4492: } else {
4493: $description = {};
4494: }
4495: }
4496: return (\@possroles,$description);
4497: }
4498:
1.399 www 4499: # ----------------------------------------------------- Frontpage Announcements
4500: #
4501: #
4502:
4503: sub postannounce {
4504: my ($server,$text)=@_;
1.844 albertel 4505: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4506: unless ($text=~/\w/) { $text=''; }
4507: return &reply('setannounce:'.&escape($text),$server);
4508: }
4509:
4510: sub getannounce {
1.448 albertel 4511:
1.1172.2.96! raeburn 4512: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4513: my $announcement='';
1.800 albertel 4514: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4515: close($fh);
1.399 www 4516: if ($announcement=~/\w/) {
4517: return
4518: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4519: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4520: } else {
4521: return '';
4522: }
4523: } else {
4524: return '';
4525: }
1.351 www 4526: }
1.353 www 4527:
4528: # ---------------------------------------------------------- Course ID routines
4529: # Deal with domain's nohist_courseid.db files
4530: #
4531:
4532: sub courseidput {
1.921 raeburn 4533: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4534: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4535: my $outcome;
4536: if ($caller eq 'timeonly') {
4537: my $cids = '';
4538: foreach my $item (keys(%$storehash)) {
4539: $cids.=&escape($item).'&';
4540: }
4541: $cids=~s/\&$//;
4542: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4543: $coursehome);
4544: } else {
4545: my $items = '';
4546: foreach my $item (keys(%$storehash)) {
4547: $items.= &escape($item).'='.
4548: &freeze_escape($$storehash{$item}).'&';
4549: }
4550: $items=~s/\&$//;
4551: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4552: $coursehome);
1.918 raeburn 4553: }
4554: if ($outcome eq 'unknown_cmd') {
4555: my $what;
4556: foreach my $cid (keys(%$storehash)) {
4557: $what .= &escape($cid).'=';
1.921 raeburn 4558: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4559: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4560: }
4561: $what =~ s/\:$/&/;
4562: }
4563: $what =~ s/\&$//;
4564: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4565: } else {
4566: return $outcome;
4567: }
1.353 www 4568: }
4569:
4570: sub courseiddump {
1.921 raeburn 4571: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4572: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4573: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4574: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4575: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4576: my $as_hash = 1;
4577: my %returnhash;
4578: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4579: my %libserv = &all_library();
4580: foreach my $tryserver (keys(%libserv)) {
4581: if ( ( $hostidflag == 1
4582: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4583: || (!defined($hostidflag)) ) {
4584:
1.918 raeburn 4585: if (($domfilter eq '') ||
4586: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4587: my $rep;
4588: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4589: $rep = &LONCAPA::Lond::dump_course_id_handler(
4590: join(":", (&host_domain($tryserver), $sincefilter,
4591: &escape($descfilter), &escape($instcodefilter),
4592: &escape($ownerfilter), &escape($coursefilter),
4593: &escape($typefilter), &escape($regexp_ok),
4594: $as_hash, &escape($selfenrollonly),
4595: &escape($catfilter), $showhidden, $caller,
4596: &escape($cloner), &escape($cc_clone), $cloneonly,
4597: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4598: &escape($creationcontext),$domcloner,$hasuniquecode,
4599: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4600: } else {
4601: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4602: $sincefilter.':'.&escape($descfilter).':'.
4603: &escape($instcodefilter).':'.&escape($ownerfilter).
4604: ':'.&escape($coursefilter).':'.&escape($typefilter).
4605: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4606: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4607: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4608: &escape($cc_clone).':'.$cloneonly.':'.
4609: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4610: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4611: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4612: }
4613:
1.918 raeburn 4614: my @pairs=split(/\&/,$rep);
4615: foreach my $item (@pairs) {
4616: my ($key,$value)=split(/\=/,$item,2);
4617: $key = &unescape($key);
4618: next if ($key =~ /^error: 2 /);
4619: my $result = &thaw_unescape($value);
4620: if (ref($result) eq 'HASH') {
4621: $returnhash{$key}=$result;
4622: } else {
1.921 raeburn 4623: my @responses = split(/:/,$value);
4624: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4625: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4626: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4627: }
1.1008 raeburn 4628: }
1.353 www 4629: }
4630: }
4631: }
4632: }
4633: return %returnhash;
4634: }
4635:
1.1055 raeburn 4636: sub courselastaccess {
4637: my ($cdom,$cnum,$hostidref) = @_;
4638: my %returnhash;
4639: if ($cdom && $cnum) {
4640: my $chome = &homeserver($cnum,$cdom);
4641: if ($chome ne 'no_host') {
4642: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4643: &extract_lastaccess(\%returnhash,$rep);
4644: }
4645: } else {
4646: if (!$cdom) { $cdom=''; }
4647: my %libserv = &all_library();
4648: foreach my $tryserver (keys(%libserv)) {
4649: if (ref($hostidref) eq 'ARRAY') {
4650: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4651: }
4652: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4653: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4654: &extract_lastaccess(\%returnhash,$rep);
4655: }
4656: }
4657: }
4658: return %returnhash;
4659: }
4660:
4661: sub extract_lastaccess {
4662: my ($returnhash,$rep) = @_;
4663: if (ref($returnhash) eq 'HASH') {
4664: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4665: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4666: $rep eq '') {
4667: my @pairs=split(/\&/,$rep);
4668: foreach my $item (@pairs) {
4669: my ($key,$value)=split(/\=/,$item,2);
4670: $key = &unescape($key);
4671: next if ($key =~ /^error: 2 /);
4672: $returnhash->{$key} = &thaw_unescape($value);
4673: }
4674: }
4675: }
4676: return;
4677: }
4678:
1.658 raeburn 4679: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4680:
4681: sub dcmailput {
1.685 raeburn 4682: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4683: my $status = &Apache::lonnet::critical(
1.740 www 4684: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4685: &escape($message),$server);
1.662 raeburn 4686: return $status;
4687: }
4688:
1.658 raeburn 4689: sub dcmaildump {
4690: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4691: my %returnhash=();
1.846 albertel 4692:
4693: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4694: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4695: &escape($enddate).':';
4696: my @esc_senders=map { &escape($_)} @$senders;
4697: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4698: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4699: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4700: if (($key) && ($value)) {
4701: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4702: }
4703: }
4704: }
4705: return %returnhash;
4706: }
1.662 raeburn 4707: # ---------------------------------------------------------- Domain roles
4708:
4709: sub get_domain_roles {
4710: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4711: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4712: $startdate = '.';
4713: }
1.1018 raeburn 4714: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4715: $enddate = '.';
4716: }
1.922 raeburn 4717: my $rolelist;
4718: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4719: $rolelist = join('&',@{$roles});
1.922 raeburn 4720: }
1.662 raeburn 4721: my %personnel = ();
1.841 albertel 4722:
4723: my %servers = &get_servers($dom,'library');
4724: foreach my $tryserver (keys(%servers)) {
4725: %{$personnel{$tryserver}}=();
4726: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4727: &escape($startdate).':'.
4728: &escape($enddate).':'.
4729: &escape($rolelist), $tryserver))) {
4730: my ($key,$value) = split(/\=/,$line,2);
4731: if (($key) && ($value)) {
4732: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4733: }
4734: }
1.662 raeburn 4735: }
4736: return %personnel;
4737: }
1.658 raeburn 4738:
1.1172.2.89 raeburn 4739: sub get_active_domroles {
4740: my ($dom,$roles) = @_;
4741: return () unless (ref($roles) eq 'ARRAY');
4742: my $now = time;
4743: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4744: my %domroles;
4745: foreach my $server (keys(%dompersonnel)) {
4746: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4747: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4748: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4749: }
4750: }
4751: return %domroles;
4752: }
4753:
1.1057 www 4754: # ----------------------------------------------------------- Interval timing
1.149 www 4755:
1.1153 www 4756: {
4757: # Caches needed for speedup of navmaps
4758: # We don't want to cache this for very long at all (5 seconds at most)
4759: #
4760: # The user for whom we cache
4761: my $cachedkey='';
4762: # The cached times for this user
4763: my %cachedtimes=();
4764: # When this was last done
1.1172.2.66 raeburn 4765: my $cachedtime='';
1.1153 www 4766:
4767: sub load_all_first_access {
1.1154 raeburn 4768: my ($uname,$udom)=@_;
1.1156 www 4769: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4770: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4771: return;
4772: }
4773: $cachedtime=time;
4774: $cachedkey=$uname.':'.$udom;
4775: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4776: }
4777:
1.504 albertel 4778: sub get_first_access {
1.1162 raeburn 4779: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4780: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4781: if ($argsymb) { $symb=$argsymb; }
4782: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4783: if ($argmap) { $map = $argmap; }
1.926 albertel 4784: if ($type eq 'course') {
4785: $res='course';
4786: } elsif ($type eq 'map') {
1.588 albertel 4787: $res=&symbread($map);
4788: } else {
4789: $res=$symb;
4790: }
1.1153 www 4791: &load_all_first_access($uname,$udom);
4792: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4793: }
4794:
4795: sub set_first_access {
1.1162 raeburn 4796: my ($type,$interval)=@_;
1.790 albertel 4797: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4798: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4799: if ($type eq 'course') {
4800: $res='course';
4801: } elsif ($type eq 'map') {
1.588 albertel 4802: $res=&symbread($map);
4803: } else {
4804: $res=$symb;
4805: }
1.1153 www 4806: $cachedkey='';
1.1162 raeburn 4807: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4808: if (!$firstaccess) {
1.1162 raeburn 4809: my $start = time;
4810: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4811: $udom,$uname);
4812: if ($putres eq 'ok') {
4813: &put('timerinterval',{"$courseid\0$res"=>$interval},
4814: $udom,$uname);
4815: &appenv(
4816: {
4817: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4818: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4819: }
4820: );
4821: }
4822: return $putres;
1.505 albertel 4823: }
4824: return 'already_set';
1.504 albertel 4825: }
1.1153 www 4826: }
1.1172.2.32 raeburn 4827:
4828: sub checkout {
4829: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4830: my $now=time;
4831: my $lonhost=$perlvar{'lonHostID'};
4832: my $infostr=&escape(
4833: 'CHECKOUTTOKEN&'.
4834: $tuname.'&'.
4835: $tudom.'&'.
4836: $tcrsid.'&'.
4837: $symb.'&'.
4838: $now.'&'.$ENV{'REMOTE_ADDR'});
4839: my $token=&reply('tmpput:'.$infostr,$lonhost);
4840: if ($token=~/^error\:/) {
4841: &logthis("<font color=\"blue\">WARNING: ".
4842: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4843: "</font>");
4844: return '';
4845: }
4846:
4847: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4848: $token=~tr/a-z/A-Z/;
4849:
4850: my %infohash=('resource.0.outtoken' => $token,
4851: 'resource.0.checkouttime' => $now,
4852: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4853:
4854: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4855: return '';
4856: } else {
4857: &logthis("<font color=\"blue\">WARNING: ".
4858: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4859: "</font>");
4860: }
4861:
4862: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4863: &escape('Checkout '.$infostr.' - '.
4864: $token)) ne 'ok') {
4865: return '';
4866: } else {
4867: &logthis("<font color=\"blue\">WARNING: ".
4868: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4869: "</font>");
4870: }
4871: return $token;
4872: }
4873:
4874: # ------------------------------------------------------------ Check in an item
4875:
4876: sub checkin {
4877: my $token=shift;
4878: my $now=time;
4879: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4880: $lonhost=~tr/A-Z/a-z/;
4881: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4882: $dtoken=~s/\W/\_/g;
4883: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4884: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4885:
4886: unless (($tuname) && ($tudom)) {
4887: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4888: return '';
4889: }
4890:
4891: unless (&allowed('mgr',$tcrsid)) {
4892: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4893: $env{'user.name'}.' - '.$env{'user.domain'});
4894: return '';
4895: }
4896:
4897: my %infohash=('resource.0.intoken' => $token,
4898: 'resource.0.checkintime' => $now,
4899: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4900:
4901: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4902: return '';
4903: }
4904:
4905: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4906: &escape('Checkin - '.$token)) ne 'ok') {
4907: return '';
4908: }
4909:
4910: return ($symb,$tuname,$tudom,$tcrsid);
4911: }
4912:
1.110 www 4913: # --------------------------------------------- Set Expire Date for Spreadsheet
4914:
4915: sub expirespread {
4916: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4917: my $cid=$env{'request.course.id'};
1.110 www 4918: if ($cid) {
4919: my $now=time;
4920: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4921: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4922: $env{'course.'.$cid.'.num'}.
1.110 www 4923: ':nohist_expirationdates:'.
4924: &escape($key).'='.$now,
1.620 albertel 4925: $env{'course.'.$cid.'.home'})
1.110 www 4926: }
4927: return 'ok';
1.14 www 4928: }
4929:
1.109 www 4930: # ----------------------------------------------------- Devalidate Spreadsheets
4931:
4932: sub devalidate {
1.325 www 4933: my ($symb,$uname,$udom)=@_;
1.620 albertel 4934: my $cid=$env{'request.course.id'};
1.109 www 4935: if ($cid) {
1.391 matthew 4936: # delete the stored spreadsheets for
4937: # - the student level sheet of this user in course's homespace
4938: # - the assessment level sheet for this resource
4939: # for this user in user's homespace
1.553 albertel 4940: # - current conditional state info
1.325 www 4941: my $key=$uname.':'.$udom.':';
1.109 www 4942: my $status=
1.299 matthew 4943: &del('nohist_calculatedsheets',
1.391 matthew 4944: [$key.'studentcalc:'],
1.620 albertel 4945: $env{'course.'.$cid.'.domain'},
4946: $env{'course.'.$cid.'.num'})
1.133 albertel 4947: .' '.
4948: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4949: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4950: unless ($status eq 'ok ok') {
4951: &logthis('Could not devalidate spreadsheet '.
1.325 www 4952: $uname.' at '.$udom.' for '.
1.109 www 4953: $symb.': '.$status);
1.133 albertel 4954: }
1.553 albertel 4955: &delenv('user.state.'.$cid);
1.109 www 4956: }
4957: }
4958:
1.265 albertel 4959: sub get_scalar {
4960: my ($string,$end) = @_;
4961: my $value;
4962: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4963: $value = $1;
4964: } elsif ($$string =~ s/^([^&]*?)&//) {
4965: $value = $1;
4966: }
4967: return &unescape($value);
4968: }
4969:
4970: sub array2str {
4971: my (@array) = @_;
4972: my $result=&arrayref2str(\@array);
4973: $result=~s/^__ARRAY_REF__//;
4974: $result=~s/__END_ARRAY_REF__$//;
4975: return $result;
4976: }
4977:
1.204 albertel 4978: sub arrayref2str {
4979: my ($arrayref) = @_;
1.265 albertel 4980: my $result='__ARRAY_REF__';
1.204 albertel 4981: foreach my $elem (@$arrayref) {
1.265 albertel 4982: if(ref($elem) eq 'ARRAY') {
4983: $result.=&arrayref2str($elem).'&';
4984: } elsif(ref($elem) eq 'HASH') {
4985: $result.=&hashref2str($elem).'&';
4986: } elsif(ref($elem)) {
4987: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4988: } else {
4989: $result.=&escape($elem).'&';
4990: }
4991: }
4992: $result=~s/\&$//;
1.265 albertel 4993: $result .= '__END_ARRAY_REF__';
1.204 albertel 4994: return $result;
4995: }
4996:
1.168 albertel 4997: sub hash2str {
1.204 albertel 4998: my (%hash) = @_;
4999: my $result=&hashref2str(\%hash);
1.265 albertel 5000: $result=~s/^__HASH_REF__//;
5001: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5002: return $result;
5003: }
5004:
5005: sub hashref2str {
5006: my ($hashref)=@_;
1.265 albertel 5007: my $result='__HASH_REF__';
1.800 albertel 5008: foreach my $key (sort(keys(%$hashref))) {
5009: if (ref($key) eq 'ARRAY') {
5010: $result.=&arrayref2str($key).'=';
5011: } elsif (ref($key) eq 'HASH') {
5012: $result.=&hashref2str($key).'=';
5013: } elsif (ref($key)) {
1.265 albertel 5014: $result.='=';
1.800 albertel 5015: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5016: } else {
1.1132 raeburn 5017: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5018: }
5019:
1.800 albertel 5020: if(ref($hashref->{$key}) eq 'ARRAY') {
5021: $result.=&arrayref2str($hashref->{$key}).'&';
5022: } elsif(ref($hashref->{$key}) eq 'HASH') {
5023: $result.=&hashref2str($hashref->{$key}).'&';
5024: } elsif(ref($hashref->{$key})) {
1.265 albertel 5025: $result.='&';
1.800 albertel 5026: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5027: } else {
1.800 albertel 5028: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5029: }
5030: }
1.168 albertel 5031: $result=~s/\&$//;
1.265 albertel 5032: $result .= '__END_HASH_REF__';
1.168 albertel 5033: return $result;
5034: }
5035:
5036: sub str2hash {
1.265 albertel 5037: my ($string)=@_;
5038: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5039: return %$hash;
5040: }
5041:
5042: sub str2hashref {
1.168 albertel 5043: my ($string) = @_;
1.265 albertel 5044:
5045: my %hash;
5046:
5047: if($string !~ /^__HASH_REF__/) {
5048: if (! ($string eq '' || !defined($string))) {
5049: $hash{'error'}='Not hash reference';
5050: }
5051: return (\%hash, $string);
5052: }
5053:
5054: $string =~ s/^__HASH_REF__//;
5055:
5056: while($string !~ /^__END_HASH_REF__/) {
5057: #key
5058: my $key='';
5059: if($string =~ /^__HASH_REF__/) {
5060: ($key, $string)=&str2hashref($string);
5061: if(defined($key->{'error'})) {
5062: $hash{'error'}='Bad data';
5063: return (\%hash, $string);
5064: }
5065: } elsif($string =~ /^__ARRAY_REF__/) {
5066: ($key, $string)=&str2arrayref($string);
5067: if($key->[0] eq 'Array reference error') {
5068: $hash{'error'}='Bad data';
5069: return (\%hash, $string);
5070: }
5071: } else {
5072: $string =~ s/^(.*?)=//;
1.267 albertel 5073: $key=&unescape($1);
1.265 albertel 5074: }
5075: $string =~ s/^=//;
5076:
5077: #value
5078: my $value='';
5079: if($string =~ /^__HASH_REF__/) {
5080: ($value, $string)=&str2hashref($string);
5081: if(defined($value->{'error'})) {
5082: $hash{'error'}='Bad data';
5083: return (\%hash, $string);
5084: }
5085: } elsif($string =~ /^__ARRAY_REF__/) {
5086: ($value, $string)=&str2arrayref($string);
5087: if($value->[0] eq 'Array reference error') {
5088: $hash{'error'}='Bad data';
5089: return (\%hash, $string);
5090: }
5091: } else {
5092: $value=&get_scalar(\$string,'__END_HASH_REF__');
5093: }
5094: $string =~ s/^&//;
5095:
5096: $hash{$key}=$value;
1.204 albertel 5097: }
1.265 albertel 5098:
5099: $string =~ s/^__END_HASH_REF__//;
5100:
5101: return (\%hash, $string);
1.204 albertel 5102: }
5103:
5104: sub str2array {
1.265 albertel 5105: my ($string)=@_;
5106: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5107: return @$array;
5108: }
5109:
5110: sub str2arrayref {
1.204 albertel 5111: my ($string) = @_;
1.265 albertel 5112: my @array;
5113:
5114: if($string !~ /^__ARRAY_REF__/) {
5115: if (! ($string eq '' || !defined($string))) {
5116: $array[0]='Array reference error';
5117: }
5118: return (\@array, $string);
5119: }
5120:
5121: $string =~ s/^__ARRAY_REF__//;
5122:
5123: while($string !~ /^__END_ARRAY_REF__/) {
5124: my $value='';
5125: if($string =~ /^__HASH_REF__/) {
5126: ($value, $string)=&str2hashref($string);
5127: if(defined($value->{'error'})) {
5128: $array[0] ='Array reference error';
5129: return (\@array, $string);
5130: }
5131: } elsif($string =~ /^__ARRAY_REF__/) {
5132: ($value, $string)=&str2arrayref($string);
5133: if($value->[0] eq 'Array reference error') {
5134: $array[0] ='Array reference error';
5135: return (\@array, $string);
5136: }
5137: } else {
5138: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5139: }
5140: $string =~ s/^&//;
5141:
5142: push(@array, $value);
1.191 harris41 5143: }
1.265 albertel 5144:
5145: $string =~ s/^__END_ARRAY_REF__//;
5146:
5147: return (\@array, $string);
1.168 albertel 5148: }
5149:
1.167 albertel 5150: # -------------------------------------------------------------------Temp Store
5151:
1.168 albertel 5152: sub tmpreset {
5153: my ($symb,$namespace,$domain,$stuname) = @_;
5154: if (!$symb) {
5155: $symb=&symbread();
1.620 albertel 5156: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5157: }
5158: $symb=escape($symb);
5159:
1.620 albertel 5160: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5161: $namespace=~s/\//\_/g;
5162: $namespace=~s/\W//g;
5163:
1.620 albertel 5164: if (!$domain) { $domain=$env{'user.domain'}; }
5165: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5166: if ($domain eq 'public' && $stuname eq 'public') {
5167: $stuname=$ENV{'REMOTE_ADDR'};
5168: }
1.1117 foxr 5169: my $path=LONCAPA::tempdir();
1.168 albertel 5170: my %hash;
5171: if (tie(%hash,'GDBM_File',
5172: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5173: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5174: foreach my $key (keys(%hash)) {
1.180 albertel 5175: if ($key=~ /:$symb/) {
1.168 albertel 5176: delete($hash{$key});
5177: }
5178: }
5179: }
5180: }
5181:
1.167 albertel 5182: sub tmpstore {
1.168 albertel 5183: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5184:
5185: if (!$symb) {
5186: $symb=&symbread();
1.620 albertel 5187: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5188: }
5189: $symb=escape($symb);
5190:
5191: if (!$namespace) {
5192: # I don't think we would ever want to store this for a course.
5193: # it seems this will only be used if we don't have a course.
1.620 albertel 5194: #$namespace=$env{'request.course.id'};
1.168 albertel 5195: #if (!$namespace) {
1.620 albertel 5196: $namespace=$env{'request.state'};
1.168 albertel 5197: #}
5198: }
5199: $namespace=~s/\//\_/g;
5200: $namespace=~s/\W//g;
1.620 albertel 5201: if (!$domain) { $domain=$env{'user.domain'}; }
5202: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5203: if ($domain eq 'public' && $stuname eq 'public') {
5204: $stuname=$ENV{'REMOTE_ADDR'};
5205: }
1.168 albertel 5206: my $now=time;
5207: my %hash;
1.1117 foxr 5208: my $path=LONCAPA::tempdir();
1.168 albertel 5209: if (tie(%hash,'GDBM_File',
5210: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5211: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5212: $hash{"version:$symb"}++;
5213: my $version=$hash{"version:$symb"};
5214: my $allkeys='';
5215: foreach my $key (keys(%$storehash)) {
5216: $allkeys.=$key.':';
1.591 albertel 5217: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5218: }
5219: $hash{"$version:$symb:timestamp"}=$now;
5220: $allkeys.='timestamp';
5221: $hash{"$version:keys:$symb"}=$allkeys;
5222: if (untie(%hash)) {
5223: return 'ok';
5224: } else {
5225: return "error:$!";
5226: }
5227: } else {
5228: return "error:$!";
5229: }
5230: }
1.167 albertel 5231:
1.168 albertel 5232: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5233:
1.168 albertel 5234: sub tmprestore {
5235: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5236:
1.168 albertel 5237: if (!$symb) {
5238: $symb=&symbread();
1.620 albertel 5239: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5240: }
5241: $symb=escape($symb);
5242:
1.620 albertel 5243: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5244:
1.620 albertel 5245: if (!$domain) { $domain=$env{'user.domain'}; }
5246: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5247: if ($domain eq 'public' && $stuname eq 'public') {
5248: $stuname=$ENV{'REMOTE_ADDR'};
5249: }
1.168 albertel 5250: my %returnhash;
5251: $namespace=~s/\//\_/g;
5252: $namespace=~s/\W//g;
5253: my %hash;
1.1117 foxr 5254: my $path=LONCAPA::tempdir();
1.168 albertel 5255: if (tie(%hash,'GDBM_File',
5256: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5257: &GDBM_READER(),0640)) {
1.168 albertel 5258: my $version=$hash{"version:$symb"};
5259: $returnhash{'version'}=$version;
5260: my $scope;
5261: for ($scope=1;$scope<=$version;$scope++) {
5262: my $vkeys=$hash{"$scope:keys:$symb"};
5263: my @keys=split(/:/,$vkeys);
5264: my $key;
5265: $returnhash{"$scope:keys"}=$vkeys;
5266: foreach $key (@keys) {
1.591 albertel 5267: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5268: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5269: }
5270: }
1.168 albertel 5271: if (!(untie(%hash))) {
5272: return "error:$!";
5273: }
5274: } else {
5275: return "error:$!";
5276: }
5277: return %returnhash;
1.167 albertel 5278: }
5279:
1.9 www 5280: # ----------------------------------------------------------------------- Store
5281:
5282: sub store {
1.1172.2.64 raeburn 5283: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5284: my $home='';
5285:
1.168 albertel 5286: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5287:
1.213 www 5288: $symb=&symbclean($symb);
1.122 albertel 5289: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5290:
1.620 albertel 5291: if (!$domain) { $domain=$env{'user.domain'}; }
5292: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5293:
5294: &devalidate($symb,$stuname,$domain);
1.109 www 5295:
5296: $symb=escape($symb);
1.187 www 5297: if (!$namespace) {
1.620 albertel 5298: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5299: return '';
5300: }
5301: }
1.620 albertel 5302: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5303:
5304: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5305: $$storehash{'host'}=$perlvar{'lonHostID'};
5306:
1.12 www 5307: my $namevalue='';
1.800 albertel 5308: foreach my $key (keys(%$storehash)) {
5309: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5310: }
1.12 www 5311: $namevalue=~s/\&$//;
1.187 www 5312: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5313: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5314: }
5315:
1.47 www 5316: # -------------------------------------------------------------- Critical Store
5317:
5318: sub cstore {
1.1172.2.64 raeburn 5319: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5320: my $home='';
5321:
1.168 albertel 5322: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5323:
1.213 www 5324: $symb=&symbclean($symb);
1.122 albertel 5325: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5326:
1.620 albertel 5327: if (!$domain) { $domain=$env{'user.domain'}; }
5328: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5329:
5330: &devalidate($symb,$stuname,$domain);
1.109 www 5331:
5332: $symb=escape($symb);
1.187 www 5333: if (!$namespace) {
1.620 albertel 5334: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5335: return '';
5336: }
5337: }
1.620 albertel 5338: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5339:
5340: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5341: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5342:
1.47 www 5343: my $namevalue='';
1.800 albertel 5344: foreach my $key (keys(%$storehash)) {
5345: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5346: }
1.47 www 5347: $namevalue=~s/\&$//;
1.187 www 5348: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5349: return critical
1.1172.2.64 raeburn 5350: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5351: }
5352:
1.9 www 5353: # --------------------------------------------------------------------- Restore
5354:
5355: sub restore {
1.124 www 5356: my ($symb,$namespace,$domain,$stuname) = @_;
5357: my $home='';
5358:
1.168 albertel 5359: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5360:
1.122 albertel 5361: if (!$symb) {
1.1172.2.26 raeburn 5362: return if ($namespace eq 'courserequests');
5363: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5364: } else {
1.1172.2.26 raeburn 5365: unless ($namespace eq 'courserequests') {
5366: $symb=&escape(&symbclean($symb));
5367: }
1.122 albertel 5368: }
1.188 www 5369: if (!$namespace) {
1.620 albertel 5370: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5371: return '';
5372: }
5373: }
1.620 albertel 5374: if (!$domain) { $domain=$env{'user.domain'}; }
5375: if (!$stuname) { $stuname=$env{'user.name'}; }
5376: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5377: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5378:
1.12 www 5379: my %returnhash=();
1.800 albertel 5380: foreach my $line (split(/\&/,$answer)) {
5381: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5382: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5383: }
1.75 www 5384: my $version;
5385: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5386: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5387: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5388: }
1.75 www 5389: }
1.13 www 5390: return %returnhash;
1.34 www 5391: }
5392:
5393: # ---------------------------------------------------------- Course Description
1.1118 foxr 5394: #
5395: #
1.34 www 5396:
5397: sub coursedescription {
1.731 albertel 5398: my ($courseid,$args)=@_;
1.34 www 5399: $courseid=~s/^\///;
1.49 www 5400: $courseid=~s/\_/\//g;
1.34 www 5401: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5402: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5403: my $normalid=$cdomain.'_'.$cnum;
5404: # need to always cache even if we get errors otherwise we keep
5405: # trying and trying and trying to get the course description.
5406: my %envhash=();
5407: my %returnhash=();
1.731 albertel 5408:
5409: my $expiretime=600;
5410: if ($env{'request.course.id'} eq $normalid) {
5411: $expiretime=120;
5412: }
5413:
5414: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5415: if (!$args->{'freshen_cache'}
5416: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5417: foreach my $key (keys(%env)) {
5418: next if ($key !~ /^\Q$prefix\E(.*)/);
5419: my ($setting) = $1;
5420: $returnhash{$setting} = $env{$key};
5421: }
5422: return %returnhash;
5423: }
5424:
1.1118 foxr 5425: # get the data again
5426:
1.731 albertel 5427: if (!$args->{'one_time'}) {
5428: $envhash{'course.'.$normalid.'.last_cache'}=time;
5429: }
1.811 albertel 5430:
1.34 www 5431: if ($chome ne 'no_host') {
1.302 albertel 5432: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5433: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5434: my $username = $env{'user.name'}; # Defult username
5435: if(defined $args->{'user'}) {
5436: $username = $args->{'user'};
5437: }
1.129 albertel 5438: $returnhash{'home'}= $chome;
5439: $returnhash{'domain'} = $cdomain;
5440: $returnhash{'num'} = $cnum;
1.741 raeburn 5441: if (!defined($returnhash{'type'})) {
5442: $returnhash{'type'} = 'Course';
5443: }
1.130 albertel 5444: while (my ($name,$value) = each %returnhash) {
1.53 www 5445: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5446: }
1.270 www 5447: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5448: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5449: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5450: $envhash{'course.'.$normalid.'.home'}=$chome;
5451: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5452: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5453: }
5454: }
1.731 albertel 5455: if (!$args->{'one_time'}) {
1.949 raeburn 5456: &appenv(\%envhash);
1.731 albertel 5457: }
1.302 albertel 5458: return %returnhash;
1.461 www 5459: }
5460:
1.1080 raeburn 5461: sub update_released_required {
5462: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5463: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5464: $cid = $env{'request.course.id'};
5465: $cdom = $env{'course.'.$cid.'.domain'};
5466: $cnum = $env{'course.'.$cid.'.num'};
5467: $chome = $env{'course.'.$cid.'.home'};
5468: }
5469: if ($needsrelease) {
5470: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5471: my $needsupdate;
5472: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5473: $needsupdate = 1;
5474: } else {
5475: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5476: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5477: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5478: $needsupdate = 1;
5479: }
5480: }
5481: if ($needsupdate) {
5482: my %needshash = (
5483: 'internal.releaserequired' => $needsrelease,
5484: );
5485: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5486: if ($putresult eq 'ok') {
5487: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5488: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5489: if (ref($crsinfo{$cid}) eq 'HASH') {
5490: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5491: &courseidput($cdom,\%crsinfo,$chome,'notime');
5492: }
5493: }
5494: }
5495: }
5496: return;
5497: }
5498:
1.461 www 5499: # -------------------------------------------------See if a user is privileged
5500:
5501: sub privileged {
1.1172.2.23 raeburn 5502: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5503: my $now = time;
1.1172.2.23 raeburn 5504: my $roles;
5505: if (ref($possroles) eq 'ARRAY') {
5506: $roles = $possroles;
5507: } else {
5508: $roles = ['dc','su'];
5509: }
5510: if (ref($possdomains) eq 'ARRAY') {
5511: my %privileged = &privileged_by_domain($possdomains,$roles);
5512: foreach my $dom (@{$possdomains}) {
5513: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5514: (ref($privileged{$dom}) eq 'HASH')) {
5515: foreach my $role (@{$roles}) {
5516: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5517: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5518: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5519: return 1 unless (($end && $end < $now) ||
5520: ($start && $start > $now));
5521: }
5522: }
5523: }
5524: }
5525: }
5526: } else {
5527: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5528: my $now = time;
1.1170 droeschl 5529:
1.1172.2.58 raeburn 5530: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5531: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5532: if (grep(/^\Q$trole\E$/,@{$roles})) {
5533: return 1 unless ($tend && $tend < $now)
5534: or ($tstart && $tstart > $now);
1.1170 droeschl 5535: }
1.1172.2.23 raeburn 5536: }
5537: }
1.461 www 5538: return 0;
1.9 www 5539: }
1.1 albertel 5540:
1.1172.2.23 raeburn 5541: sub privileged_by_domain {
5542: my ($domains,$roles) = @_;
5543: my %privileged = ();
5544: my $cachetime = 60*60*24;
5545: my $now = time;
5546: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5547: return %privileged;
5548: }
5549: foreach my $dom (@{$domains}) {
5550: next if (ref($privileged{$dom}) eq 'HASH');
5551: my $needroles;
5552: foreach my $role (@{$roles}) {
5553: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5554: if (defined($cached)) {
5555: if (ref($result) eq 'HASH') {
5556: $privileged{$dom}{$role} = $result;
5557: }
5558: } else {
5559: $needroles = 1;
5560: }
5561: }
5562: if ($needroles) {
5563: my %dompersonnel = &get_domain_roles($dom,$roles);
5564: $privileged{$dom} = {};
5565: foreach my $server (keys(%dompersonnel)) {
5566: if (ref($dompersonnel{$server}) eq 'HASH') {
5567: foreach my $item (keys(%{$dompersonnel{$server}})) {
5568: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5569: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5570: next if ($end && $end < $now);
5571: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5572: $dompersonnel{$server}{$item};
5573: }
5574: }
5575: }
5576: if (ref($privileged{$dom}) eq 'HASH') {
5577: foreach my $role (@{$roles}) {
5578: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5579: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5580: } else {
5581: my %hash = ();
5582: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5583: }
5584: }
5585: }
5586: }
5587: }
5588: return %privileged;
5589: }
5590:
1.103 harris41 5591: # -------------------------------------------------------- Get user privileges
1.11 www 5592:
5593: sub rolesinit {
1.1169 droeschl 5594: my ($domain, $username) = @_;
5595: my %userroles = ('user.login.time' => time);
5596: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5597:
5598: # firstaccess and timerinterval are related to timed maps/resources.
5599: # also, blocking can be triggered by an activating timer
5600: # it's saved in the user's %env.
5601: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5602: my %timerinterval = &dump('timerinterval', $domain, $username);
5603: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5604: %timerintchk, %timerintenv);
5605:
1.1162 raeburn 5606: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5607: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5608: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5609: }
1.1169 droeschl 5610:
1.1162 raeburn 5611: foreach my $key (keys(%timerinterval)) {
5612: my ($cid,$rest) = split(/\0/,$key);
5613: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5614: }
1.1169 droeschl 5615:
1.11 www 5616: my %allroles=();
1.1162 raeburn 5617: my %allgroups=();
1.11 www 5618:
1.1172.2.58 raeburn 5619: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5620: my $role = $rolesdump{$area};
5621: $area =~ s/\_\w\w$//;
5622:
5623: my ($trole, $tend, $tstart, $group_privs);
5624:
5625: if ($role =~ /^cr/) {
5626: # Custom role, defined by a user
5627: # e.g., user.role.cr/msu/smith/mynewrole
5628: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5629: $trole = $1;
5630: ($tend, $tstart) = split('_', $2);
5631: } else {
5632: $trole = $role;
5633: }
5634: } elsif ($role =~ m|^gr/|) {
5635: # Role of member in a group, defined within a course/community
5636: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5637: ($trole, $tend, $tstart) = split(/_/, $role);
5638: next if $tstart eq '-1';
5639: ($trole, $group_privs) = split(/\//, $trole);
5640: $group_privs = &unescape($group_privs);
5641: } else {
5642: # Just a normal role, defined in roles.tab
5643: ($trole, $tend, $tstart) = split(/_/,$role);
5644: }
5645:
5646: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5647: $username);
5648: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5649:
5650: # role expired or not available yet?
5651: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5652: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5653:
5654: next if $area eq '' or $trole eq '';
5655:
5656: my $spec = "$trole.$area";
5657: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5658:
5659: if ($trole =~ /^cr\//) {
5660: # Custom role, defined by a user
5661: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5662: } elsif ($trole eq 'gr') {
5663: # Role of a member in a group, defined within a course/community
5664: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5665: next;
5666: } else {
5667: # Normal role, defined in roles.tab
5668: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5669: }
5670:
5671: my $cid = $tdomain.'_'.$trest;
5672: unless ($firstaccchk{$cid}) {
5673: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5674: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5675: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5676: $coursetimerstarts{$cid}{$item};
5677: }
5678: }
5679: $firstaccchk{$cid} = 1;
5680: }
5681: unless ($timerintchk{$cid}) {
5682: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5683: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5684: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5685: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5686: }
1.12 www 5687: }
1.1169 droeschl 5688: $timerintchk{$cid} = 1;
1.191 harris41 5689: }
1.11 www 5690: }
1.1169 droeschl 5691:
1.1172.2.91 raeburn 5692: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5693: \%allroles, \%allgroups);
1.1169 droeschl 5694: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 5695: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5696:
1.1162 raeburn 5697: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5698: }
5699:
1.567 raeburn 5700: sub set_arearole {
1.1172.2.19 raeburn 5701: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5702: unless ($nolog) {
1.567 raeburn 5703: # log the associated role with the area
1.1172.2.19 raeburn 5704: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5705: }
1.743 albertel 5706: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5707: }
5708:
5709: sub custom_roleprivs {
5710: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5711: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5712: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5713: if (&hostname($homsvr) ne '') {
1.567 raeburn 5714: my ($rdummy,$roledef)=
5715: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5716: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5717: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5718: if (defined($syspriv)) {
1.1043 raeburn 5719: if ($trest =~ /^$match_community$/) {
5720: $syspriv =~ s/bre\&S//;
5721: }
1.567 raeburn 5722: $$allroles{'cm./'}.=':'.$syspriv;
5723: $$allroles{$spec.'./'}.=':'.$syspriv;
5724: }
5725: if ($tdomain ne '') {
5726: if (defined($dompriv)) {
5727: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5728: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5729: }
5730: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 5731: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5732: my $rolename = $1;
5733: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5734: }
1.567 raeburn 5735: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5736: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5737: }
5738: }
5739: }
5740: }
5741: }
5742:
1.1172.2.89 raeburn 5743: sub course_adhocrole_privs {
5744: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5745: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5746: if ($overrides{"internal.adhocpriv.$rolename"}) {
5747: my (%currprivs,%storeprivs);
5748: foreach my $item (split(/:/,$coursepriv)) {
5749: my ($priv,$restrict) = split(/\&/,$item);
5750: $currprivs{$priv} = $restrict;
5751: }
5752: my (%possadd,%possremove,%full);
5753: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5754: my ($priv,$restrict)=split(/\&/,$item);
5755: $full{$priv} = $restrict;
5756: }
5757: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5758: next if ($item eq '');
5759: my ($rule,$rest) = split(/=/,$item);
5760: next unless (($rule eq 'off') || ($rule eq 'on'));
5761: foreach my $priv (split(/:/,$rest)) {
5762: if ($priv ne '') {
5763: if ($rule eq 'off') {
5764: $possremove{$priv} = 1;
5765: } else {
5766: $possadd{$priv} = 1;
5767: }
5768: }
5769: }
5770: }
5771: foreach my $priv (sort(keys(%full))) {
5772: if (exists($currprivs{$priv})) {
5773: unless (exists($possremove{$priv})) {
5774: $storeprivs{$priv} = $currprivs{$priv};
5775: }
5776: } elsif (exists($possadd{$priv})) {
5777: $storeprivs{$priv} = $full{$priv};
5778: }
5779: }
5780: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5781: }
5782: return $coursepriv;
5783: }
5784:
1.678 raeburn 5785: sub group_roleprivs {
5786: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5787: my $access = 1;
5788: my $now = time;
5789: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5790: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5791: if ($access) {
1.811 albertel 5792: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5793: $$allgroups{$course}{$group} .=':'.$group_privs;
5794: }
5795: }
1.567 raeburn 5796:
5797: sub standard_roleprivs {
5798: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5799: if (defined($pr{$trole.':s'})) {
5800: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5801: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5802: }
5803: if ($tdomain ne '') {
5804: if (defined($pr{$trole.':d'})) {
5805: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5806: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5807: }
5808: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5809: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5810: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5811: }
5812: }
5813: }
5814:
5815: sub set_userprivs {
1.1064 raeburn 5816: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5817: my $author=0;
5818: my $adv=0;
1.1172.2.91 raeburn 5819: my $rar=0;
1.678 raeburn 5820: my %grouproles = ();
5821: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5822: my @groupkeys;
1.1000 raeburn 5823: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5824: push(@groupkeys,$role);
5825: }
5826: if (ref($groups_roles) eq 'HASH') {
5827: foreach my $key (keys(%{$groups_roles})) {
5828: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5829: push(@groupkeys,$key);
5830: }
5831: }
5832: }
5833: if (@groupkeys > 0) {
5834: foreach my $role (@groupkeys) {
5835: my ($trole,$area,$sec,$extendedarea);
5836: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5837: $trole = $1;
5838: $area = $2;
5839: $sec = $3;
5840: $extendedarea = $area.$sec;
5841: if (exists($$allgroups{$area})) {
5842: foreach my $group (keys(%{$$allgroups{$area}})) {
5843: my $spec = $trole.'.'.$extendedarea;
5844: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5845: $$allgroups{$area}{$group};
1.1064 raeburn 5846: }
1.678 raeburn 5847: }
5848: }
5849: }
5850: }
5851: }
1.800 albertel 5852: foreach my $group (keys(%grouproles)) {
5853: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5854: }
1.800 albertel 5855: foreach my $role (keys(%{$allroles})) {
5856: my %thesepriv;
1.941 raeburn 5857: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5858: foreach my $item (split(/:/,$$allroles{$role})) {
5859: if ($item ne '') {
5860: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5861: if ($restrictions eq '') {
5862: $thesepriv{$privilege}='F';
5863: } elsif ($thesepriv{$privilege} ne 'F') {
5864: $thesepriv{$privilege}.=$restrictions;
5865: }
5866: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 5867: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5868: }
5869: }
5870: my $thesestr='';
1.1104 raeburn 5871: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5872: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5873: }
5874: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5875: }
1.1172.2.91 raeburn 5876: return ($author,$adv,$rar);
1.567 raeburn 5877: }
5878:
1.994 raeburn 5879: sub role_status {
1.1104 raeburn 5880: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5881: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5882: my ($one,$two) = split(m{\./},$rolekey,2);
5883: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5884: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5885: $$where = '/'.$two;
1.994 raeburn 5886: $$trolecode=$$role.'.'.$$where;
5887: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5888: $$tstatus='is';
1.1104 raeburn 5889: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5890: $$tstatus='future';
1.1034 raeburn 5891: if ($$tstart<$now) {
5892: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5893: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5894: my (%allroles,%allgroups,$group_privs,
5895: %groups_roles,@rolecodes);
1.1002 raeburn 5896: my %userroles = (
5897: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5898: );
1.1064 raeburn 5899: @rolecodes = ('cm');
1.1002 raeburn 5900: my $spec=$$role.'.'.$$where;
5901: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5902: if ($$role =~ /^cr\//) {
5903: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5904: push(@rolecodes,'cr');
1.1002 raeburn 5905: } elsif ($$role eq 'gr') {
1.1064 raeburn 5906: push(@rolecodes,$$role);
1.1002 raeburn 5907: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5908: $env{'user.name'});
1.1064 raeburn 5909: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5910: (undef,my $group_privs) = split(/\//,$trole);
5911: $group_privs = &unescape($group_privs);
5912: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5913: 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 5914: &get_groups_roles($tdomain,$trest,
5915: \%course_roles,\@rolecodes,
5916: \%groups_roles);
1.1002 raeburn 5917: } else {
1.1064 raeburn 5918: push(@rolecodes,$$role);
1.1002 raeburn 5919: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5920: }
1.1172.2.91 raeburn 5921: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
5922: \%groups_roles);
1.1064 raeburn 5923: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 5924: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 5925: }
5926: }
1.1034 raeburn 5927: $$tstatus = 'is';
1.1002 raeburn 5928: }
1.994 raeburn 5929: }
5930: if ($$tend) {
1.1104 raeburn 5931: if ($$tend<$update) {
1.994 raeburn 5932: $$tstatus='expired';
5933: } elsif ($$tend<$now) {
5934: $$tstatus='will_not';
5935: }
5936: }
5937: }
5938: }
5939: }
5940:
1.1104 raeburn 5941: sub get_groups_roles {
5942: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5943: return unless((ref($cdom_courseroles) eq 'HASH') &&
5944: (ref($rolecodes) eq 'ARRAY') &&
5945: (ref($groups_roles) eq 'HASH'));
5946: if (keys(%{$cdom_courseroles}) > 0) {
5947: my ($cnum) = ($rest =~ /^($match_courseid)/);
5948: if ($cdom ne '' && $cnum ne '') {
5949: foreach my $key (keys(%{$cdom_courseroles})) {
5950: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5951: my $crsrole = $1;
5952: my $crssec = $2;
5953: if ($crsrole =~ /^cr/) {
5954: unless (grep(/^cr$/,@{$rolecodes})) {
5955: push(@{$rolecodes},'cr');
5956: }
5957: } else {
5958: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5959: push(@{$rolecodes},$crsrole);
5960: }
5961: }
5962: my $rolekey = "$crsrole./$cdom/$cnum";
5963: if ($crssec ne '') {
5964: $rolekey .= "/$crssec";
5965: }
5966: $rolekey .= './';
5967: $groups_roles->{$rolekey} = $rolecodes;
5968: }
5969: }
5970: }
5971: }
5972: return;
5973: }
5974:
5975: sub delete_env_groupprivs {
5976: my ($where,$courseroles,$possroles) = @_;
5977: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5978: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5979: unless (ref($courseroles->{$udom}) eq 'HASH') {
5980: %{$courseroles->{$udom}} =
5981: &get_my_roles('','','userroles',['active'],
5982: $possroles,[$udom],1);
5983: }
5984: if (ref($courseroles->{$udom}) eq 'HASH') {
5985: foreach my $item (keys(%{$courseroles->{$udom}})) {
5986: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5987: my $area = '/'.$cdom.'/'.$cnum;
5988: my $privkey = "user.priv.$crsrole.$area";
5989: if ($crssec ne '') {
5990: $privkey .= '/'.$crssec;
5991: }
5992: $privkey .= ".$area/$group";
5993: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5994: }
5995: }
5996: return;
5997: }
5998:
1.994 raeburn 5999: sub check_adhoc_privs {
1.1172.2.86 raeburn 6000: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6001: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6002: if ($sec) {
6003: $cckey .= '/'.$sec;
6004: }
1.1172.2.9 raeburn 6005: my $setprivs;
1.994 raeburn 6006: if ($env{$cckey}) {
6007: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6008: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6009: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6010: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6011: $setprivs = 1;
1.994 raeburn 6012: }
6013: } else {
1.1172.2.87 raeburn 6014: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6015: $setprivs = 1;
1.994 raeburn 6016: }
1.1172.2.9 raeburn 6017: return $setprivs;
1.994 raeburn 6018: }
6019:
6020: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6021: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6022: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6023: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6024: if ($sec ne '') {
6025: $area .= '/'.$sec;
6026: }
1.994 raeburn 6027: my $spec = $role.'.'.$area;
6028: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6029: $env{'user.name'},1);
1.1172.2.84 raeburn 6030: my %rolehash = ();
1.1172.2.89 raeburn 6031: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6032: my $rolename = $1;
1.1172.2.84 raeburn 6033: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6034: my %domdef = &get_domain_defaults($dcdom);
6035: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6036: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6037: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6038: }
6039: }
1.1172.2.84 raeburn 6040: } else {
6041: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6042: }
1.1172.2.91 raeburn 6043: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6044: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6045: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6046: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6047: &appenv( {'request.role' => $spec,
6048: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6049: 'request.course.sec' => $sec,
1.1088 raeburn 6050: }
6051: );
6052: my $tadv=0;
6053: if (&allowed('adv') eq 'F') { $tadv=1; }
6054: &appenv({'request.role.adv' => $tadv});
6055: }
1.994 raeburn 6056: }
6057:
1.12 www 6058: # --------------------------------------------------------------- get interface
6059:
6060: sub get {
1.131 albertel 6061: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6062: my $items='';
1.800 albertel 6063: foreach my $item (@$storearr) {
6064: $items.=&escape($item).'&';
1.191 harris41 6065: }
1.12 www 6066: $items=~s/\&$//;
1.620 albertel 6067: if (!$udomain) { $udomain=$env{'user.domain'}; }
6068: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6069: my $uhome=&homeserver($uname,$udomain);
6070:
1.133 albertel 6071: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6072: my @pairs=split(/\&/,$rep);
1.273 albertel 6073: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6074: return @pairs;
6075: }
1.15 www 6076: my %returnhash=();
1.42 www 6077: my $i=0;
1.800 albertel 6078: foreach my $item (@$storearr) {
6079: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6080: $i++;
1.191 harris41 6081: }
1.15 www 6082: return %returnhash;
1.27 www 6083: }
6084:
6085: # --------------------------------------------------------------- del interface
6086:
6087: sub del {
1.133 albertel 6088: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6089: my $items='';
1.800 albertel 6090: foreach my $item (@$storearr) {
6091: $items.=&escape($item).'&';
1.191 harris41 6092: }
1.984 neumanie 6093:
1.27 www 6094: $items=~s/\&$//;
1.620 albertel 6095: if (!$udomain) { $udomain=$env{'user.domain'}; }
6096: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6097: my $uhome=&homeserver($uname,$udomain);
6098: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6099: }
6100:
6101: # -------------------------------------------------------------- dump interface
6102:
1.1172.2.22 raeburn 6103: sub unserialize {
6104: my ($rep, $escapedkeys) = @_;
6105:
6106: return {} if $rep =~ /^error/;
6107:
6108: my %returnhash=();
6109: foreach my $item (split(/\&/,$rep)) {
6110: my ($key, $value) = split(/=/, $item, 2);
6111: $key = unescape($key) unless $escapedkeys;
6112: next if $key =~ /^error: 2 /;
6113: $returnhash{$key} = &thaw_unescape($value);
6114: }
6115: return \%returnhash;
6116: }
6117:
6118: # see Lond::dump_with_regexp
6119: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6120: sub dump {
1.1172.2.22 raeburn 6121: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6122: if (!$udomain) { $udomain=$env{'user.domain'}; }
6123: if (!$uname) { $uname=$env{'user.name'}; }
6124: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6125:
1.1172.2.55 raeburn 6126: if ($regexp) {
6127: $regexp=&escape($regexp);
6128: } else {
6129: $regexp='.';
6130: }
1.1172.2.22 raeburn 6131: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6132: # user is hosted on this machine
1.1172.2.55 raeburn 6133: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6134: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6135: return %{&unserialize($reply, $escapedkeys)};
6136: }
1.1166 raeburn 6137: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6138: my @pairs=split(/\&/,$rep);
6139: my %returnhash=();
1.1098 foxr 6140: if (!($rep =~ /^error/ )) {
6141: foreach my $item (@pairs) {
6142: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6143: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6144: next if ($key =~ /^error: 2 /);
6145: $returnhash{$key}=&thaw_unescape($value);
6146: }
1.755 albertel 6147: }
6148: return %returnhash;
1.407 www 6149: }
6150:
1.1098 foxr 6151:
1.717 albertel 6152: # --------------------------------------------------------- dumpstore interface
6153:
6154: sub dumpstore {
6155: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6156: # same as dump but keys must be escaped. They may contain colon separated
6157: # lists of values that may themself contain colons (e.g. symbs).
6158: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6159: }
6160:
1.407 www 6161: # -------------------------------------------------------------- keys interface
6162:
6163: sub getkeys {
6164: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6165: if (!$udomain) { $udomain=$env{'user.domain'}; }
6166: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6167: my $uhome=&homeserver($uname,$udomain);
6168: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6169: my @keyarray=();
1.800 albertel 6170: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6171: next if ($key =~ /^error: 2 /);
1.800 albertel 6172: push(@keyarray,&unescape($key));
1.407 www 6173: }
6174: return @keyarray;
1.318 matthew 6175: }
6176:
1.319 matthew 6177: # --------------------------------------------------------------- currentdump
6178: sub currentdump {
1.328 matthew 6179: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6180: $courseid = $env{'request.course.id'} if (! defined($courseid));
6181: $sdom = $env{'user.domain'} if (! defined($sdom));
6182: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6183: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6184: my $rep;
6185:
6186: if (grep { $_ eq $uhome } current_machine_ids()) {
6187: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6188: $courseid)));
6189: } else {
6190: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6191: }
6192:
1.318 matthew 6193: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6194: #
1.318 matthew 6195: my %returnhash=();
1.319 matthew 6196: #
6197: if ($rep eq "unknown_cmd") {
6198: # an old lond will not know currentdump
6199: # Do a dump and make it look like a currentdump
1.822 albertel 6200: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6201: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6202: my %hash = @tmp;
6203: @tmp=();
1.424 matthew 6204: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6205: } else {
6206: my @pairs=split(/\&/,$rep);
1.800 albertel 6207: foreach my $pair (@pairs) {
6208: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6209: my ($symb,$param) = split(/:/,$key);
6210: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6211: &thaw_unescape($value);
1.319 matthew 6212: }
1.191 harris41 6213: }
1.12 www 6214: return %returnhash;
1.424 matthew 6215: }
6216:
6217: sub convert_dump_to_currentdump{
6218: my %hash = %{shift()};
6219: my %returnhash;
6220: # Code ripped from lond, essentially. The only difference
6221: # here is the unescaping done by lonnet::dump(). Conceivably
6222: # we might run in to problems with parameter names =~ /^v\./
6223: while (my ($key,$value) = each(%hash)) {
6224: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6225: $symb = &unescape($symb);
6226: $param = &unescape($param);
1.424 matthew 6227: next if ($v eq 'version' || $symb eq 'keys');
6228: next if (exists($returnhash{$symb}) &&
6229: exists($returnhash{$symb}->{$param}) &&
6230: $returnhash{$symb}->{'v.'.$param} > $v);
6231: $returnhash{$symb}->{$param}=$value;
6232: $returnhash{$symb}->{'v.'.$param}=$v;
6233: }
6234: #
6235: # Remove all of the keys in the hashes which keep track of
6236: # the version of the parameter.
6237: while (my ($symb,$param_hash) = each(%returnhash)) {
6238: # use a foreach because we are going to delete from the hash.
6239: foreach my $key (keys(%$param_hash)) {
6240: delete($param_hash->{$key}) if ($key =~ /^v\./);
6241: }
6242: }
6243: return \%returnhash;
1.12 www 6244: }
6245:
1.627 albertel 6246: # ------------------------------------------------------ critical inc interface
6247:
6248: sub cinc {
6249: return &inc(@_,'critical');
6250: }
6251:
1.449 matthew 6252: # --------------------------------------------------------------- inc interface
6253:
6254: sub inc {
1.627 albertel 6255: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6256: if (!$udomain) { $udomain=$env{'user.domain'}; }
6257: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6258: my $uhome=&homeserver($uname,$udomain);
6259: my $items='';
6260: if (! ref($store)) {
6261: # got a single value, so use that instead
6262: $items = &escape($store).'=&';
6263: } elsif (ref($store) eq 'SCALAR') {
6264: $items = &escape($$store).'=&';
6265: } elsif (ref($store) eq 'ARRAY') {
6266: $items = join('=&',map {&escape($_);} @{$store});
6267: } elsif (ref($store) eq 'HASH') {
6268: while (my($key,$value) = each(%{$store})) {
6269: $items.= &escape($key).'='.&escape($value).'&';
6270: }
6271: }
6272: $items=~s/\&$//;
1.627 albertel 6273: if ($critical) {
6274: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6275: } else {
6276: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6277: }
1.449 matthew 6278: }
6279:
1.12 www 6280: # --------------------------------------------------------------- put interface
6281:
6282: sub put {
1.134 albertel 6283: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6284: if (!$udomain) { $udomain=$env{'user.domain'}; }
6285: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6286: my $uhome=&homeserver($uname,$udomain);
1.12 www 6287: my $items='';
1.800 albertel 6288: foreach my $item (keys(%$storehash)) {
6289: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6290: }
1.12 www 6291: $items=~s/\&$//;
1.134 albertel 6292: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6293: }
6294:
1.631 albertel 6295: # ------------------------------------------------------------ newput interface
6296:
6297: sub newput {
6298: my ($namespace,$storehash,$udomain,$uname)=@_;
6299: if (!$udomain) { $udomain=$env{'user.domain'}; }
6300: if (!$uname) { $uname=$env{'user.name'}; }
6301: my $uhome=&homeserver($uname,$udomain);
6302: my $items='';
6303: foreach my $key (keys(%$storehash)) {
6304: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6305: }
6306: $items=~s/\&$//;
6307: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6308: }
6309:
6310: # --------------------------------------------------------- putstore interface
6311:
1.524 raeburn 6312: sub putstore {
1.1172.2.59 raeburn 6313: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6314: if (!$udomain) { $udomain=$env{'user.domain'}; }
6315: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6316: my $uhome=&homeserver($uname,$udomain);
6317: my $items='';
1.715 albertel 6318: foreach my $key (keys(%$storehash)) {
6319: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6320: }
1.715 albertel 6321: $items=~s/\&$//;
1.716 albertel 6322: my $esc_symb=&escape($symb);
6323: my $esc_v=&escape($version);
1.715 albertel 6324: my $reply =
1.716 albertel 6325: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6326: $uhome);
1.1172.2.59 raeburn 6327: if (($tolog) && ($reply eq 'ok')) {
6328: my $namevalue='';
6329: foreach my $key (keys(%{$storehash})) {
6330: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6331: }
6332: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6333: '&host='.&escape($perlvar{'lonHostID'}).
6334: '&version='.$esc_v.
6335: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6336: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6337: }
1.715 albertel 6338: if ($reply eq 'unknown_cmd') {
1.716 albertel 6339: # gfall back to way things use to be done
1.715 albertel 6340: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6341: $uname);
1.524 raeburn 6342: }
1.715 albertel 6343: return $reply;
6344: }
6345:
6346: sub old_putstore {
1.716 albertel 6347: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6348: if (!$udomain) { $udomain=$env{'user.domain'}; }
6349: if (!$uname) { $uname=$env{'user.name'}; }
6350: my $uhome=&homeserver($uname,$udomain);
6351: my %newstorehash;
1.800 albertel 6352: foreach my $item (keys(%$storehash)) {
6353: my $key = $version.':'.&escape($symb).':'.$item;
6354: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6355: }
6356: my $items='';
6357: my %allitems = ();
1.800 albertel 6358: foreach my $item (keys(%newstorehash)) {
6359: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6360: my $key = $1.':keys:'.$2;
6361: $allitems{$key} .= $3.':';
6362: }
1.800 albertel 6363: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6364: }
1.800 albertel 6365: foreach my $item (keys(%allitems)) {
6366: $allitems{$item} =~ s/\:$//;
6367: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6368: }
6369: $items=~s/\&$//;
6370: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6371: }
6372:
1.47 www 6373: # ------------------------------------------------------ critical put interface
6374:
6375: sub cput {
1.134 albertel 6376: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6377: if (!$udomain) { $udomain=$env{'user.domain'}; }
6378: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6379: my $uhome=&homeserver($uname,$udomain);
1.47 www 6380: my $items='';
1.800 albertel 6381: foreach my $item (keys(%$storehash)) {
6382: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6383: }
1.47 www 6384: $items=~s/\&$//;
1.134 albertel 6385: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6386: }
6387:
6388: # -------------------------------------------------------------- eget interface
6389:
6390: sub eget {
1.133 albertel 6391: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6392: my $items='';
1.800 albertel 6393: foreach my $item (@$storearr) {
6394: $items.=&escape($item).'&';
1.191 harris41 6395: }
1.12 www 6396: $items=~s/\&$//;
1.620 albertel 6397: if (!$udomain) { $udomain=$env{'user.domain'}; }
6398: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6399: my $uhome=&homeserver($uname,$udomain);
6400: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6401: my @pairs=split(/\&/,$rep);
6402: my %returnhash=();
1.42 www 6403: my $i=0;
1.800 albertel 6404: foreach my $item (@$storearr) {
6405: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6406: $i++;
1.191 harris41 6407: }
1.12 www 6408: return %returnhash;
6409: }
6410:
1.667 albertel 6411: # ------------------------------------------------------------ tmpput interface
6412: sub tmpput {
1.802 raeburn 6413: my ($storehash,$server,$context)=@_;
1.667 albertel 6414: my $items='';
1.800 albertel 6415: foreach my $item (keys(%$storehash)) {
6416: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6417: }
6418: $items=~s/\&$//;
1.802 raeburn 6419: if (defined($context)) {
6420: $items .= ':'.&escape($context);
6421: }
1.667 albertel 6422: return &reply("tmpput:$items",$server);
6423: }
6424:
6425: # ------------------------------------------------------------ tmpget interface
6426: sub tmpget {
1.688 albertel 6427: my ($token,$server)=@_;
6428: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6429: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6430: my %returnhash;
1.1172.2.85 raeburn 6431: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6432: return %returnhash;
6433: }
1.667 albertel 6434: foreach my $item (split(/\&/,$rep)) {
6435: my ($key,$value)=split(/=/,$item);
6436: $returnhash{&unescape($key)}=&thaw_unescape($value);
6437: }
6438: return %returnhash;
6439: }
6440:
1.1113 raeburn 6441: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6442: sub tmpdel {
6443: my ($token,$server)=@_;
6444: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6445: return &reply("tmpdel:$token",$server);
6446: }
6447:
1.1172.2.13 raeburn 6448: # ------------------------------------------------------------ get_timebased_id
6449:
6450: sub get_timebased_id {
6451: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6452: $maxtries) = @_;
6453: my ($newid,$error,$dellock);
6454: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6455: return ('','ok','invalid call to get suffix');
6456: }
6457:
6458: # set defaults for any optional args for which values were not supplied
6459: if ($who eq '') {
6460: $who = $env{'user.name'}.':'.$env{'user.domain'};
6461: }
6462: if (!$locktries) {
6463: $locktries = 3;
6464: }
6465: if (!$maxtries) {
6466: $maxtries = 10;
6467: }
6468:
6469: if (($cdom eq '') || ($cnum eq '')) {
6470: if ($env{'request.course.id'}) {
6471: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6472: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6473: }
6474: if (($cdom eq '') || ($cnum eq '')) {
6475: return ('','ok','call to get suffix not in course context');
6476: }
6477: }
6478:
6479: # construct locking item
6480: my $lockhash = {
6481: $prefix."\0".'locked_'.$keyid => $who,
6482: };
6483: my $tries = 0;
6484:
6485: # attempt to get lock on nohist_$namespace file
6486: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6487: while (($gotlock ne 'ok') && $tries <$locktries) {
6488: $tries ++;
6489: sleep 1;
6490: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6491: }
6492:
6493: # attempt to get unique identifier, based on current timestamp
6494: if ($gotlock eq 'ok') {
6495: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6496: my $id = time;
6497: $newid = $id;
1.1172.2.56 raeburn 6498: if ($idtype eq 'addcode') {
6499: $newid .= &sixnum_code();
6500: }
1.1172.2.13 raeburn 6501: my $idtries = 0;
6502: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6503: if ($idtype eq 'concat') {
6504: $newid = $id.$idtries;
1.1172.2.56 raeburn 6505: } elsif ($idtype eq 'addcode') {
6506: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6507: } else {
6508: $newid ++;
6509: }
6510: $idtries ++;
6511: }
6512: if (!exists($inuse{$prefix."\0".$newid})) {
6513: my %new_item = (
6514: $prefix."\0".$newid => $who,
6515: );
6516: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6517: $cdom,$cnum);
6518: if ($putresult ne 'ok') {
6519: undef($newid);
6520: $error = 'error saving new item: '.$putresult;
6521: }
6522: } else {
1.1172.2.56 raeburn 6523: undef($newid);
1.1172.2.13 raeburn 6524: $error = ('error: no unique suffix available for the new item ');
6525: }
6526: # remove lock
6527: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6528: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6529: } else {
6530: $error = "error: could not obtain lockfile\n";
6531: $dellock = 'ok';
1.1172.2.58 raeburn 6532: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6533: $dellock = 'nolock';
6534: }
1.1172.2.13 raeburn 6535: }
6536: return ($newid,$dellock,$error);
6537: }
6538:
1.1172.2.56 raeburn 6539: sub sixnum_code {
6540: my $code;
6541: for (0..6) {
6542: $code .= int( rand(9) );
6543: }
6544: return $code;
6545: }
6546:
1.765 albertel 6547: # -------------------------------------------------- portfolio access checking
6548:
6549: sub portfolio_access {
1.1172.2.77 raeburn 6550: my ($requrl,$clientip) = @_;
1.765 albertel 6551: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6552: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6553: if ($result) {
6554: my %setters;
6555: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6556: my ($startblock,$endblock) =
6557: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6558: if ($startblock && $endblock) {
6559: return 'B';
6560: }
6561: } else {
6562: my ($startblock,$endblock) =
6563: &Apache::loncommon::blockcheck(\%setters,'port');
6564: if ($startblock && $endblock) {
6565: return 'B';
6566: }
6567: }
6568: }
1.765 albertel 6569: if ($result eq 'ok') {
1.766 albertel 6570: return 'F';
1.765 albertel 6571: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6572: return 'A';
1.765 albertel 6573: }
1.766 albertel 6574: return '';
1.765 albertel 6575: }
6576:
6577: sub get_portfolio_access {
1.1172.2.77 raeburn 6578: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6579:
6580: if (!ref($access_hash)) {
6581: my $current_perms = &get_portfile_permissions($udom,$unum);
6582: my %access_controls = &get_access_controls($current_perms,$group,
6583: $file_name);
6584: $access_hash = $access_controls{$file_name};
6585: }
6586:
1.1172.2.77 raeburn 6587: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6588: my $now = time;
6589: if (ref($access_hash) eq 'HASH') {
6590: foreach my $key (keys(%{$access_hash})) {
6591: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6592: if ($start > $now) {
6593: next;
6594: }
6595: if ($end && $end<$now) {
6596: next;
6597: }
6598: if ($scope eq 'public') {
6599: $public = $key;
6600: last;
6601: } elsif ($scope eq 'guest') {
6602: $guest = $key;
6603: } elsif ($scope eq 'domains') {
6604: push(@domains,$key);
6605: } elsif ($scope eq 'users') {
6606: push(@users,$key);
6607: } elsif ($scope eq 'course') {
6608: push(@courses,$key);
6609: } elsif ($scope eq 'group') {
6610: push(@groups,$key);
1.1172.2.77 raeburn 6611: } elsif ($scope eq 'ip') {
6612: push(@ips,$key);
1.765 albertel 6613: }
6614: }
6615: if ($public) {
6616: return 'ok';
1.1172.2.77 raeburn 6617: } elsif (@ips > 0) {
6618: my $allowed;
6619: foreach my $ipkey (@ips) {
6620: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6621: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6622: $allowed = 1;
6623: last;
6624: }
6625: }
6626: }
6627: if ($allowed) {
6628: return 'ok';
6629: }
1.765 albertel 6630: }
6631: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6632: if ($guest) {
6633: return $guest;
6634: }
6635: } else {
6636: if (@domains > 0) {
6637: foreach my $domkey (@domains) {
6638: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6639: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6640: return 'ok';
6641: }
6642: }
6643: }
6644: }
6645: if (@users > 0) {
6646: foreach my $userkey (@users) {
1.865 raeburn 6647: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6648: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6649: if (ref($item) eq 'HASH') {
6650: if (($item->{'uname'} eq $env{'user.name'}) &&
6651: ($item->{'udom'} eq $env{'user.domain'})) {
6652: return 'ok';
6653: }
6654: }
6655: }
6656: }
1.765 albertel 6657: }
6658: }
6659: my %roleshash;
6660: my @courses_and_groups = @courses;
6661: push(@courses_and_groups,@groups);
6662: if (@courses_and_groups > 0) {
6663: my (%allgroups,%allroles);
6664: my ($start,$end,$role,$sec,$group);
6665: foreach my $envkey (%env) {
1.1060 raeburn 6666: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6667: my $cid = $2.'_'.$3;
6668: if ($1 eq 'gr') {
6669: $group = $4;
6670: $allgroups{$cid}{$group} = $env{$envkey};
6671: } else {
6672: if ($4 eq '') {
6673: $sec = 'none';
6674: } else {
6675: $sec = $4;
6676: }
6677: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6678: }
1.811 albertel 6679: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6680: my $cid = $2.'_'.$3;
6681: if ($4 eq '') {
6682: $sec = 'none';
6683: } else {
6684: $sec = $4;
6685: }
6686: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6687: }
6688: }
6689: if (keys(%allroles) == 0) {
6690: return;
6691: }
6692: foreach my $key (@courses_and_groups) {
6693: my %content = %{$$access_hash{$key}};
6694: my $cnum = $content{'number'};
6695: my $cdom = $content{'domain'};
6696: my $cid = $cdom.'_'.$cnum;
6697: if (!exists($allroles{$cid})) {
6698: next;
6699: }
6700: foreach my $role_id (keys(%{$content{'roles'}})) {
6701: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6702: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6703: my @status = @{$content{'roles'}{$role_id}{'access'}};
6704: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6705: foreach my $role (keys(%{$allroles{$cid}})) {
6706: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6707: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6708: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6709: if (grep/^all$/,@sections) {
6710: return 'ok';
6711: } else {
6712: if (grep/^$sec$/,@sections) {
6713: return 'ok';
6714: }
6715: }
6716: }
6717: }
6718: if (keys(%{$allgroups{$cid}}) == 0) {
6719: if (grep/^none$/,@groups) {
6720: return 'ok';
6721: }
6722: } else {
6723: if (grep/^all$/,@groups) {
6724: return 'ok';
6725: }
6726: foreach my $group (keys(%{$allgroups{$cid}})) {
6727: if (grep/^$group$/,@groups) {
6728: return 'ok';
6729: }
6730: }
6731: }
6732: }
6733: }
6734: }
6735: }
6736: }
6737: if ($guest) {
6738: return $guest;
6739: }
6740: }
6741: }
6742: return;
6743: }
6744:
6745: sub course_group_datechecker {
6746: my ($dates,$now,$status) = @_;
6747: my ($start,$end) = split(/\./,$dates);
6748: if (!$start && !$end) {
6749: return 'ok';
6750: }
6751: if (grep/^active$/,@{$status}) {
6752: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6753: return 'ok';
6754: }
6755: }
6756: if (grep/^previous$/,@{$status}) {
6757: if ($end > $now ) {
6758: return 'ok';
6759: }
6760: }
6761: if (grep/^future$/,@{$status}) {
6762: if ($start > $now) {
6763: return 'ok';
6764: }
6765: }
6766: return;
6767: }
6768:
6769: sub parse_portfolio_url {
6770: my ($url) = @_;
6771:
6772: my ($type,$udom,$unum,$group,$file_name);
6773:
1.823 albertel 6774: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6775: $type = 1;
6776: $udom = $1;
6777: $unum = $2;
6778: $file_name = $3;
1.823 albertel 6779: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6780: $type = 2;
6781: $udom = $1;
6782: $unum = $2;
6783: $group = $3;
6784: $file_name = $3.'/'.$4;
6785: }
6786: if (wantarray) {
6787: return ($type,$udom,$unum,$file_name,$group);
6788: }
6789: return $type;
6790: }
6791:
6792: sub is_portfolio_url {
6793: my ($url) = @_;
6794: return scalar(&parse_portfolio_url($url));
6795: }
6796:
1.798 raeburn 6797: sub is_portfolio_file {
6798: my ($file) = @_;
1.820 raeburn 6799: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6800: return 1;
6801: }
6802: return;
6803: }
6804:
1.976 raeburn 6805: sub usertools_access {
1.1084 raeburn 6806: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6807: my ($access,%tools);
6808: if ($context eq '') {
6809: $context = 'tools';
6810: }
6811: if ($context eq 'requestcourses') {
6812: %tools = (
6813: official => 1,
6814: unofficial => 1,
1.1006 raeburn 6815: community => 1,
1.1172.2.37 raeburn 6816: textbook => 1,
1.985 raeburn 6817: );
1.1172.2.9 raeburn 6818: } elsif ($context eq 'requestauthor') {
6819: %tools = (
6820: requestauthor => 1,
6821: );
1.985 raeburn 6822: } else {
6823: %tools = (
6824: aboutme => 1,
6825: blog => 1,
1.1172.2.6 raeburn 6826: webdav => 1,
1.985 raeburn 6827: portfolio => 1,
6828: );
6829: }
1.976 raeburn 6830: return if (!defined($tools{$tool}));
6831:
1.1172.2.35 raeburn 6832: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6833: $udom = $env{'user.domain'};
6834: $uname = $env{'user.name'};
6835: }
6836:
1.978 raeburn 6837: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6838: if ($action ne 'reload') {
1.985 raeburn 6839: if ($context eq 'requestcourses') {
6840: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6841: } elsif ($context eq 'requestauthor') {
6842: return $env{'environment.canrequest.author'};
1.985 raeburn 6843: } else {
6844: return $env{'environment.availabletools.'.$tool};
6845: }
6846: }
1.976 raeburn 6847: }
6848:
1.1172.2.9 raeburn 6849: my ($toolstatus,$inststatus,$envkey);
6850: if ($context eq 'requestauthor') {
6851: $envkey = $context;
6852: } else {
6853: $envkey = $context.'.'.$tool;
6854: }
1.976 raeburn 6855:
1.985 raeburn 6856: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6857: ($action ne 'reload')) {
1.1172.2.9 raeburn 6858: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6859: $inststatus = $env{'environment.inststatus'};
6860: } else {
1.1084 raeburn 6861: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6862: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6863: $inststatus = $userenvref->{'inststatus'};
6864: } else {
1.1172.2.9 raeburn 6865: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6866: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6867: $inststatus = $userenv{'inststatus'};
6868: }
1.976 raeburn 6869: }
6870:
6871: if ($toolstatus ne '') {
6872: if ($toolstatus) {
6873: $access = 1;
6874: } else {
6875: $access = 0;
6876: }
6877: return $access;
6878: }
6879:
1.1084 raeburn 6880: my ($is_adv,%domdef);
6881: if (ref($is_advref) eq 'HASH') {
6882: $is_adv = $is_advref->{'is_adv'};
6883: } else {
6884: $is_adv = &is_advanced_user($udom,$uname);
6885: }
6886: if (ref($domdefref) eq 'HASH') {
6887: %domdef = %{$domdefref};
6888: } else {
6889: %domdef = &get_domain_defaults($udom);
6890: }
1.976 raeburn 6891: if (ref($domdef{$tool}) eq 'HASH') {
6892: if ($is_adv) {
6893: if ($domdef{$tool}{'_LC_adv'} ne '') {
6894: if ($domdef{$tool}{'_LC_adv'}) {
6895: $access = 1;
6896: } else {
6897: $access = 0;
6898: }
6899: return $access;
6900: }
6901: }
6902: if ($inststatus ne '') {
6903: my ($hasaccess,$hasnoaccess);
6904: foreach my $affiliation (split(/:/,$inststatus)) {
6905: if ($domdef{$tool}{$affiliation} ne '') {
6906: if ($domdef{$tool}{$affiliation}) {
6907: $hasaccess = 1;
6908: } else {
6909: $hasnoaccess = 1;
6910: }
6911: }
6912: }
6913: if ($hasaccess || $hasnoaccess) {
6914: if ($hasaccess) {
6915: $access = 1;
6916: } elsif ($hasnoaccess) {
6917: $access = 0;
6918: }
6919: return $access;
6920: }
6921: } else {
6922: if ($domdef{$tool}{'default'} ne '') {
6923: if ($domdef{$tool}{'default'}) {
6924: $access = 1;
6925: } elsif ($domdef{$tool}{'default'} == 0) {
6926: $access = 0;
6927: }
6928: return $access;
6929: }
6930: }
6931: } else {
1.1172.2.6 raeburn 6932: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6933: $access = 1;
6934: } else {
6935: $access = 0;
6936: }
1.976 raeburn 6937: return $access;
6938: }
6939: }
6940:
1.1050 raeburn 6941: sub is_course_owner {
6942: my ($cdom,$cnum,$udom,$uname) = @_;
6943: if (($udom eq '') || ($uname eq '')) {
6944: $udom = $env{'user.domain'};
6945: $uname = $env{'user.name'};
6946: }
6947: unless (($udom eq '') || ($uname eq '')) {
6948: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6949: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6950: return 1;
6951: } else {
6952: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6953: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6954: return 1;
6955: }
6956: }
6957: }
6958: }
6959: return;
6960: }
6961:
1.976 raeburn 6962: sub is_advanced_user {
6963: my ($udom,$uname) = @_;
1.1085 raeburn 6964: if ($udom ne '' && $uname ne '') {
6965: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6966: if (wantarray) {
6967: return ($env{'user.adv'},$env{'user.author'});
6968: } else {
6969: return $env{'user.adv'};
6970: }
1.1085 raeburn 6971: }
6972: }
1.976 raeburn 6973: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6974: my %allroles;
1.1128 raeburn 6975: my ($is_adv,$is_author);
1.976 raeburn 6976: foreach my $role (keys(%roleshash)) {
6977: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6978: my $area = '/'.$tdomain.'/'.$trest;
6979: if ($sec ne '') {
6980: $area .= '/'.$sec;
6981: }
6982: if (($area ne '') && ($trole ne '')) {
6983: my $spec=$trole.'.'.$area;
6984: if ($trole =~ /^cr\//) {
6985: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6986: } elsif ($trole ne 'gr') {
6987: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6988: }
1.1128 raeburn 6989: if ($trole eq 'au') {
6990: $is_author = 1;
6991: }
1.976 raeburn 6992: }
6993: }
6994: foreach my $role (keys(%allroles)) {
6995: last if ($is_adv);
6996: foreach my $item (split(/:/,$allroles{$role})) {
6997: if ($item ne '') {
6998: my ($privilege,$restrictions)=split(/&/,$item);
6999: if ($privilege eq 'adv') {
7000: $is_adv = 1;
7001: last;
7002: }
7003: }
7004: }
7005: }
1.1128 raeburn 7006: if (wantarray) {
7007: return ($is_adv,$is_author);
7008: }
1.976 raeburn 7009: return $is_adv;
7010: }
1.798 raeburn 7011:
1.1035 raeburn 7012: sub check_can_request {
1.1036 raeburn 7013: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7014: my $canreq = 0;
7015: my ($types,$typename) = &Apache::loncommon::course_types();
7016: my @options = ('approval','validate','autolimit');
7017: my $optregex = join('|',@options);
7018: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7019: foreach my $type (@{$types}) {
7020: if (&usertools_access($env{'user.name'},
7021: $env{'user.domain'},
7022: $type,undef,'requestcourses')) {
7023: $canreq ++;
1.1036 raeburn 7024: if (ref($request_domains) eq 'HASH') {
7025: push(@{$request_domains->{$type}},$env{'user.domain'});
7026: }
1.1035 raeburn 7027: if ($dom eq $env{'user.domain'}) {
7028: $can_request->{$type} = 1;
7029: }
7030: }
7031: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7032: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7033: if (@curr > 0) {
1.1036 raeburn 7034: foreach my $item (@curr) {
7035: if (ref($request_domains) eq 'HASH') {
7036: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7037: if ($otherdom ne '') {
7038: if (ref($request_domains->{$type}) eq 'ARRAY') {
7039: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7040: push(@{$request_domains->{$type}},$otherdom);
7041: }
7042: } else {
7043: push(@{$request_domains->{$type}},$otherdom);
7044: }
7045: }
7046: }
7047: }
7048: unless($dom eq $env{'user.domain'}) {
7049: $canreq ++;
1.1035 raeburn 7050: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7051: $can_request->{$type} = 1;
7052: }
7053: }
7054: }
7055: }
7056: }
7057: }
7058: return $canreq;
7059: }
7060:
1.341 www 7061: # ---------------------------------------------- Custom access rule evaluation
7062:
7063: sub customaccess {
7064: my ($priv,$uri)=@_;
1.807 albertel 7065: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7066: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7067: $udom = &LONCAPA::clean_domain($udom);
7068: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7069: my $access=0;
1.800 albertel 7070: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7071: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7072: if ($type eq 'user') {
7073: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7074: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7075: if ($tdom) {
7076: if ($tdom ne $env{'user.domain'}) { next; }
7077: }
1.896 albertel 7078: if ($tuname) {
7079: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7080: }
7081: $access=($effect eq 'allow');
7082: last;
7083: }
7084: } else {
7085: if ($role) {
7086: if ($role ne $urole) { next; }
7087: }
7088: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7089: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7090: if ($tdom) {
7091: if ($tdom ne $udom) { next; }
7092: }
7093: if ($tcrs) {
7094: if ($tcrs ne $ucrs) { next; }
7095: }
7096: if ($tsec) {
7097: if ($tsec ne $usec) { next; }
7098: }
7099: $access=($effect eq 'allow');
7100: last;
7101: }
7102: if ($realm eq '' && $role eq '') {
7103: $access=($effect eq 'allow');
7104: }
1.402 bowersj2 7105: }
1.341 www 7106: }
7107: return $access;
7108: }
7109:
1.103 harris41 7110: # ------------------------------------------------- Check for a user privilege
1.12 www 7111:
7112: sub allowed {
1.1172.2.65 raeburn 7113: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7114: my $ver_orguri=$uri;
1.439 www 7115: $uri=&deversion($uri);
1.152 www 7116: my $orguri=$uri;
1.52 www 7117: $uri=&declutter($uri);
1.809 raeburn 7118:
1.810 raeburn 7119: if ($priv eq 'evb') {
7120: # Evade communication block restrictions for specified role in a course
7121: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7122: return $1;
7123: } else {
7124: return;
7125: }
7126: }
7127:
1.620 albertel 7128: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7129: # Free bre access to adm and meta resources
1.775 albertel 7130: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7131: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7132: && ($priv eq 'bre')) {
1.14 www 7133: return 'F';
1.159 www 7134: }
7135:
1.545 banghart 7136: # Free bre access to user's own portfolio contents
1.714 raeburn 7137: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7138: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7139: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7140: my %setters;
7141: my ($startblock,$endblock) =
7142: &Apache::loncommon::blockcheck(\%setters,'port');
7143: if ($startblock && $endblock) {
7144: return 'B';
7145: } else {
7146: return 'F';
7147: }
1.545 banghart 7148: }
7149:
1.762 raeburn 7150: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7151: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7152: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7153: if (exists($env{'request.course.id'})) {
7154: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7155: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7156: if (($domain eq $cdom) && ($name eq $cnum)) {
7157: my $courseprivid=$env{'request.course.id'};
7158: $courseprivid=~s/\_/\//;
7159: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7160: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7161: return $1;
1.762 raeburn 7162: } else {
7163: if ($env{'request.course.sec'}) {
7164: $courseprivid.='/'.$env{'request.course.sec'};
7165: }
7166: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7167: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7168: return $2;
7169: }
1.714 raeburn 7170: }
7171: }
7172: }
7173: }
7174:
1.159 www 7175: # Free bre to public access
7176:
7177: if ($priv eq 'bre') {
1.238 www 7178: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7179: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7180: return 'F';
7181: }
1.238 www 7182: if ($copyright eq 'priv') {
7183: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7184: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7185: return '';
7186: }
7187: }
7188: if ($copyright eq 'domain') {
7189: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7190: unless (($env{'user.domain'} eq $1) ||
7191: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7192: return '';
7193: }
1.262 matthew 7194: }
1.620 albertel 7195: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7196: # Library role, so allow browsing of resources in this domain.
7197: return 'F';
1.238 www 7198: }
1.341 www 7199: if ($copyright eq 'custom') {
7200: unless (&customaccess($priv,$uri)) { return ''; }
7201: }
1.14 www 7202: }
1.264 matthew 7203: # Domain coordinator is trying to create a course
1.620 albertel 7204: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7205: # uri is the requested domain in this case.
7206: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7207: # a role of dc for the domain in question.
1.620 albertel 7208: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7209: }
1.29 www 7210:
1.52 www 7211: my $thisallowed='';
7212: my $statecond=0;
7213: my $courseprivid='';
7214:
1.1039 raeburn 7215: my $ownaccess;
1.1043 raeburn 7216: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7217: if (($priv eq 'bro') && ($env{'user.author'})) {
7218: if ($uri eq '') {
7219: $ownaccess = 1;
7220: } else {
7221: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7222: my $udom = $env{'user.domain'};
7223: my $uname = $env{'user.name'};
7224: if ($uri =~ m{^\Q$udom\E/?$}) {
7225: $ownaccess = 1;
1.1040 raeburn 7226: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7227: unless ($uri =~ m{\.\./}) {
7228: $ownaccess = 1;
7229: }
7230: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7231: my $now = time;
7232: if ($uri =~ m{^([^/]+)/?$}) {
7233: my $adom = $1;
7234: foreach my $key (keys(%env)) {
1.1042 raeburn 7235: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7236: my ($start,$end) = split('.',$env{$key});
7237: if (($now >= $start) && (!$end || $end < $now)) {
7238: $ownaccess = 1;
7239: last;
7240: }
7241: }
7242: }
7243: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7244: my $adom = $1;
7245: my $aname = $2;
1.1042 raeburn 7246: foreach my $role ('ca','aa') {
7247: if ($env{"user.role.$role./$adom/$aname"}) {
7248: my ($start,$end) =
7249: split('.',$env{"user.role.$role./$adom/$aname"});
7250: if (($now >= $start) && (!$end || $end < $now)) {
7251: $ownaccess = 1;
7252: last;
7253: }
1.1039 raeburn 7254: }
7255: }
7256: }
7257: }
7258: }
7259: }
7260: }
7261:
1.52 www 7262: # Course
7263:
1.620 albertel 7264: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7265: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7266: $thisallowed.=$1;
7267: }
1.52 www 7268: }
1.29 www 7269:
1.52 www 7270: # Domain
7271:
1.620 albertel 7272: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7273: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7274: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7275: $thisallowed.=$1;
7276: }
1.12 www 7277: }
1.52 www 7278:
1.1141 raeburn 7279: # User who is not author or co-author might still be able to edit
7280: # resource of an author in the domain (e.g., if Domain Coordinator).
7281: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7282: (&allowed('mdc',$env{'request.course.id'}))) {
7283: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7284: $thisallowed.=$1;
7285: }
7286: }
7287:
1.52 www 7288: # Course: uri itself is a course
1.66 www 7289: my $courseuri=$uri;
7290: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7291: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7292:
1.620 albertel 7293: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7294: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7295: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7296: $thisallowed.=$1;
7297: }
1.12 www 7298: }
1.29 www 7299:
1.665 albertel 7300: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7301: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7302: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7303: $thisallowed='';
1.671 raeburn 7304: my ($match)=&is_on_map($uri);
7305: if ($match) {
7306: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7307: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7308: my $value = $1;
7309: if ($noblockcheck) {
7310: $thisallowed.=$value;
1.1162 raeburn 7311: } else {
1.1172.2.65 raeburn 7312: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7313: if (@blockers > 0) {
7314: $thisallowed = 'B';
7315: } else {
7316: $thisallowed.=$value;
7317: }
1.1162 raeburn 7318: }
1.671 raeburn 7319: }
7320: } else {
1.705 albertel 7321: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7322: if ($refuri) {
7323: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7324: $thisallowed='F';
1.671 raeburn 7325: } else {
7326: $refuri=&declutter($refuri);
7327: my ($match) = &is_on_map($refuri);
7328: if ($match) {
1.1172.2.65 raeburn 7329: if ($noblockcheck) {
1.1162 raeburn 7330: $thisallowed='F';
1.1172.2.65 raeburn 7331: } else {
7332: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7333: if (@blockers > 0) {
7334: $thisallowed = 'B';
7335: } else {
7336: $thisallowed='F';
7337: }
1.1162 raeburn 7338: }
1.671 raeburn 7339: }
1.669 raeburn 7340: }
1.671 raeburn 7341: }
7342: }
1.314 www 7343: }
1.492 albertel 7344:
1.766 albertel 7345: if ($priv eq 'bre'
7346: && $thisallowed ne 'F'
7347: && $thisallowed ne '2'
7348: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7349: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7350: }
7351:
1.52 www 7352: # Full access at system, domain or course-wide level? Exit.
1.29 www 7353: if ($thisallowed=~/F/) {
7354: return 'F';
7355: }
7356:
1.52 www 7357: # If this is generating or modifying users, exit with special codes
1.29 www 7358:
1.643 www 7359: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7360: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7361: my ($audom,$auname)=split('/',$uri);
1.643 www 7362: # no author name given, so this just checks on the general right to make a co-author in this domain
7363: unless ($auname) { return $thisallowed; }
7364: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7365: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7366: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7367: ($audom ne $env{'request.role.domain'}))) { return ''; }
7368: }
1.52 www 7369: return $thisallowed;
7370: }
7371: #
1.103 harris41 7372: # Gathered so far: system, domain and course wide privileges
1.52 www 7373: #
7374: # Course: See if uri or referer is an individual resource that is part of
7375: # the course
7376:
1.620 albertel 7377: if ($env{'request.course.id'}) {
1.232 www 7378:
1.620 albertel 7379: $courseprivid=$env{'request.course.id'};
7380: if ($env{'request.course.sec'}) {
7381: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7382: }
7383: $courseprivid=~s/\_/\//;
7384: my $checkreferer=1;
1.232 www 7385: my ($match,$cond)=&is_on_map($uri);
7386: if ($match) {
7387: $statecond=$cond;
1.620 albertel 7388: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7389: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7390: my $value = $1;
7391: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7392: if ($noblockcheck) {
1.1162 raeburn 7393: $thisallowed.=$value;
1.1172.2.65 raeburn 7394: } else {
7395: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7396: if (@blockers > 0) {
7397: $thisallowed = 'B';
7398: } else {
7399: $thisallowed.=$value;
7400: }
1.1162 raeburn 7401: }
7402: } else {
7403: $thisallowed.=$value;
7404: }
1.52 www 7405: $checkreferer=0;
7406: }
1.29 www 7407: }
1.83 www 7408:
1.148 www 7409: if ($checkreferer) {
1.620 albertel 7410: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7411: unless ($refuri) {
1.800 albertel 7412: foreach my $key (keys(%env)) {
7413: if ($key=~/^httpref\..*\*/) {
7414: my $pattern=$key;
1.156 www 7415: $pattern=~s/^httpref\.\/res\///;
1.148 www 7416: $pattern=~s/\*/\[\^\/\]\+/g;
7417: $pattern=~s/\//\\\//g;
1.152 www 7418: if ($orguri=~/$pattern/) {
1.800 albertel 7419: $refuri=$env{$key};
1.148 www 7420: }
7421: }
1.191 harris41 7422: }
1.148 www 7423: }
1.232 www 7424:
1.148 www 7425: if ($refuri) {
1.152 www 7426: $refuri=&declutter($refuri);
1.232 www 7427: my ($match,$cond)=&is_on_map($refuri);
7428: if ($match) {
7429: my $refstatecond=$cond;
1.620 albertel 7430: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7431: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7432: my $value = $1;
7433: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7434: if ($noblockcheck) {
1.1162 raeburn 7435: $thisallowed.=$value;
1.1172.2.65 raeburn 7436: } else {
7437: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7438: if (@blockers > 0) {
7439: $thisallowed = 'B';
7440: } else {
7441: $thisallowed.=$value;
7442: }
1.1162 raeburn 7443: }
7444: } else {
7445: $thisallowed.=$value;
7446: }
1.53 www 7447: $uri=$refuri;
7448: $statecond=$refstatecond;
1.52 www 7449: }
7450: }
1.148 www 7451: }
1.29 www 7452: }
1.52 www 7453: }
1.29 www 7454:
1.52 www 7455: #
1.103 harris41 7456: # Gathered now: all privileges that could apply, and condition number
1.52 www 7457: #
7458: #
7459: # Full or no access?
7460: #
1.29 www 7461:
1.52 www 7462: if ($thisallowed=~/F/) {
7463: return 'F';
7464: }
1.29 www 7465:
1.52 www 7466: unless ($thisallowed) {
7467: return '';
7468: }
1.29 www 7469:
1.52 www 7470: # Restrictions exist, deal with them
7471: #
7472: # C:according to course preferences
7473: # R:according to resource settings
7474: # L:unless locked
7475: # X:according to user session state
7476: #
7477:
7478: # Possibly locked functionality, check all courses
1.54 www 7479: # Locks might take effect only after 10 minutes cache expiration for other
7480: # courses, and 2 minutes for current course
1.52 www 7481:
7482: my $envkey;
7483: if ($thisallowed=~/L/) {
1.1000 raeburn 7484: foreach $envkey (keys(%env)) {
1.54 www 7485: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7486: my $courseid=$2;
7487: my $roleid=$1.'.'.$2;
1.92 www 7488: $courseid=~s/^\///;
1.54 www 7489: my $expiretime=600;
1.620 albertel 7490: if ($env{'request.role'} eq $roleid) {
1.54 www 7491: $expiretime=120;
7492: }
7493: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7494: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7495: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7496: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7497: }
1.620 albertel 7498: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7499: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7500: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7501: &log($env{'user.domain'},$env{'user.name'},
7502: $env{'user.home'},
1.57 www 7503: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7504: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7505: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7506: return '';
7507: }
7508: }
1.620 albertel 7509: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7510: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7511: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7512: &log($env{'user.domain'},$env{'user.name'},
7513: $env{'user.home'},
1.57 www 7514: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7515: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7516: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7517: return '';
7518: }
7519: }
7520: }
1.29 www 7521: }
1.52 www 7522: }
7523:
7524: #
7525: # Rest of the restrictions depend on selected course
7526: #
7527:
1.620 albertel 7528: unless ($env{'request.course.id'}) {
1.766 albertel 7529: if ($thisallowed eq 'A') {
7530: return 'A';
1.814 raeburn 7531: } elsif ($thisallowed eq 'B') {
7532: return 'B';
1.766 albertel 7533: } else {
7534: return '1';
7535: }
1.52 www 7536: }
1.29 www 7537:
1.52 www 7538: #
7539: # Now user is definitely in a course
7540: #
1.53 www 7541:
7542:
7543: # Course preferences
7544:
7545: if ($thisallowed=~/C/) {
1.620 albertel 7546: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7547: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7548: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7549: =~/\Q$rolecode\E/) {
1.1103 raeburn 7550: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7551: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7552: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7553: $env{'request.course.id'});
7554: }
1.237 www 7555: return '';
7556: }
7557:
1.620 albertel 7558: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7559: =~/\Q$unamedom\E/) {
1.1103 raeburn 7560: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7561: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7562: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7563: $env{'request.course.id'});
7564: }
1.54 www 7565: return '';
7566: }
1.53 www 7567: }
7568:
7569: # Resource preferences
7570:
7571: if ($thisallowed=~/R/) {
1.620 albertel 7572: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7573: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7574: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7575: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7576: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7577: }
7578: return '';
1.54 www 7579: }
1.53 www 7580: }
1.30 www 7581:
1.246 www 7582: # Restricted by state or randomout?
1.30 www 7583:
1.52 www 7584: if ($thisallowed=~/X/) {
1.620 albertel 7585: if ($env{'acc.randomout'}) {
1.579 albertel 7586: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7587: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7588: return '';
7589: }
1.247 www 7590: }
7591: if (&condval($statecond)) {
1.52 www 7592: return '2';
7593: } else {
7594: return '';
7595: }
7596: }
1.30 www 7597:
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: }
1.52 www 7603: return 'F';
1.232 www 7604: }
1.1162 raeburn 7605:
1.1172.2.13 raeburn 7606: # ------------------------------------------- Check construction space access
7607:
7608: sub constructaccess {
7609: my ($url,$setpriv)=@_;
7610:
7611: # We do not allow editing of previous versions of files
7612: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7613:
7614: # Get username and domain from URL
7615: my ($ownername,$ownerdomain,$ownerhome);
7616:
7617: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7618: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7619:
7620: # The URL does not really point to any authorspace, forget it
7621: unless (($ownername) && ($ownerdomain)) { return ''; }
7622:
7623: # Now we need to see if the user has access to the authorspace of
7624: # $ownername at $ownerdomain
7625:
7626: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7627: # Real author for this?
7628: $ownerhome = $env{'user.home'};
7629: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7630: return ($ownername,$ownerdomain,$ownerhome);
7631: }
7632: } else {
7633: # Co-author for this?
7634: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7635: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7636: $ownerhome = &homeserver($ownername,$ownerdomain);
7637: return ($ownername,$ownerdomain,$ownerhome);
7638: }
7639: }
7640:
7641: # We don't have any access right now. If we are not possibly going to do anything about this,
7642: # we might as well leave
7643: unless ($setpriv) { return ''; }
7644:
7645: # Backdoor access?
7646: my $allowed=&allowed('eco',$ownerdomain);
7647: # Nope
7648: unless ($allowed) { return ''; }
7649: # Looks like we may have access, but could be locked by the owner of the construction space
7650: if ($allowed eq 'U') {
7651: my %blocked=&get('environment',['domcoord.author'],
7652: $ownerdomain,$ownername);
7653: # Is blocked by owner
7654: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7655: }
7656: if (($allowed eq 'F') || ($allowed eq 'U')) {
7657: # Grant temporary access
7658: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7659: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7660: if (!$update) { $update = $then; }
7661: my $refresh=$env{'user.refresh.time'};
7662: if (!$refresh) { $refresh = $update; }
7663: my $now = time;
7664: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7665: $now,'ca','constructaccess');
7666: $ownerhome = &homeserver($ownername,$ownerdomain);
7667: return($ownername,$ownerdomain,$ownerhome);
7668: }
7669: # No business here
7670: return '';
7671: }
7672:
1.1172.2.66 raeburn 7673: # ----------------------------------------------------------- Content Blocking
7674:
7675: {
7676: # Caches for faster Course Contents display where content blocking
7677: # is in operation (i.e., interval param set) for timed quiz.
7678: #
7679: # User for whom data are being temporarily cached.
7680: my $cacheduser='';
7681: # Cached blockers for this user (a hash of blocking items).
7682: my %cachedblockers=();
7683: # When the data were last cached.
7684: my $cachedlast='';
7685:
7686: sub load_all_blockers {
7687: my ($uname,$udom,$blocks)=@_;
7688: if (($uname ne '') && ($udom ne '')) {
7689: if (($cacheduser eq $uname.':'.$udom) &&
7690: (abs($cachedlast-time)<5)) {
7691: return;
7692: }
7693: }
7694: $cachedlast=time;
7695: $cacheduser=$uname.':'.$udom;
7696: %cachedblockers = &get_commblock_resources($blocks);
7697: }
7698:
1.1162 raeburn 7699: sub get_comm_blocks {
7700: my ($cdom,$cnum) = @_;
7701: if ($cdom eq '' || $cnum eq '') {
7702: return unless ($env{'request.course.id'});
7703: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7704: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7705: }
7706: my %commblocks;
7707: my $hashid=$cdom.'_'.$cnum;
7708: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7709: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7710: %commblocks = %{$blocksref};
7711: } else {
7712: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7713: my $cachetime = 600;
7714: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7715: }
7716: return %commblocks;
7717: }
7718:
1.1172.2.66 raeburn 7719: sub get_commblock_resources {
7720: my ($blocks) = @_;
7721: my %blockers = ();
7722: return %blockers unless ($env{'request.course.id'});
7723: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7724: my %commblocks;
7725: if (ref($blocks) eq 'HASH') {
7726: %commblocks = %{$blocks};
7727: } else {
7728: %commblocks = &get_comm_blocks();
7729: }
1.1172.2.66 raeburn 7730: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7731: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7732: return %blockers unless (ref($navmap));
7733: my $now = time;
1.1162 raeburn 7734: foreach my $block (keys(%commblocks)) {
7735: if ($block =~ /^(\d+)____(\d+)$/) {
7736: my ($start,$end) = ($1,$2);
7737: if ($start <= $now && $end >= $now) {
7738: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7739: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7740: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7741: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7742: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7743: }
7744: }
7745: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7746: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7747: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7748: }
7749: }
7750: }
7751: }
7752: }
7753: } elsif ($block =~ /^firstaccess____(.+)$/) {
7754: my $item = $1;
1.1163 raeburn 7755: my @to_test;
1.1162 raeburn 7756: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7757: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7758: my @interval;
7759: my $type = 'map';
7760: if ($item eq 'course') {
7761: $type = 'course';
7762: @interval=&EXT("resource.0.interval");
7763: } else {
7764: if ($item =~ /___\d+___/) {
7765: $type = 'resource';
7766: @interval=&EXT("resource.0.interval",$item);
7767: if (ref($navmap)) {
7768: my $res = $navmap->getBySymb($item);
7769: push(@to_test,$res);
7770: }
1.1162 raeburn 7771: } else {
1.1172.2.66 raeburn 7772: my $mapsymb = &symbread($item,1);
7773: if ($mapsymb) {
7774: if (ref($navmap)) {
7775: my $mapres = $navmap->getBySymb($mapsymb);
7776: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7777: foreach my $res (@to_test) {
7778: my $symb = $res->symb();
7779: next if ($symb eq $mapsymb);
7780: if ($symb ne '') {
7781: @interval=&EXT("resource.0.interval",$symb);
7782: if ($interval[1] eq 'map') {
7783: last;
1.1162 raeburn 7784: }
7785: }
7786: }
7787: }
7788: }
7789: }
1.1172.2.66 raeburn 7790: }
7791: if ($interval[0] =~ /^\d+$/) {
7792: my $first_access;
7793: if ($type eq 'resource') {
7794: $first_access=&get_first_access($interval[1],$item);
7795: } elsif ($type eq 'map') {
7796: $first_access=&get_first_access($interval[1],undef,$item);
7797: } else {
7798: $first_access=&get_first_access($interval[1]);
7799: }
7800: if ($first_access) {
7801: my $timesup = $first_access+$interval[0];
7802: if ($timesup > $now) {
7803: my $activeblock;
7804: foreach my $res (@to_test) {
7805: if ($res->answerable()) {
7806: $activeblock = 1;
7807: last;
7808: }
7809: }
7810: if ($activeblock) {
7811: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7812: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7813: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7814: }
7815: }
7816: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7817: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7818: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7819: }
1.1162 raeburn 7820: }
7821: }
7822: }
7823: }
7824: }
7825: }
7826: }
7827: }
7828: }
1.1172.2.66 raeburn 7829: return %blockers;
1.1162 raeburn 7830: }
7831:
1.1172.2.66 raeburn 7832: sub has_comm_blocking {
7833: my ($priv,$symb,$uri,$blocks) = @_;
7834: my @blockers;
7835: return unless ($env{'request.course.id'});
7836: return unless ($priv eq 'bre');
7837: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7838: return if ($env{'request.state'} eq 'construct');
7839: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7840: return unless (keys(%cachedblockers) > 0);
7841: my (%possibles,@symbs);
7842: if (!$symb) {
7843: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7844: }
1.1172.2.66 raeburn 7845: if ($symb) {
7846: @symbs = ($symb);
7847: } elsif (keys(%possibles)) {
7848: @symbs = keys(%possibles);
7849: }
7850: my $noblock;
7851: foreach my $symb (@symbs) {
7852: last if ($noblock);
7853: my ($map,$resid,$resurl)=&decode_symb($symb);
7854: foreach my $block (keys(%cachedblockers)) {
7855: if ($block =~ /^firstaccess____(.+)$/) {
7856: my $item = $1;
7857: if (($item eq $map) || ($item eq $symb)) {
7858: $noblock = 1;
7859: last;
7860: }
1.1162 raeburn 7861: }
1.1172.2.66 raeburn 7862: if (ref($cachedblockers{$block}) eq 'HASH') {
7863: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7864: if ($cachedblockers{$block}{'resources'}{$symb}) {
7865: unless (grep(/^\Q$block\E$/,@blockers)) {
7866: push(@blockers,$block);
7867: }
7868: }
7869: }
7870: }
7871: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7872: if ($cachedblockers{$block}{'maps'}{$map}) {
7873: unless (grep(/^\Q$block\E$/,@blockers)) {
7874: push(@blockers,$block);
7875: }
7876: }
1.1162 raeburn 7877: }
7878: }
7879: }
1.1172.2.66 raeburn 7880: return if ($noblock);
7881: return @blockers;
7882: }
1.1162 raeburn 7883: }
7884:
1.1172.2.66 raeburn 7885: # -------------------------------- Deversion and split uri into path an filename
7886:
1.1133 foxr 7887: #
1.1172.2.66 raeburn 7888: # Removes the version from a URI and
1.1133 foxr 7889: # splits it in to its filename and path to the filename.
7890: # Seems like File::Basename could have done this more clearly.
7891: # Parameters:
7892: # $uri - input URI
7893: # Returns:
7894: # Two element list consisting of
7895: # $pathname - the URI up to and excluding the trailing /
7896: # $filename - The part of the URI following the last /
7897: # NOTE:
7898: # Another realization of this is simply:
7899: # use File::Basename;
7900: # ...
7901: # $uri = shift;
7902: # $filename = basename($uri);
7903: # $path = dirname($uri);
7904: # return ($filename, $path);
7905: #
7906: # The implementation below is probably faster however.
7907: #
1.710 albertel 7908: sub split_uri_for_cond {
7909: my $uri=&deversion(&declutter(shift));
7910: my @uriparts=split(/\//,$uri);
7911: my $filename=pop(@uriparts);
7912: my $pathname=join('/',@uriparts);
7913: return ($pathname,$filename);
7914: }
1.232 www 7915: # --------------------------------------------------- Is a resource on the map?
7916:
7917: sub is_on_map {
1.710 albertel 7918: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7919: #Trying to find the conditional for the file
1.620 albertel 7920: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7921: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7922: if ($match) {
1.289 bowersj2 7923: return (1,$1);
7924: } else {
1.434 www 7925: return (0,0);
1.289 bowersj2 7926: }
1.12 www 7927: }
7928:
1.427 www 7929: # --------------------------------------------------------- Get symb from alias
7930:
7931: sub get_symb_from_alias {
7932: my $symb=shift;
7933: my ($map,$resid,$url)=&decode_symb($symb);
7934: # Already is a symb
7935: if ($url) { return $symb; }
7936: # Must be an alias
7937: my $aliassymb='';
7938: my %bighash;
1.620 albertel 7939: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7940: &GDBM_READER(),0640)) {
7941: my $rid=$bighash{'mapalias_'.$symb};
7942: if ($rid) {
7943: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7944: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7945: $resid,$bighash{'src_'.$rid});
1.427 www 7946: }
7947: untie %bighash;
7948: }
7949: return $aliassymb;
7950: }
7951:
1.12 www 7952: # ----------------------------------------------------------------- Define Role
7953:
7954: sub definerole {
7955: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 7956: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7957: foreach my $role (split(':',$sysrole)) {
7958: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7959: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7960: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7961: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7962: return "refused:s:$crole&$cqual";
7963: }
7964: }
1.191 harris41 7965: }
1.800 albertel 7966: foreach my $role (split(':',$domrole)) {
7967: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7968: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7969: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7970: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7971: return "refused:d:$crole&$cqual";
7972: }
7973: }
1.191 harris41 7974: }
1.800 albertel 7975: foreach my $role (split(':',$courole)) {
7976: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7977: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7978: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7979: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7980: return "refused:c:$crole&$cqual";
7981: }
7982: }
1.191 harris41 7983: }
1.1172.2.84 raeburn 7984: my $uhome;
7985: if (($uname ne '') && ($udom ne '')) {
7986: $uhome = &homeserver($uname,$udom);
7987: return $uhome if ($uhome eq 'no_host');
7988: } else {
7989: $uname = $env{'user.name'};
7990: $udom = $env{'user.domain'};
7991: $uhome = $env{'user.home'};
7992: }
1.620 albertel 7993: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 7994: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7995: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 7996: return reply($command,$uhome);
1.12 www 7997: } else {
7998: return 'refused';
7999: }
1.105 harris41 8000: }
8001:
8002: # ---------------- Make a metadata query against the network of library servers
8003:
8004: sub metadata_query {
1.1172.2.33 raeburn 8005: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8006: my %rhash;
1.845 albertel 8007: my %libserv = &all_library();
1.244 matthew 8008: my @server_list = (defined($server_array) ? @$server_array
8009: : keys(%libserv) );
8010: for my $server (@server_list) {
1.1172.2.33 raeburn 8011: my $domains = '';
8012: if (ref($domains_hash) eq 'HASH') {
8013: $domains = $domains_hash->{$server};
8014: }
1.118 harris41 8015: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8016: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8017: $rhash{$server}=$reply;
8018: }
8019: else {
8020: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8021: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8022: $server);
8023: $rhash{$server}=$reply;
8024: }
1.112 harris41 8025: }
1.118 harris41 8026: return \%rhash;
1.240 www 8027: }
8028:
8029: # ----------------------------------------- Send log queries and wait for reply
8030:
8031: sub log_query {
8032: my ($uname,$udom,$query,%filters)=@_;
8033: my $uhome=&homeserver($uname,$udom);
8034: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8035: my $uhost=&hostname($uhome);
1.800 albertel 8036: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8037: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8038: $uhome);
1.479 albertel 8039: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8040: return get_query_reply($queryid);
8041: }
8042:
1.818 raeburn 8043: # -------------------------- Update MySQL table for portfolio file
8044:
8045: sub update_portfolio_table {
1.821 raeburn 8046: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8047: if ($group ne '') {
8048: $file_name =~s /^\Q$group\E//;
8049: }
1.818 raeburn 8050: my $homeserver = &homeserver($uname,$udom);
8051: my $queryid=
1.821 raeburn 8052: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8053: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8054: my $reply = &get_query_reply($queryid);
8055: return $reply;
8056: }
8057:
1.899 raeburn 8058: # -------------------------- Update MySQL allusers table
8059:
8060: sub update_allusers_table {
8061: my ($uname,$udom,$names) = @_;
8062: my $homeserver = &homeserver($uname,$udom);
8063: my $queryid=
8064: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8065: 'lastname='.&escape($names->{'lastname'}).'%%'.
8066: 'firstname='.&escape($names->{'firstname'}).'%%'.
8067: 'middlename='.&escape($names->{'middlename'}).'%%'.
8068: 'generation='.&escape($names->{'generation'}).'%%'.
8069: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8070: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8071: return;
1.899 raeburn 8072: }
8073:
1.508 raeburn 8074: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8075:
8076: sub fetch_enrollment_query {
1.511 raeburn 8077: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8078: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8079: my $maxtries = 1;
1.508 raeburn 8080: if ($context eq 'automated') {
8081: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8082: $sleep = 2;
8083: $loopmax = 100;
1.547 raeburn 8084: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8085: } else {
8086: $homeserver = &homeserver($cnum,$dom);
8087: }
1.838 albertel 8088: my $host=&hostname($homeserver);
1.506 raeburn 8089: my $cmd = '';
1.1000 raeburn 8090: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8091: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8092: }
8093: $cmd =~ s/%%$//;
8094: $cmd = &escape($cmd);
8095: my $query = 'fetchenrollment';
1.620 albertel 8096: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8097: unless ($queryid=~/^\Q$host\E\_/) {
8098: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8099: return 'error: '.$queryid;
8100: }
1.1172.2.93 raeburn 8101: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8102: my $tries = 1;
8103: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8104: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8105: $tries ++;
8106: }
1.526 raeburn 8107: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8108: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8109: } else {
1.901 albertel 8110: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8111: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8112: foreach my $line (@responses) {
8113: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8114: $$replyref{$key} = $value;
8115: }
8116: } else {
1.1117 foxr 8117: my $pathname = LONCAPA::tempdir();
1.800 albertel 8118: foreach my $line (@responses) {
8119: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8120: $$replyref{$key} = $value;
8121: if ($value > 0) {
1.800 albertel 8122: foreach my $item (@{$$affiliatesref{$key}}) {
8123: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8124: my $destname = $pathname.'/'.$filename;
8125: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8126: if ($xml_classlist =~ /^error/) {
8127: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8128: } else {
1.1172.2.96! raeburn 8129: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8130: print FILE &unescape($xml_classlist);
8131: close(FILE);
1.526 raeburn 8132: } else {
8133: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8134: }
8135: }
8136: }
8137: }
8138: }
8139: }
8140: return 'ok';
8141: }
8142: return 'error';
8143: }
8144:
1.242 www 8145: sub get_query_reply {
1.1172.2.79 raeburn 8146: my ($queryid,$sleep,$loopmax) = @_;
8147: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8148: $sleep = 0.2;
8149: }
8150: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8151: $loopmax = 100;
8152: }
1.1117 foxr 8153: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8154: my $reply='';
1.1172.2.79 raeburn 8155: for (1..$loopmax) {
8156: sleep($sleep);
1.240 www 8157: if (-e $replyfile.'.end') {
1.1172.2.96! raeburn 8158: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8159: $reply = join('',<$fh>);
8160: close($fh);
1.240 www 8161: } else { return 'error: reply_file_error'; }
1.242 www 8162: return &unescape($reply);
8163: }
1.240 www 8164: }
1.242 www 8165: return 'timeout:'.$queryid;
1.240 www 8166: }
8167:
8168: sub courselog_query {
1.241 www 8169: #
8170: # possible filters:
8171: # url: url or symb
8172: # username
8173: # domain
8174: # action: view, submit, grade
8175: # start: timestamp
8176: # end: timestamp
8177: #
1.240 www 8178: my (%filters)=@_;
1.620 albertel 8179: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8180: if ($filters{'url'}) {
8181: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8182: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8183: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8184: }
1.620 albertel 8185: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8186: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8187: return &log_query($cname,$cdom,'courselog',%filters);
8188: }
8189:
8190: sub userlog_query {
1.858 raeburn 8191: #
8192: # possible filters:
8193: # action: log check role
8194: # start: timestamp
8195: # end: timestamp
8196: #
1.240 www 8197: my ($uname,$udom,%filters)=@_;
8198: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8199: }
8200:
1.506 raeburn 8201: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8202:
8203: sub auto_run {
1.508 raeburn 8204: my ($cnum,$cdom) = @_;
1.876 raeburn 8205: my $response = 0;
8206: my $settings;
8207: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8208: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8209: $settings = $domconfig{'autoenroll'};
8210: if ($settings->{'run'} eq '1') {
8211: $response = 1;
8212: }
8213: } else {
1.934 raeburn 8214: my $homeserver;
8215: if (&is_course($cdom,$cnum)) {
8216: $homeserver = &homeserver($cnum,$cdom);
8217: } else {
8218: $homeserver = &domain($cdom,'primary');
8219: }
8220: if ($homeserver ne 'no_host') {
8221: $response = &reply('autorun:'.$cdom,$homeserver);
8222: }
1.876 raeburn 8223: }
1.506 raeburn 8224: return $response;
8225: }
1.776 albertel 8226:
1.506 raeburn 8227: sub auto_get_sections {
1.508 raeburn 8228: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8229: my $homeserver;
8230: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8231: $homeserver = &homeserver($cnum,$cdom);
8232: }
8233: if (!defined($homeserver)) {
8234: if ($cdom =~ /^$match_domain$/) {
8235: $homeserver = &domain($cdom,'primary');
8236: }
8237: }
8238: my @secs;
8239: if (defined($homeserver)) {
8240: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8241: unless ($response eq 'refused') {
8242: @secs = split(/:/,$response);
8243: }
1.506 raeburn 8244: }
8245: return @secs;
8246: }
1.776 albertel 8247:
1.506 raeburn 8248: sub auto_new_course {
1.1099 raeburn 8249: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8250: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8251: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8252: return $response;
8253: }
1.776 albertel 8254:
1.506 raeburn 8255: sub auto_validate_courseID {
1.508 raeburn 8256: my ($cnum,$cdom,$inst_course_id) = @_;
8257: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8258: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8259: return $response;
8260: }
1.776 albertel 8261:
1.1007 raeburn 8262: sub auto_validate_instcode {
1.1020 raeburn 8263: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8264: my ($homeserver,$response);
8265: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8266: $homeserver = &homeserver($cnum,$cdom);
8267: }
8268: if (!defined($homeserver)) {
8269: if ($cdom =~ /^$match_domain$/) {
8270: $homeserver = &domain($cdom,'primary');
8271: }
8272: }
1.1065 raeburn 8273: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8274: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8275: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8276: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8277: }
8278:
1.506 raeburn 8279: sub auto_create_password {
1.873 raeburn 8280: my ($cnum,$cdom,$authparam,$udom) = @_;
8281: my ($homeserver,$response);
1.506 raeburn 8282: my $create_passwd = 0;
8283: my $authchk = '';
1.873 raeburn 8284: if ($udom =~ /^$match_domain$/) {
8285: $homeserver = &domain($udom,'primary');
8286: }
8287: if ($homeserver eq '') {
8288: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8289: $homeserver = &homeserver($cnum,$cdom);
8290: }
8291: }
8292: if ($homeserver eq '') {
8293: $authchk = 'nodomain';
1.506 raeburn 8294: } else {
1.873 raeburn 8295: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8296: if ($response eq 'refused') {
8297: $authchk = 'refused';
8298: } else {
1.901 albertel 8299: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8300: }
1.506 raeburn 8301: }
8302: return ($authparam,$create_passwd,$authchk);
8303: }
8304:
1.706 raeburn 8305: sub auto_photo_permission {
8306: my ($cnum,$cdom,$students) = @_;
8307: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8308: my ($outcome,$perm_reqd,$conditions) =
8309: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8310: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8311: return (undef,undef);
8312: }
1.706 raeburn 8313: return ($outcome,$perm_reqd,$conditions);
8314: }
8315:
8316: sub auto_checkphotos {
8317: my ($uname,$udom,$pid) = @_;
8318: my $homeserver = &homeserver($uname,$udom);
8319: my ($result,$resulttype);
8320: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8321: &escape($uname).':'.&escape($pid),
8322: $homeserver));
1.709 albertel 8323: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8324: return (undef,undef);
8325: }
1.706 raeburn 8326: if ($outcome) {
8327: ($result,$resulttype) = split(/:/,$outcome);
8328: }
8329: return ($result,$resulttype);
8330: }
8331:
8332: sub auto_photochoice {
8333: my ($cnum,$cdom) = @_;
8334: my $homeserver = &homeserver($cnum,$cdom);
8335: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8336: &escape($cdom),
8337: $homeserver)));
1.709 albertel 8338: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8339: return (undef,undef);
8340: }
1.706 raeburn 8341: return ($update,$comment);
8342: }
8343:
8344: sub auto_photoupdate {
8345: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8346: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8347: my $host=&hostname($homeserver);
1.706 raeburn 8348: my $cmd = '';
8349: my $maxtries = 1;
1.800 albertel 8350: foreach my $affiliate (keys(%{$affiliatesref})) {
8351: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8352: }
8353: $cmd =~ s/%%$//;
8354: $cmd = &escape($cmd);
8355: my $query = 'institutionalphotos';
8356: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8357: unless ($queryid=~/^\Q$host\E\_/) {
8358: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8359: return 'error: '.$queryid;
8360: }
8361: my $reply = &get_query_reply($queryid);
8362: my $tries = 1;
8363: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8364: $reply = &get_query_reply($queryid);
8365: $tries ++;
8366: }
8367: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8368: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8369: } else {
8370: my @responses = split(/:/,$reply);
8371: my $outcome = shift(@responses);
8372: foreach my $item (@responses) {
8373: my ($key,$value) = split(/=/,$item);
8374: $$photo{$key} = $value;
8375: }
8376: return $outcome;
8377: }
8378: return 'error';
8379: }
8380:
1.521 raeburn 8381: sub auto_instcode_format {
1.793 albertel 8382: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8383: $cat_order) = @_;
1.521 raeburn 8384: my $courses = '';
1.772 raeburn 8385: my @homeservers;
1.521 raeburn 8386: if ($caller eq 'global') {
1.841 albertel 8387: my %servers = &get_servers($codedom,'library');
8388: foreach my $tryserver (keys(%servers)) {
8389: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8390: push(@homeservers,$tryserver);
8391: }
1.584 raeburn 8392: }
1.1022 raeburn 8393: } elsif ($caller eq 'requests') {
8394: if ($codedom =~ /^$match_domain$/) {
8395: my $chome = &domain($codedom,'primary');
8396: unless ($chome eq 'no_host') {
8397: push(@homeservers,$chome);
8398: }
8399: }
1.521 raeburn 8400: } else {
1.772 raeburn 8401: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8402: }
1.793 albertel 8403: foreach my $code (keys(%{$instcodes})) {
8404: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8405: }
8406: chop($courses);
1.772 raeburn 8407: my $ok_response = 0;
8408: my $response;
8409: while (@homeservers > 0 && $ok_response == 0) {
8410: my $server = shift(@homeservers);
8411: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8412: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8413: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8414: split(/:/,$response);
1.772 raeburn 8415: %{$codes} = (%{$codes},&str2hash($codes_str));
8416: push(@{$codetitles},&str2array($codetitles_str));
8417: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8418: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8419: $ok_response = 1;
8420: }
8421: }
8422: if ($ok_response) {
1.521 raeburn 8423: return 'ok';
1.772 raeburn 8424: } else {
8425: return $response;
1.521 raeburn 8426: }
8427: }
8428:
1.792 raeburn 8429: sub auto_instcode_defaults {
8430: my ($domain,$returnhash,$code_order) = @_;
8431: my @homeservers;
1.841 albertel 8432:
8433: my %servers = &get_servers($domain,'library');
8434: foreach my $tryserver (keys(%servers)) {
8435: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8436: push(@homeservers,$tryserver);
8437: }
1.792 raeburn 8438: }
1.841 albertel 8439:
1.792 raeburn 8440: my $response;
1.841 albertel 8441: foreach my $server (@homeservers) {
1.792 raeburn 8442: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8443: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8444:
8445: foreach my $pair (split(/\&/,$response)) {
8446: my ($name,$value)=split(/\=/,$pair);
8447: if ($name eq 'code_order') {
8448: @{$code_order} = split(/\&/,&unescape($value));
8449: } else {
8450: $returnhash->{&unescape($name)}=&unescape($value);
8451: }
8452: }
8453: return 'ok';
1.792 raeburn 8454: }
1.841 albertel 8455:
8456: return $response;
1.1003 raeburn 8457: }
8458:
8459: sub auto_possible_instcodes {
1.1007 raeburn 8460: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8461: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8462: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8463: return;
8464: }
1.1003 raeburn 8465: my (@homeservers,$uhome);
8466: if (defined(&domain($domain,'primary'))) {
8467: $uhome=&domain($domain,'primary');
8468: push(@homeservers,&domain($domain,'primary'));
8469: } else {
8470: my %servers = &get_servers($domain,'library');
8471: foreach my $tryserver (keys(%servers)) {
8472: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8473: push(@homeservers,$tryserver);
8474: }
8475: }
8476: }
8477: my $response;
8478: foreach my $server (@homeservers) {
8479: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8480: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8481: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8482: split(':',$response);
8483: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8484: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8485: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8486: my ($name,$value)=split('=',$item);
8487: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8488: }
8489: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8490: my ($name,$value)=split('=',$item);
8491: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8492: }
8493: return 'ok';
8494: }
8495: return $response;
8496: }
1.792 raeburn 8497:
1.1010 raeburn 8498: sub auto_courserequest_checks {
8499: my ($dom) = @_;
1.1020 raeburn 8500: my ($homeserver,%validations);
8501: if ($dom =~ /^$match_domain$/) {
8502: $homeserver = &domain($dom,'primary');
8503: }
8504: unless ($homeserver eq 'no_host') {
8505: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8506: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8507: my @items = split(/&/,$response);
8508: foreach my $item (@items) {
8509: my ($key,$value) = split('=',$item);
8510: $validations{&unescape($key)} = &thaw_unescape($value);
8511: }
8512: }
8513: }
1.1010 raeburn 8514: return %validations;
8515: }
8516:
1.1020 raeburn 8517: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8518: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8519: my ($homeserver,$response);
8520: if ($dom =~ /^$match_domain$/) {
8521: $homeserver = &domain($dom,'primary');
8522: }
1.1172.2.43 raeburn 8523: unless ($homeserver eq 'no_host') {
8524: my $customdata;
8525: if (ref($custominfo) eq 'HASH') {
8526: $customdata = &freeze_escape($custominfo);
8527: }
1.1020 raeburn 8528: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8529: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8530: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8531: $customdata,$homeserver));
1.1020 raeburn 8532: }
8533: return $response;
8534: }
8535:
1.777 albertel 8536: sub auto_validate_class_sec {
1.918 raeburn 8537: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8538: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8539: my $ownerlist;
8540: if (ref($owners) eq 'ARRAY') {
8541: $ownerlist = join(',',@{$owners});
8542: } else {
8543: $ownerlist = $owners;
8544: }
1.773 raeburn 8545: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8546: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8547: return $response;
8548: }
8549:
1.1172.2.94 raeburn 8550: sub auto_validate_instclasses {
8551: my ($cdom,$cnum,$owners,$classesref) = @_;
8552: my ($homeserver,%validations);
8553: $homeserver = &homeserver($cnum,$cdom);
8554: unless ($homeserver eq 'no_host') {
8555: my $ownerlist;
8556: if (ref($owners) eq 'ARRAY') {
8557: $ownerlist = join(',',@{$owners});
8558: } else {
8559: $ownerlist = $owners;
8560: }
8561: if (ref($classesref) eq 'HASH') {
8562: my $classes = &freeze_escape($classesref);
8563: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
8564: ':'.$cdom.':'.$classes,$homeserver);
8565: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8566: my @items = split(/&/,$response);
8567: foreach my $item (@items) {
8568: my ($key,$value) = split('=',$item);
8569: $validations{&unescape($key)} = &thaw_unescape($value);
8570: }
8571: }
8572: }
8573: }
8574: return %validations;
8575: }
8576:
1.1172.2.38 raeburn 8577: sub auto_crsreq_update {
8578: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8579: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8580: my ($homeserver,%crsreqresponse);
8581: if ($cdom =~ /^$match_domain$/) {
8582: $homeserver = &domain($cdom,'primary');
8583: }
8584: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8585: my $info;
8586: if (ref($inbound) eq 'HASH') {
8587: $info = &freeze_escape($inbound);
8588: }
8589: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8590: ':'.&escape($action).':'.&escape($ownername).':'.
8591: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8592: &escape($title).':'.&escape($code).':'.
8593: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8594: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8595: my @items = split(/&/,$response);
8596: foreach my $item (@items) {
8597: my ($key,$value) = split('=',$item);
8598: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8599: }
8600: }
8601: }
8602: return \%crsreqresponse;
8603: }
8604:
1.1172.2.78 raeburn 8605: sub auto_export_grades {
8606: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8607: my ($homeserver,%exportresponse);
8608: if ($cdom =~ /^$match_domain$/) {
8609: $homeserver = &domain($cdom,'primary');
8610: }
8611: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8612: my $info;
8613: if (ref($inforef) eq 'HASH') {
8614: $info = &freeze_escape($inforef);
8615: }
8616: if (ref($gradesref) eq 'HASH') {
8617: my $grades = &freeze_escape($gradesref);
8618: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8619: $info.':'.$grades,$homeserver);
8620: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8621: my @items = split(/&/,$response);
8622: foreach my $item (@items) {
8623: my ($key,$value) = split('=',$item);
8624: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8625: }
8626: }
8627: }
8628: }
8629: return \%exportresponse;
8630: }
8631:
1.1172.2.68 raeburn 8632: sub check_instcode_cloning {
8633: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8634: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8635: return;
8636: }
8637: my $canclone;
8638: if (@{$code_order} > 0) {
8639: my $instcoderegexp ='^';
8640: my @clonecodes = split(/\&/,$cloner);
8641: foreach my $item (@{$code_order}) {
8642: if (grep(/^\Q$item\E=/,@clonecodes)) {
8643: foreach my $pair (@clonecodes) {
8644: my ($key,$val) = split(/\=/,$pair,2);
8645: $val = &unescape($val);
8646: if ($key eq $item) {
8647: $instcoderegexp .= '('.$val.')';
8648: last;
8649: }
8650: }
8651: } else {
8652: $instcoderegexp .= $codedefaults->{$item};
8653: }
8654: }
8655: $instcoderegexp .= '$';
8656: my (@from,@to);
8657: eval {
8658: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8659: (@to) = ($clonetocode =~ /$instcoderegexp/);
8660: };
8661: if ((@from > 0) && (@to > 0)) {
8662: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8663: if (!@diffs) {
8664: $canclone = 1;
8665: }
8666: }
8667: }
8668: return $canclone;
8669: }
8670:
8671: sub default_instcode_cloning {
8672: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8673: my (%codedefaults,@code_order,$canclone);
8674: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8675: %codedefaults = %{$codedefaultsref};
8676: @code_order = @{$codeorderref};
8677: } elsif ($clonedom) {
8678: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8679: }
8680: if (($domdefclone) && (@code_order)) {
8681: my @clonecodes = split(/\+/,$domdefclone);
8682: my $instcoderegexp ='^';
8683: foreach my $item (@code_order) {
8684: if (grep(/^\Q$item\E$/,@clonecodes)) {
8685: $instcoderegexp .= '('.$codedefaults{$item}.')';
8686: } else {
8687: $instcoderegexp .= $codedefaults{$item};
8688: }
8689: }
8690: $instcoderegexp .= '$';
8691: my (@from,@to);
8692: eval {
8693: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8694: (@to) = ($clonetocode =~ /$instcoderegexp/);
8695: };
8696: if ((@from > 0) && (@to > 0)) {
8697: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8698: if (!@diffs) {
8699: $canclone = 1;
8700: }
8701: }
8702: }
8703: return $canclone;
8704: }
8705:
1.679 raeburn 8706: # ------------------------------------------------------- Course Group routines
8707:
8708: sub get_coursegroups {
1.809 raeburn 8709: my ($cdom,$cnum,$group,$namespace) = @_;
8710: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8711: }
8712:
1.679 raeburn 8713: sub modify_coursegroup {
8714: my ($cdom,$cnum,$groupsettings) = @_;
8715: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8716: }
8717:
1.809 raeburn 8718: sub toggle_coursegroup_status {
8719: my ($cdom,$cnum,$group,$action) = @_;
8720: my ($from_namespace,$to_namespace);
8721: if ($action eq 'delete') {
8722: $from_namespace = 'coursegroups';
8723: $to_namespace = 'deleted_groups';
8724: } else {
8725: $from_namespace = 'deleted_groups';
8726: $to_namespace = 'coursegroups';
8727: }
8728: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8729: if (my $tmp = &error(%curr_group)) {
8730: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8731: return ('read error',$tmp);
8732: } else {
8733: my %savedsettings = %curr_group;
1.809 raeburn 8734: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8735: my $deloutcome;
8736: if ($result eq 'ok') {
1.809 raeburn 8737: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8738: } else {
8739: return ('write error',$result);
8740: }
8741: if ($deloutcome eq 'ok') {
8742: return 'ok';
8743: } else {
8744: return ('delete error',$deloutcome);
8745: }
8746: }
8747: }
8748:
1.679 raeburn 8749: sub modify_group_roles {
1.957 raeburn 8750: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8751: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8752: my $role = 'gr/'.&escape($userprivs);
8753: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8754: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8755: if ($result eq 'ok') {
8756: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8757: }
1.679 raeburn 8758: return $result;
8759: }
8760:
8761: sub modify_coursegroup_membership {
8762: my ($cdom,$cnum,$membership) = @_;
8763: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8764: return $result;
8765: }
8766:
1.682 raeburn 8767: sub get_active_groups {
8768: my ($udom,$uname,$cdom,$cnum) = @_;
8769: my $now = time;
8770: my %groups = ();
8771: foreach my $key (keys(%env)) {
1.811 albertel 8772: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8773: my ($start,$end) = split(/\./,$env{$key});
8774: if (($end!=0) && ($end<$now)) { next; }
8775: if (($start!=0) && ($start>$now)) { next; }
8776: if ($1 eq $cdom && $2 eq $cnum) {
8777: $groups{$3} = $env{$key} ;
8778: }
8779: }
8780: }
8781: return %groups;
8782: }
8783:
1.683 raeburn 8784: sub get_group_membership {
8785: my ($cdom,$cnum,$group) = @_;
8786: return(&dump('groupmembership',$cdom,$cnum,$group));
8787: }
8788:
8789: sub get_users_groups {
8790: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8791: my @usersgroups;
1.683 raeburn 8792: my $cachetime=1800;
8793:
8794: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8795: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8796: if (defined($cached)) {
1.734 albertel 8797: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8798: } else {
8799: $grouplist = '';
1.816 raeburn 8800: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8801: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8802: my $access_end = $env{'course.'.$courseid.
8803: '.default_enrollment_end_date'};
8804: my $now = time;
8805: foreach my $key (keys(%roleshash)) {
8806: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8807: my $group = $1;
8808: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8809: my $start = $2;
8810: my $end = $1;
8811: if ($start == -1) { next; } # deleted from group
8812: if (($start!=0) && ($start>$now)) { next; }
8813: if (($end!=0) && ($end<$now)) {
8814: if ($access_end && $access_end < $now) {
8815: if ($access_end - $end < 86400) {
8816: push(@usersgroups,$group);
1.733 raeburn 8817: }
8818: }
1.817 raeburn 8819: next;
1.733 raeburn 8820: }
1.817 raeburn 8821: push(@usersgroups,$group);
1.683 raeburn 8822: }
8823: }
8824: }
1.817 raeburn 8825: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8826: $grouplist = join(':',@usersgroups);
8827: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8828: }
1.733 raeburn 8829: return @usersgroups;
1.683 raeburn 8830: }
8831:
8832: sub devalidate_getgroups_cache {
8833: my ($udom,$uname,$cdom,$cnum)=@_;
8834: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8835:
1.683 raeburn 8836: my $hashid="$udom:$uname:$courseid";
8837: &devalidate_cache_new('getgroups',$hashid);
8838: }
8839:
1.12 www 8840: # ------------------------------------------------------------------ Plain Text
8841:
8842: sub plaintext {
1.988 raeburn 8843: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8844: if ($short =~ m{^cr/}) {
1.758 albertel 8845: return (split('/',$short))[-1];
8846: }
1.742 raeburn 8847: if (!defined($cid)) {
8848: $cid = $env{'request.course.id'};
8849: }
8850: my %rolenames = (
1.1008 raeburn 8851: Course => 'std',
8852: Community => 'alt1',
1.742 raeburn 8853: );
1.1037 raeburn 8854: if ($cid ne '') {
8855: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8856: unless ($forcedefault) {
8857: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8858: &Apache::lonlocal::mt_escape(\$roletext);
8859: return &Apache::lonlocal::mt($roletext);
8860: }
8861: }
8862: }
8863: if ((defined($type)) && (defined($rolenames{$type})) &&
8864: (defined($rolenames{$type})) &&
8865: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8866: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8867: } elsif ($cid ne '') {
8868: my $crstype = $env{'course.'.$cid.'.type'};
8869: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8870: (defined($prp{$short}{$rolenames{$crstype}}))) {
8871: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8872: }
1.742 raeburn 8873: }
1.1037 raeburn 8874: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8875: }
8876:
8877: # ----------------------------------------------------------------- Assign Role
8878:
8879: sub assignrole {
1.957 raeburn 8880: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8881: $context)=@_;
1.21 www 8882: my $mrole;
8883: if ($role =~ /^cr\//) {
1.393 www 8884: my $cwosec=$url;
1.811 albertel 8885: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8886: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8887: my $refused = 1;
8888: if ($context eq 'requestcourses') {
8889: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8890: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8891: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8892: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8893: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8894: if ($crsenv{'internal.courseowner'} eq
8895: $env{'user.name'}.':'.$env{'user.domain'}) {
8896: $refused = '';
8897: }
8898: }
8899: }
8900: }
8901: }
8902: if ($refused) {
8903: &logthis('Refused custom assignrole: '.
8904: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8905: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8906: return 'refused';
8907: }
1.104 www 8908: }
1.21 www 8909: $mrole='cr';
1.678 raeburn 8910: } elsif ($role =~ /^gr\//) {
8911: my $cwogrp=$url;
1.811 albertel 8912: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8913: unless (&allowed('mdg',$cwogrp)) {
8914: &logthis('Refused group assignrole: '.
8915: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8916: $env{'user.name'}.' at '.$env{'user.domain'});
8917: return 'refused';
8918: }
8919: $mrole='gr';
1.21 www 8920: } else {
1.82 www 8921: my $cwosec=$url;
1.811 albertel 8922: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8923: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8924: my $refused;
8925: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8926: if (!(&allowed('c'.$role,$url))) {
8927: $refused = 1;
8928: }
8929: } else {
8930: $refused = 1;
8931: }
1.947 raeburn 8932: if ($refused) {
1.1045 raeburn 8933: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8934: if (!$selfenroll && $context eq 'course') {
8935: my %crsenv;
8936: if ($role eq 'cc' || $role eq 'co') {
8937: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8938: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8939: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8940: if ($crsenv{'internal.courseowner'} eq
8941: $env{'user.name'}.':'.$env{'user.domain'}) {
8942: $refused = '';
8943: }
8944: }
8945: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8946: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8947: if ($crsenv{'internal.courseowner'} eq
8948: $env{'user.name'}.':'.$env{'user.domain'}) {
8949: $refused = '';
8950: }
8951: }
8952: }
8953: }
8954: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8955: $refused = '';
1.1017 raeburn 8956: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8957: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8958: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8959: my $wrongcc;
8960: if ($cnum =~ /^$match_community$/) {
8961: $wrongcc = 1 if ($role eq 'cc');
8962: } else {
8963: $wrongcc = 1 if ($role eq 'co');
8964: }
8965: unless ($wrongcc) {
8966: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8967: if ($crsenv{'internal.courseowner'} eq
8968: $env{'user.name'}.':'.$env{'user.domain'}) {
8969: $refused = '';
8970: }
1.1017 raeburn 8971: }
8972: }
1.1172.2.9 raeburn 8973: } elsif ($context eq 'requestauthor') {
8974: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8975: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8976: if ($env{'environment.requestauthor'} eq 'automatic') {
8977: $refused = '';
8978: } else {
8979: my %domdefaults = &get_domain_defaults($udom);
8980: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8981: my $checkbystatus;
8982: if ($env{'user.adv'}) {
8983: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8984: if ($disposition eq 'automatic') {
8985: $refused = '';
8986: } elsif ($disposition eq '') {
8987: $checkbystatus = 1;
8988: }
8989: } else {
8990: $checkbystatus = 1;
8991: }
8992: if ($checkbystatus) {
8993: if ($env{'environment.inststatus'}) {
8994: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8995: foreach my $type (@inststatuses) {
8996: if (($type ne '') &&
8997: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8998: $refused = '';
8999: }
9000: }
9001: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9002: $refused = '';
9003: }
9004: }
9005: }
9006: }
9007: }
1.1017 raeburn 9008: }
9009: if ($refused) {
1.947 raeburn 9010: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9011: ' '.$role.' '.$end.' '.$start.' by '.
9012: $env{'user.name'}.' at '.$env{'user.domain'});
9013: return 'refused';
9014: }
1.932 raeburn 9015: }
1.1131 raeburn 9016: } elsif ($role eq 'au') {
9017: if ($url ne '/'.$udom.'/') {
9018: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9019: ' to assign author role for '.$uname.':'.$udom.
9020: ' in domain: '.$url.' refused (wrong domain).');
9021: return 'refused';
9022: }
1.104 www 9023: }
1.21 www 9024: $mrole=$role;
9025: }
1.620 albertel 9026: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9027: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9028: if ($end) { $command.='_'.$end; }
1.21 www 9029: if ($start) {
9030: if ($end) {
1.81 www 9031: $command.='_'.$start;
1.21 www 9032: } else {
1.81 www 9033: $command.='_0_'.$start;
1.21 www 9034: }
9035: }
1.739 raeburn 9036: my $origstart = $start;
9037: my $origend = $end;
1.957 raeburn 9038: my $delflag;
1.357 www 9039: # actually delete
9040: if ($deleteflag) {
1.373 www 9041: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9042: # modify command to delete the role
1.620 albertel 9043: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9044: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9045: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9046: # set start and finish to negative values for userrolelog
9047: $start=-1;
9048: $end=-1;
1.957 raeburn 9049: $delflag = 1;
1.357 www 9050: }
9051: }
9052: # send command
1.349 www 9053: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9054: # log new user role if status is ok
1.349 www 9055: if ($answer eq 'ok') {
1.663 raeburn 9056: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9057: if (($role eq 'cc') || ($role eq 'in') ||
9058: ($role eq 'ep') || ($role eq 'ad') ||
9059: ($role eq 'ta') || ($role eq 'st') ||
9060: ($role=~/^cr/) || ($role eq 'gr') ||
9061: ($role eq 'co')) {
1.1172.2.13 raeburn 9062: # for course roles, perform group memberships changes triggered by role change.
9063: unless ($role =~ /^gr/) {
9064: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9065: $origstart,$selfenroll,$context);
9066: }
1.1172.2.9 raeburn 9067: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9068: $selfenroll,$context);
9069: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9070: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9071: ($role eq 'da')) {
1.1172.2.9 raeburn 9072: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9073: $context);
9074: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9075: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9076: $context);
9077: }
1.1053 raeburn 9078: if ($role eq 'cc') {
9079: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9080: }
1.349 www 9081: }
9082: return $answer;
1.169 harris41 9083: }
9084:
1.1053 raeburn 9085: sub autoupdate_coowners {
9086: my ($url,$end,$start,$uname,$udom) = @_;
9087: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9088: if (($cdom ne '') && ($cnum ne '')) {
9089: my $now = time;
9090: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9091: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9092: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9093: my $instcode = $coursehash{'internal.coursecode'};
9094: if ($instcode ne '') {
1.1056 raeburn 9095: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9096: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9097: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9098: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9099: if ($result eq 'valid') {
9100: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9101: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9102: push(@newcoowners,$coowner);
9103: }
9104: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9105: push(@newcoowners,$uname.':'.$udom);
9106: }
9107: @newcoowners = sort(@newcoowners);
9108: } else {
9109: push(@newcoowners,$uname.':'.$udom);
9110: }
9111: } else {
9112: if ($coursehash{'internal.co-owners'}) {
9113: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9114: unless ($coowner eq $uname.':'.$udom) {
9115: push(@newcoowners,$coowner);
9116: }
9117: }
9118: unless (@newcoowners > 0) {
9119: $delcoowners = 1;
9120: $coowners = '';
9121: }
9122: }
9123: }
9124: if (@newcoowners || $delcoowners) {
9125: &store_coowners($cdom,$cnum,$coursehash{'home'},
9126: $delcoowners,@newcoowners);
9127: }
9128: }
9129: }
9130: }
9131: }
9132: }
9133: }
9134:
9135: sub store_coowners {
9136: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9137: my $cid = $cdom.'_'.$cnum;
9138: my ($coowners,$delresult,$putresult);
9139: if (@newcoowners) {
9140: $coowners = join(',',@newcoowners);
9141: my %coownershash = (
9142: 'internal.co-owners' => $coowners,
9143: );
9144: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9145: if ($putresult eq 'ok') {
9146: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9147: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9148: }
9149: }
9150: }
9151: if ($delcoowners) {
9152: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9153: if ($delresult eq 'ok') {
9154: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9155: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9156: }
9157: }
9158: }
9159: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9160: my %crsinfo =
9161: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9162: if (ref($crsinfo{$cid}) eq 'HASH') {
9163: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9164: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9165: }
9166: }
9167: }
9168:
1.169 harris41 9169: # -------------------------------------------------- Modify user authentication
1.197 www 9170: # Overrides without validation
9171:
1.169 harris41 9172: sub modifyuserauth {
9173: my ($udom,$uname,$umode,$upass)=@_;
9174: my $uhome=&homeserver($uname,$udom);
1.197 www 9175: unless (&allowed('mau',$udom)) { return 'refused'; }
9176: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9177: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9178: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9179: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9180: &escape($upass),$uhome);
1.620 albertel 9181: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9182: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9183: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9184: &log($udom,,$uname,$uhome,
1.620 albertel 9185: 'Authentication changed by '.$env{'user.domain'}.', '.
9186: $env{'user.name'}.', '.$umode.
1.197 www 9187: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9188: unless ($reply eq 'ok') {
1.197 www 9189: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9190: return 'error: '.$reply;
9191: }
1.170 harris41 9192: return 'ok';
1.80 www 9193: }
9194:
1.81 www 9195: # --------------------------------------------------------------- Modify a user
1.80 www 9196:
1.81 www 9197: sub modifyuser {
1.206 matthew 9198: my ($udom, $uname, $uid,
9199: $umode, $upass, $first,
9200: $middle, $last, $gene,
1.1058 raeburn 9201: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9202: $udom= &LONCAPA::clean_domain($udom);
9203: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9204: my $showcandelete = 'none';
9205: if (ref($candelete) eq 'ARRAY') {
9206: if (@{$candelete} > 0) {
9207: $showcandelete = join(', ',@{$candelete});
9208: }
9209: }
1.81 www 9210: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9211: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9212: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9213: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9214: ' desiredhome not specified').
1.620 albertel 9215: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9216: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9217: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9218: my $newuser;
9219: if ($uhome eq 'no_host') {
9220: $newuser = 1;
9221: }
1.80 www 9222: # ----------------------------------------------------------------- Create User
1.406 albertel 9223: if (($uhome eq 'no_host') &&
9224: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9225: my $unhome='';
1.844 albertel 9226: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9227: $unhome = $desiredhome;
1.620 albertel 9228: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9229: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9230: } else { # load balancing routine for determining $unhome
1.81 www 9231: my $loadm=10000000;
1.841 albertel 9232: my %servers = &get_servers($udom,'library');
9233: foreach my $tryserver (keys(%servers)) {
9234: my $answer=reply('load',$tryserver);
9235: if (($answer=~/\d+/) && ($answer<$loadm)) {
9236: $loadm=$answer;
9237: $unhome=$tryserver;
9238: }
1.80 www 9239: }
9240: }
9241: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9242: return 'error: unable to find a home server for '.$uname.
9243: ' in domain '.$udom;
1.80 www 9244: }
9245: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9246: &escape($upass),$unhome);
9247: unless ($reply eq 'ok') {
9248: return 'error: '.$reply;
9249: }
1.230 stredwic 9250: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9251: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9252: return 'error: unable verify users home machine.';
1.80 www 9253: }
1.209 matthew 9254: } # End of creation of new user
1.80 www 9255: # ---------------------------------------------------------------------- Add ID
9256: if ($uid) {
9257: $uid=~tr/A-Z/a-z/;
9258: my %uidhash=&idrget($udom,$uname);
1.196 www 9259: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9260: && (!$forceid)) {
1.80 www 9261: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9262: return 'error: user id "'.$uid.'" does not match '.
9263: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9264: }
9265: } else {
9266: &idput($udom,($uname => $uid));
9267: }
9268: }
9269: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9270: my @tmp=&get('environment',
1.899 raeburn 9271: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9272: 'permanentemail','inststatus'],
1.134 albertel 9273: $udom,$uname);
1.1075 raeburn 9274: my (%names,%oldnames);
1.313 matthew 9275: if ($tmp[0] =~ m/^error:.*/) {
9276: %names=();
9277: } else {
9278: %names = @tmp;
1.1075 raeburn 9279: %oldnames = %names;
1.313 matthew 9280: }
1.388 www 9281: #
1.1058 raeburn 9282: # If name, email and/or uid are blank (e.g., because an uploaded file
9283: # of users did not contain them), do not overwrite existing values
9284: # unless field is in $candelete array ref.
9285: #
9286:
9287: my @fields = ('firstname','middlename','lastname','generation',
9288: 'permanentemail','id');
9289: my %newvalues;
9290: if (ref($candelete) eq 'ARRAY') {
9291: foreach my $field (@fields) {
9292: if (grep(/^\Q$field\E$/,@{$candelete})) {
9293: if ($field eq 'firstname') {
9294: $names{$field} = $first;
9295: } elsif ($field eq 'middlename') {
9296: $names{$field} = $middle;
9297: } elsif ($field eq 'lastname') {
9298: $names{$field} = $last;
9299: } elsif ($field eq 'generation') {
9300: $names{$field} = $gene;
9301: } elsif ($field eq 'permanentemail') {
9302: $names{$field} = $email;
9303: } elsif ($field eq 'id') {
9304: $names{$field} = $uid;
9305: }
9306: }
9307: }
9308: }
1.388 www 9309: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9310: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9311: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9312: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9313: if ($email) {
9314: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9315: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9316: }
1.899 raeburn 9317: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9318: if (defined($inststatus)) {
9319: $names{'inststatus'} = '';
9320: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9321: if (ref($usertypes) eq 'HASH') {
9322: my @okstatuses;
9323: foreach my $item (split(/:/,$inststatus)) {
9324: if (defined($usertypes->{$item})) {
9325: push(@okstatuses,$item);
9326: }
9327: }
9328: if (@okstatuses) {
9329: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9330: }
9331: }
9332: }
1.1075 raeburn 9333: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9334: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9335: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9336: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9337: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9338: } else {
9339: $logmsg .= ' during self creation';
9340: }
1.1075 raeburn 9341: my $changed;
9342: if ($newuser) {
9343: $changed = 1;
9344: } else {
9345: foreach my $field (@fields) {
9346: if ($names{$field} ne $oldnames{$field}) {
9347: $changed = 1;
9348: last;
9349: }
9350: }
9351: }
9352: unless ($changed) {
9353: $logmsg = 'No changes in user information needed for: '.$logmsg;
9354: &logthis($logmsg);
9355: return 'ok';
9356: }
9357: my $reply = &put('environment', \%names, $udom,$uname);
9358: if ($reply ne 'ok') {
9359: return 'error: '.$reply;
9360: }
1.1087 raeburn 9361: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9362: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9363: }
1.1075 raeburn 9364: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9365: &devalidate_cache_new('namescache',$uname.':'.$udom);
9366: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9367: &logthis($logmsg);
1.134 albertel 9368: return 'ok';
1.80 www 9369: }
9370:
1.81 www 9371: # -------------------------------------------------------------- Modify student
1.80 www 9372:
1.81 www 9373: sub modifystudent {
9374: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9375: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9376: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9377: if (!$cid) {
1.620 albertel 9378: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9379: return 'not_in_class';
9380: }
1.80 www 9381: }
9382: # --------------------------------------------------------------- Make the user
1.81 www 9383: my $reply=&modifyuser
1.209 matthew 9384: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9385: $desiredhome,$email,$inststatus);
1.80 www 9386: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9387: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9388: # student's environment
1.297 matthew 9389: $uid = undef if (!$forceid);
1.455 albertel 9390: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9391: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9392: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9393: return $reply;
9394: }
9395:
9396: sub modify_student_enrollment {
1.1172.2.23 raeburn 9397: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9398: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9399: my ($cdom,$cnum,$chome);
9400: if (!$cid) {
1.620 albertel 9401: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9402: return 'not_in_class';
9403: }
1.620 albertel 9404: $cdom=$env{'course.'.$cid.'.domain'};
9405: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9406: } else {
9407: ($cdom,$cnum)=split(/_/,$cid);
9408: }
1.620 albertel 9409: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9410: if (!$chome) {
1.457 raeburn 9411: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9412: }
1.455 albertel 9413: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9414: # Make sure the user exists
1.81 www 9415: my $uhome=&homeserver($uname,$udom);
9416: if (($uhome eq '') || ($uhome eq 'no_host')) {
9417: return 'error: no such user';
9418: }
1.297 matthew 9419: # Get student data if we were not given enough information
9420: if (!defined($first) || $first eq '' ||
9421: !defined($last) || $last eq '' ||
9422: !defined($uid) || $uid eq '' ||
9423: !defined($middle) || $middle eq '' ||
9424: !defined($gene) || $gene eq '') {
1.294 matthew 9425: # They did not supply us with enough data to enroll the student, so
9426: # we need to pick up more information.
1.297 matthew 9427: my %tmp = &get('environment',
1.294 matthew 9428: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9429: ,$udom,$uname);
9430:
1.800 albertel 9431: #foreach my $key (keys(%tmp)) {
9432: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9433: #}
1.294 matthew 9434: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9435: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9436: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9437: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9438: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9439: }
1.556 albertel 9440: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9441: my $user = "$uname:$udom";
9442: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9443: my $reply=cput('classlist',
1.1148 raeburn 9444: {$user =>
1.1172.2.76 raeburn 9445: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9446: $cdom,$cnum);
1.1148 raeburn 9447: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9448: &devalidate_getsection_cache($udom,$uname,$cid);
9449: } else {
1.81 www 9450: return 'error: '.$reply;
9451: }
1.297 matthew 9452: # Add student role to user
1.83 www 9453: my $uurl='/'.$cid;
1.81 www 9454: $uurl=~s/\_/\//g;
9455: if ($usec) {
9456: $uurl.='/'.$usec;
9457: }
1.1148 raeburn 9458: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9459: $selfenroll,$context);
9460: if ($result ne 'ok') {
9461: if ($old_entry{$user} ne '') {
9462: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9463: } else {
9464: $reply = &del('classlist',[$user],$cdom,$cnum);
9465: }
9466: }
9467: return $result;
1.21 www 9468: }
9469:
1.556 albertel 9470: sub format_name {
9471: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9472: my $name;
9473: if ($first ne 'lastname') {
9474: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9475: } else {
9476: if ($lastname=~/\S/) {
9477: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9478: $name=~s/\s+,/,/;
9479: } else {
9480: $name.= $firstname.' '.$middlename.' '.$generation;
9481: }
9482: }
9483: $name=~s/^\s+//;
9484: $name=~s/\s+$//;
9485: $name=~s/\s+/ /g;
9486: return $name;
9487: }
9488:
1.84 www 9489: # ------------------------------------------------- Write to course preferences
9490:
9491: sub writecoursepref {
9492: my ($courseid,%prefs)=@_;
9493: $courseid=~s/^\///;
9494: $courseid=~s/\_/\//g;
9495: my ($cdomain,$cnum)=split(/\//,$courseid);
9496: my $chome=homeserver($cnum,$cdomain);
9497: if (($chome eq '') || ($chome eq 'no_host')) {
9498: return 'error: no such course';
9499: }
9500: my $cstring='';
1.800 albertel 9501: foreach my $pref (keys(%prefs)) {
9502: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9503: }
1.84 www 9504: $cstring=~s/\&$//;
9505: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9506: }
9507:
9508: # ---------------------------------------------------------- Make/modify course
9509:
9510: sub createcourse {
1.741 raeburn 9511: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9512: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9513: $url=&declutter($url);
9514: my $cid='';
1.1028 raeburn 9515: if ($context eq 'requestcourses') {
9516: my $can_create = 0;
9517: my ($ownername,$ownerdom) = split(':',$course_owner);
9518: if ($udom eq $ownerdom) {
9519: if (&usertools_access($ownername,$ownerdom,$category,undef,
9520: $context)) {
9521: $can_create = 1;
9522: }
9523: } else {
9524: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9525: $category);
9526: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9527: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9528: if (@curr > 0) {
9529: my @options = qw(approval validate autolimit);
9530: my $optregex = join('|',@options);
9531: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9532: $can_create = 1;
9533: }
9534: }
9535: }
9536: }
9537: if ($can_create) {
9538: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9539: unless (&allowed('ccc',$udom)) {
9540: return 'refused';
9541: }
1.1017 raeburn 9542: }
9543: } else {
9544: return 'refused';
9545: }
1.1028 raeburn 9546: } elsif (!&allowed('ccc',$udom)) {
9547: return 'refused';
1.84 www 9548: }
1.1011 raeburn 9549: # --------------------------------------------------------------- Get Unique ID
9550: my $uname;
9551: if ($cnum =~ /^$match_courseid$/) {
9552: my $chome=&homeserver($cnum,$udom,'true');
9553: if (($chome eq '') || ($chome eq 'no_host')) {
9554: $uname = $cnum;
9555: } else {
1.1038 raeburn 9556: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9557: }
9558: } else {
1.1038 raeburn 9559: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9560: }
9561: return $uname if ($uname =~ /^error/);
9562: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9563: if (!defined($course_server)) {
9564: if (defined(&domain($udom,'primary'))) {
9565: $course_server = &domain($udom,'primary');
9566: } else {
9567: $course_server = $env{'user.home'};
9568: }
9569: }
9570: my %host_servers =
9571: &Apache::lonnet::get_servers($udom,'library');
9572: unless ($host_servers{$course_server}) {
9573: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9574: }
1.84 www 9575: # ------------------------------------------------------------- Make the course
9576: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9577: $course_server);
1.84 www 9578: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9579: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9580: if (($uhome eq '') || ($uhome eq 'no_host')) {
9581: return 'error: no such course';
9582: }
1.271 www 9583: # ----------------------------------------------------------------- Course made
1.516 raeburn 9584: # log existence
1.1029 raeburn 9585: my $now = time;
1.918 raeburn 9586: my $newcourse = {
9587: $udom.'_'.$uname => {
1.921 raeburn 9588: description => $description,
9589: inst_code => $inst_code,
9590: owner => $course_owner,
9591: type => $crstype,
1.1029 raeburn 9592: creator => $env{'user.name'}.':'.
9593: $env{'user.domain'},
9594: created => $now,
9595: context => $context,
1.918 raeburn 9596: },
9597: };
1.921 raeburn 9598: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9599: # set toplevel url
1.271 www 9600: my $topurl=$url;
9601: unless ($nonstandard) {
9602: # ------------------------------------------ For standard courses, make top url
9603: my $mapurl=&clutter($url);
1.278 www 9604: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9605: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9606: <map>
9607: <resource id="1" type="start"></resource>
9608: <resource id="2" src="$mapurl"></resource>
9609: <resource id="3" type="finish"></resource>
9610: <link index="1" from="1" to="2"></link>
9611: <link index="2" from="2" to="3"></link>
9612: </map>
9613: ENDINITMAP
9614: $topurl=&declutter(
1.638 albertel 9615: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9616: );
9617: }
9618: # ----------------------------------------------------------- Write preferences
1.84 www 9619: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9620: ('description' => $description,
9621: 'url' => $topurl,
9622: 'internal.creator' => $env{'user.name'}.':'.
9623: $env{'user.domain'},
9624: 'internal.created' => $now,
9625: 'internal.creationcontext' => $context)
9626: );
1.84 www 9627: return '/'.$udom.'/'.$uname;
9628: }
9629:
1.1011 raeburn 9630: # ------------------------------------------------------------------- Create ID
9631: sub generate_coursenum {
1.1038 raeburn 9632: my ($udom,$crstype) = @_;
1.1011 raeburn 9633: my $domdesc = &domain($udom);
9634: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9635: my $first;
9636: if ($crstype eq 'Community') {
9637: $first = '0';
9638: } else {
9639: $first = int(1+rand(9));
9640: }
9641: my $uname=$first.
1.1011 raeburn 9642: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9643: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9644: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9645: # ----------------------------------------------- Make sure that does not exist
9646: my $uhome=&homeserver($uname,$udom,'true');
9647: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9648: if ($crstype eq 'Community') {
9649: $first = '0';
9650: } else {
9651: $first = int(1+rand(9));
9652: }
9653: $uname=$first.
1.1011 raeburn 9654: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9655: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9656: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9657: $uhome=&homeserver($uname,$udom,'true');
9658: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9659: return 'error: unable to generate unique course-ID';
9660: }
9661: }
9662: return $uname;
9663: }
9664:
1.813 albertel 9665: sub is_course {
1.1167 droeschl 9666: my ($cdom, $cnum) = scalar(@_) == 1 ?
9667: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 9668: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
9669: my $uhome=&homeserver($cnum,$cdom);
9670: my $iscourse;
9671: if (grep { $_ eq $uhome } current_machine_ids()) {
9672: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
9673: } else {
9674: my $hashid = $cdom.':'.$cnum;
9675: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
9676: unless (defined($cached)) {
9677: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
9678: $cnum,undef,undef,'.');
9679: $iscourse = 0;
9680: if (exists($courses{$cdom.'_'.$cnum})) {
9681: $iscourse = 1;
9682: }
9683: &do_cache_new('iscourse',$hashid,$iscourse,3600);
9684: }
9685: }
9686: return unless($iscourse);
1.1167 droeschl 9687: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9688: }
9689:
1.1015 raeburn 9690: sub store_userdata {
9691: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9692: my $result;
1.1016 raeburn 9693: if ($datakey ne '') {
1.1013 raeburn 9694: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9695: if ($udom eq '' || $uname eq '') {
9696: $udom = $env{'user.domain'};
9697: $uname = $env{'user.name'};
9698: }
9699: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9700: if (($uhome eq '') || ($uhome eq 'no_host')) {
9701: $result = 'error: no_host';
9702: } else {
9703: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9704: $storehash->{'host'} = $perlvar{'lonHostID'};
9705:
9706: my $namevalue='';
9707: foreach my $key (keys(%{$storehash})) {
9708: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9709: }
9710: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9711: unless ($namespace eq 'courserequests') {
9712: $datakey = &escape($datakey);
9713: }
1.1105 raeburn 9714: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9715: $namevalue,$uhome);
1.1013 raeburn 9716: }
9717: } else {
9718: $result = 'error: data to store was not a hash reference';
9719: }
9720: } else {
9721: $result= 'error: invalid requestkey';
9722: }
9723: return $result;
9724: }
9725:
1.21 www 9726: # ---------------------------------------------------------- Assign Custom Role
9727:
9728: sub assigncustomrole {
1.957 raeburn 9729: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9730: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9731: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9732: }
9733:
9734: # ----------------------------------------------------------------- Revoke Role
9735:
9736: sub revokerole {
1.957 raeburn 9737: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9738: my $now=time;
1.965 raeburn 9739: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9740: }
9741:
9742: # ---------------------------------------------------------- Revoke Custom Role
9743:
9744: sub revokecustomrole {
1.957 raeburn 9745: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9746: my $now=time;
1.357 www 9747: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9748: $deleteflag,$selfenroll,$context);
1.17 www 9749: }
9750:
1.533 banghart 9751: # ------------------------------------------------------------ Disk usage
1.535 albertel 9752: sub diskusage {
1.955 raeburn 9753: my ($udom,$uname,$directorypath,$getpropath)=@_;
9754: $directorypath =~ s/\/$//;
9755: my $listing=&reply('du2:'.&escape($directorypath).':'
9756: .&escape($getpropath).':'.&escape($uname).':'
9757: .&escape($udom),homeserver($uname,$udom));
9758: if ($listing eq 'unknown_cmd') {
9759: if ($getpropath) {
9760: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9761: }
9762: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9763: }
1.514 albertel 9764: return $listing;
1.512 banghart 9765: }
9766:
1.566 banghart 9767: sub is_locked {
1.1096 raeburn 9768: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9769: my @check;
9770: my $is_locked;
1.1093 raeburn 9771: push (@check,$file_name);
1.613 albertel 9772: my %locked = &get('file_permissions',\@check,
1.620 albertel 9773: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9774: my ($tmp)=keys(%locked);
9775: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9776:
1.566 banghart 9777: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9778: $is_locked = 'false';
9779: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9780: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9781: $is_locked = 'true';
1.1096 raeburn 9782: if (ref($which) eq 'ARRAY') {
9783: push(@{$which},$entry);
9784: } else {
9785: last;
9786: }
1.745 raeburn 9787: }
9788: }
1.566 banghart 9789: } else {
9790: $is_locked = 'false';
9791: }
1.1093 raeburn 9792: return $is_locked;
1.566 banghart 9793: }
9794:
1.759 albertel 9795: sub declutter_portfile {
9796: my ($file) = @_;
1.833 albertel 9797: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9798: return $file;
9799: }
9800:
1.559 banghart 9801: # ------------------------------------------------------------- Mark as Read Only
9802:
9803: sub mark_as_readonly {
9804: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9805: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9806: my ($tmp)=keys(%current_permissions);
9807: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9808: foreach my $file (@{$files}) {
1.759 albertel 9809: $file = &declutter_portfile($file);
1.561 banghart 9810: push(@{$current_permissions{$file}},$what);
1.559 banghart 9811: }
1.613 albertel 9812: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9813: return;
9814: }
9815:
1.572 banghart 9816: # ------------------------------------------------------------Save Selected Files
9817:
9818: sub save_selected_files {
9819: my ($user, $path, @files) = @_;
9820: my $filename = $user."savedfiles";
1.573 banghart 9821: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96! raeburn 9822: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 9823: foreach my $file (@files) {
1.620 albertel 9824: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9825: }
9826: foreach my $file (@other_files) {
1.574 banghart 9827: print (OUT $file."\n");
1.572 banghart 9828: }
1.574 banghart 9829: close (OUT);
1.572 banghart 9830: return 'ok';
9831: }
9832:
1.574 banghart 9833: sub clear_selected_files {
9834: my ($user) = @_;
9835: my $filename = $user."savedfiles";
1.1172.2.96! raeburn 9836: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 9837: print (OUT undef);
9838: close (OUT);
9839: return ("ok");
9840: }
9841:
1.572 banghart 9842: sub files_in_path {
9843: my ($user, $path) = @_;
9844: my $filename = $user."savedfiles";
9845: my %return_files;
1.1172.2.96! raeburn 9846: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 9847: while (my $line_in = <IN>) {
1.574 banghart 9848: chomp ($line_in);
9849: my @paths_and_file = split (m!/!, $line_in);
9850: my $file_part = pop (@paths_and_file);
9851: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9852: $path_part.='/';
9853: my $path_and_file = $path_part.$file_part;
9854: if ($path_part eq $path) {
9855: $return_files{$file_part}= 'selected';
9856: }
9857: }
1.574 banghart 9858: close (IN);
9859: return (\%return_files);
1.572 banghart 9860: }
9861:
9862: # called in portfolio select mode, to show files selected NOT in current directory
9863: sub files_not_in_path {
9864: my ($user, $path) = @_;
9865: my $filename = $user."savedfiles";
9866: my @return_files;
9867: my $path_part;
1.1172.2.96! raeburn 9868: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 9869: while (my $line = <IN>) {
1.572 banghart 9870: #ok, I know it's clunky, but I want it to work
1.800 albertel 9871: my @paths_and_file = split(m|/|, $line);
9872: my $file_part = pop(@paths_and_file);
9873: chomp($file_part);
9874: my $path_part = join('/', @paths_and_file);
1.572 banghart 9875: $path_part .= '/';
9876: my $path_and_file = $path_part.$file_part;
9877: if ($path_part ne $path) {
1.800 albertel 9878: push(@return_files, ($path_and_file));
1.572 banghart 9879: }
9880: }
1.800 albertel 9881: close(OUT);
1.574 banghart 9882: return (@return_files);
1.572 banghart 9883: }
9884:
1.745 raeburn 9885: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9886:
1.745 raeburn 9887: sub get_portfile_permissions {
9888: my ($domain,$user) = @_;
1.613 albertel 9889: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9890: my ($tmp)=keys(%current_permissions);
9891: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9892: return \%current_permissions;
9893: }
9894:
9895: #---------------------------------------------Get portfolio file access controls
9896:
1.749 raeburn 9897: sub get_access_controls {
1.745 raeburn 9898: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9899: my %access;
9900: my $real_file = $file;
9901: $file =~ s/\.meta$//;
1.745 raeburn 9902: if (defined($file)) {
1.749 raeburn 9903: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9904: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9905: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9906: }
9907: }
1.745 raeburn 9908: } else {
1.749 raeburn 9909: foreach my $key (keys(%{$current_permissions})) {
9910: if ($key =~ /\0accesscontrol$/) {
9911: if (defined($group)) {
9912: if ($key !~ m-^\Q$group\E/-) {
9913: next;
9914: }
9915: }
9916: my ($fullpath) = split(/\0/,$key);
9917: if (ref($$current_permissions{$key}) eq 'HASH') {
9918: foreach my $control (keys(%{$$current_permissions{$key}})) {
9919: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9920: }
9921: }
9922: }
9923: }
9924: }
9925: return %access;
9926: }
9927:
9928: sub modify_access_controls {
9929: my ($file_name,$changes,$domain,$user)=@_;
9930: my ($outcome,$deloutcome);
9931: my %store_permissions;
9932: my %new_values;
9933: my %new_control;
9934: my %translation;
9935: my @deletions = ();
9936: my $now = time;
9937: if (exists($$changes{'activate'})) {
9938: if (ref($$changes{'activate'}) eq 'HASH') {
9939: my @newitems = sort(keys(%{$$changes{'activate'}}));
9940: my $numnew = scalar(@newitems);
9941: for (my $i=0; $i<$numnew; $i++) {
9942: my $newkey = $newitems[$i];
9943: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9944: if ($newkey =~ /^\d+:/) {
9945: $newkey =~ s/^(\d+)/$newid/;
9946: $translation{$1} = $newid;
9947: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9948: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9949: $translation{$1} = $newid;
9950: }
1.749 raeburn 9951: $new_values{$file_name."\0".$newkey} =
9952: $$changes{'activate'}{$newitems[$i]};
9953: $new_control{$newkey} = $now;
9954: }
9955: }
9956: }
9957: my %todelete;
9958: my %changed_items;
9959: foreach my $action ('delete','update') {
9960: if (exists($$changes{$action})) {
9961: if (ref($$changes{$action}) eq 'HASH') {
9962: foreach my $key (keys(%{$$changes{$action}})) {
9963: my ($itemnum) = ($key =~ /^([^:]+):/);
9964: if ($action eq 'delete') {
9965: $todelete{$itemnum} = 1;
9966: } else {
9967: $changed_items{$itemnum} = $key;
9968: }
9969: }
1.745 raeburn 9970: }
9971: }
1.749 raeburn 9972: }
9973: # get lock on access controls for file.
9974: my $lockhash = {
9975: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9976: ':'.$env{'user.domain'},
9977: };
9978: my $tries = 0;
9979: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9980:
1.1172.2.79 raeburn 9981: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9982: $tries ++;
1.1172.2.79 raeburn 9983: sleep(0.1);
1.749 raeburn 9984: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9985: }
9986: if ($gotlock eq 'ok') {
9987: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9988: my ($tmp)=keys(%curr_permissions);
9989: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9990: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9991: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9992: if (ref($curr_controls) eq 'HASH') {
9993: foreach my $control_item (keys(%{$curr_controls})) {
9994: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9995: if (defined($todelete{$itemnum})) {
9996: push(@deletions,$file_name."\0".$control_item);
9997: } else {
9998: if (defined($changed_items{$itemnum})) {
9999: $new_control{$changed_items{$itemnum}} = $now;
10000: push(@deletions,$file_name."\0".$control_item);
10001: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10002: } else {
10003: $new_control{$control_item} = $$curr_controls{$control_item};
10004: }
10005: }
1.745 raeburn 10006: }
10007: }
10008: }
1.970 raeburn 10009: my ($group);
10010: if (&is_course($domain,$user)) {
10011: ($group,my $file) = split(/\//,$file_name,2);
10012: }
1.749 raeburn 10013: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10014: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10015: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10016: # remove lock
10017: my @del_lock = ($file_name."\0".'locked_access_records');
10018: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10019: my $sqlresult =
1.970 raeburn 10020: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10021: $group);
1.749 raeburn 10022: } else {
10023: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10024: }
1.749 raeburn 10025: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10026: }
10027:
1.827 raeburn 10028: sub make_public_indefinitely {
10029: my ($requrl) = @_;
10030: my $now = time;
10031: my $action = 'activate';
10032: my $aclnum = 0;
10033: if (&is_portfolio_url($requrl)) {
10034: my (undef,$udom,$unum,$file_name,$group) =
10035: &parse_portfolio_url($requrl);
10036: my $current_perms = &get_portfile_permissions($udom,$unum);
10037: my %access_controls = &get_access_controls($current_perms,
10038: $group,$file_name);
10039: foreach my $key (keys(%{$access_controls{$file_name}})) {
10040: my ($num,$scope,$end,$start) =
10041: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10042: if ($scope eq 'public') {
10043: if ($start <= $now && $end == 0) {
10044: $action = 'none';
10045: } else {
10046: $action = 'update';
10047: $aclnum = $num;
10048: }
10049: last;
10050: }
10051: }
10052: if ($action eq 'none') {
10053: return 'ok';
10054: } else {
10055: my %changes;
10056: my $newend = 0;
10057: my $newstart = $now;
10058: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10059: $changes{$action}{$newkey} = {
10060: type => 'public',
10061: time => {
10062: start => $newstart,
10063: end => $newend,
10064: },
10065: };
10066: my ($outcome,$deloutcome,$new_values,$translation) =
10067: &modify_access_controls($file_name,\%changes,$udom,$unum);
10068: return $outcome;
10069: }
10070: } else {
10071: return 'invalid';
10072: }
10073: }
10074:
1.745 raeburn 10075: #------------------------------------------------------Get Marked as Read Only
10076:
10077: sub get_marked_as_readonly {
10078: my ($domain,$user,$what,$group) = @_;
10079: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10080: my @readonly_files;
1.629 banghart 10081: my $cmp1=$what;
10082: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10083: while (my ($file_name,$value) = each(%{$current_permissions})) {
10084: if (defined($group)) {
10085: if ($file_name !~ m-^\Q$group\E/-) {
10086: next;
10087: }
10088: }
1.561 banghart 10089: if (ref($value) eq "ARRAY"){
10090: foreach my $stored_what (@{$value}) {
1.629 banghart 10091: my $cmp2=$stored_what;
1.759 albertel 10092: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10093: $cmp2=join('',@{$stored_what});
1.745 raeburn 10094: }
1.629 banghart 10095: if ($cmp1 eq $cmp2) {
1.561 banghart 10096: push(@readonly_files, $file_name);
1.745 raeburn 10097: last;
1.563 banghart 10098: } elsif (!defined($what)) {
10099: push(@readonly_files, $file_name);
1.745 raeburn 10100: last;
1.561 banghart 10101: }
10102: }
1.745 raeburn 10103: }
1.561 banghart 10104: }
10105: return @readonly_files;
10106: }
1.577 banghart 10107: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10108:
1.577 banghart 10109: sub get_marked_as_readonly_hash {
1.745 raeburn 10110: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10111: my %readonly_files;
1.745 raeburn 10112: while (my ($file_name,$value) = each(%{$current_permissions})) {
10113: if (defined($group)) {
10114: if ($file_name !~ m-^\Q$group\E/-) {
10115: next;
10116: }
10117: }
1.577 banghart 10118: if (ref($value) eq "ARRAY"){
10119: foreach my $stored_what (@{$value}) {
1.745 raeburn 10120: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10121: foreach my $lock_descriptor(@{$stored_what}) {
10122: if ($lock_descriptor eq 'graded') {
10123: $readonly_files{$file_name} = 'graded';
10124: } elsif ($lock_descriptor eq 'handback') {
10125: $readonly_files{$file_name} = 'handback';
10126: } else {
10127: if (!exists($readonly_files{$file_name})) {
10128: $readonly_files{$file_name} = 'locked';
10129: }
10130: }
1.745 raeburn 10131: }
1.750 banghart 10132: }
1.577 banghart 10133: }
10134: }
10135: }
10136: return %readonly_files;
10137: }
1.559 banghart 10138: # ------------------------------------------------------------ Unmark as Read Only
10139:
10140: sub unmark_as_readonly {
1.629 banghart 10141: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10142: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10143: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10144: $file_name = &declutter_portfile($file_name);
1.634 albertel 10145: my $symb_crs = $what;
10146: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10147: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10148: my ($tmp)=keys(%current_permissions);
10149: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10150: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10151: foreach my $file (@readonly_files) {
1.759 albertel 10152: my $clean_file = &declutter_portfile($file);
10153: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10154: my $current_locks = $current_permissions{$file};
1.563 banghart 10155: my @new_locks;
10156: my @del_keys;
10157: if (ref($current_locks) eq "ARRAY"){
10158: foreach my $locker (@{$current_locks}) {
1.632 albertel 10159: my $compare=$locker;
1.749 raeburn 10160: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10161: $compare=join('',@{$locker});
1.746 raeburn 10162: if ($compare ne $symb_crs) {
10163: push(@new_locks, $locker);
10164: }
1.563 banghart 10165: }
10166: }
1.650 albertel 10167: if (scalar(@new_locks) > 0) {
1.563 banghart 10168: $current_permissions{$file} = \@new_locks;
10169: } else {
10170: push(@del_keys, $file);
1.613 albertel 10171: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10172: delete($current_permissions{$file});
1.563 banghart 10173: }
10174: }
1.561 banghart 10175: }
1.613 albertel 10176: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10177: return;
10178: }
1.512 banghart 10179:
1.17 www 10180: # ------------------------------------------------------------ Directory lister
10181:
10182: sub dirlist {
1.955 raeburn 10183: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10184: $uri=~s/^\///;
10185: $uri=~s/\/$//;
1.253 stredwic 10186: my ($udom, $uname);
1.955 raeburn 10187: if ($getuserdir) {
1.253 stredwic 10188: $udom = $userdomain;
10189: $uname = $username;
1.955 raeburn 10190: } else {
10191: (undef,$udom,$uname)=split(/\//,$uri);
10192: if(defined($userdomain)) {
10193: $udom = $userdomain;
10194: }
10195: if(defined($username)) {
10196: $uname = $username;
10197: }
1.253 stredwic 10198: }
1.955 raeburn 10199: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10200:
1.955 raeburn 10201: $dirRoot = $perlvar{'lonDocRoot'};
10202: if (defined($getpropath)) {
10203: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10204: $dirRoot =~ s/\/$//;
1.955 raeburn 10205: } elsif (defined($getuserdir)) {
10206: my $subdir=$uname.'__';
10207: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10208: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10209: ."/$udom/$subdir/$uname";
10210: } elsif (defined($alternateRoot)) {
10211: $dirRoot = $alternateRoot;
1.751 banghart 10212: }
1.253 stredwic 10213:
10214: if($udom) {
10215: if($uname) {
1.1135 raeburn 10216: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10217: if ($uhome eq 'no_host') {
10218: return ([],'no_host');
10219: }
1.955 raeburn 10220: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10221: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10222: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10223: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10224: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10225: } else {
10226: @listing_results = map { &unescape($_); } split(/:/,$listing);
10227: }
1.605 matthew 10228: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10229: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10230: @listing_results = split(/:/,$listing);
10231: } else {
10232: @listing_results = map { &unescape($_); } split(/:/,$listing);
10233: }
1.1135 raeburn 10234: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10235: ($listing eq 'rejected') || ($listing eq 'refused') ||
10236: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10237: return ([],$listing);
10238: } else {
10239: return (\@listing_results);
1.1135 raeburn 10240: }
1.955 raeburn 10241: } elsif(!$alternateRoot) {
1.1136 raeburn 10242: my (%allusers,%listerror);
1.841 albertel 10243: my %servers = &get_servers($udom,'library');
1.955 raeburn 10244: foreach my $tryserver (keys(%servers)) {
10245: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10246: &escape($udom),$tryserver);
10247: if ($listing eq 'unknown_cmd') {
10248: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10249: $udom, $tryserver);
10250: } else {
10251: @listing_results = map { &unescape($_); } split(/:/,$listing);
10252: }
1.841 albertel 10253: if ($listing eq 'unknown_cmd') {
10254: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10255: $udom, $tryserver);
10256: @listing_results = split(/:/,$listing);
10257: } else {
10258: @listing_results =
10259: map { &unescape($_); } split(/:/,$listing);
10260: }
1.1136 raeburn 10261: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10262: ($listing eq 'rejected') || ($listing eq 'refused') ||
10263: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10264: $listerror{$tryserver} = $listing;
10265: } else {
1.841 albertel 10266: foreach my $line (@listing_results) {
10267: my ($entry) = split(/&/,$line,2);
10268: $allusers{$entry} = 1;
10269: }
10270: }
1.253 stredwic 10271: }
1.1136 raeburn 10272: my @alluserslist=();
1.800 albertel 10273: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10274: push(@alluserslist,$user.'&user');
1.253 stredwic 10275: }
1.1172.2.80 raeburn 10276: if (!%listerror) {
10277: # no errors
10278: return (\@alluserslist);
10279: } elsif (scalar(keys(%servers)) == 1) {
10280: # one library server, one error
10281: my ($key) = keys(%listerror);
10282: return (\@alluserslist, $listerror{$key});
10283: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10284: # con_lost indicates that we might miss data from at least one
10285: # library server
10286: return (\@alluserslist, 'con_lost');
10287: } else {
10288: # multiple library servers and no con_lost -> data should be
10289: # complete.
10290: return (\@alluserslist);
10291: }
10292:
1.253 stredwic 10293: } else {
1.1136 raeburn 10294: return ([],'missing username');
1.253 stredwic 10295: }
1.955 raeburn 10296: } elsif(!defined($getpropath)) {
1.1136 raeburn 10297: my $path = $perlvar{'lonDocRoot'}.'/res/';
10298: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10299: return (\@all_domains);
1.955 raeburn 10300: } else {
1.1136 raeburn 10301: return ([],'missing domain');
1.275 stredwic 10302: }
10303: }
10304:
10305: # --------------------------------------------- GetFileTimestamp
10306: # This function utilizes dirlist and returns the date stamp for
10307: # when it was last modified. It will also return an error of -1
10308: # if an error occurs
10309:
10310: sub GetFileTimestamp {
1.955 raeburn 10311: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10312: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10313: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10314: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10315: undef,$getuserdir);
10316: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10317: return -1;
10318: }
10319: if (ref($fileref) eq 'ARRAY') {
10320: my @stats = split('&',$fileref->[0]);
1.375 matthew 10321: # @stats contains first the filename, then the stat output
10322: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10323: } else {
10324: return -1;
1.253 stredwic 10325: }
1.26 www 10326: }
10327:
1.712 albertel 10328: sub stat_file {
10329: my ($uri) = @_;
1.787 albertel 10330: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10331:
1.955 raeburn 10332: my ($udom,$uname,$file);
1.712 albertel 10333: if ($uri =~ m-^/(uploaded|editupload)/-) {
10334: ($udom,$uname,$file) =
1.811 albertel 10335: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10336: $file = 'userfiles/'.$file;
10337: }
10338: if ($uri =~ m-^/res/-) {
10339: ($udom,$uname) =
1.807 albertel 10340: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10341: $file = $uri;
10342: }
10343:
10344: if (!$udom || !$uname || !$file) {
10345: # unable to handle the uri
10346: return ();
10347: }
1.956 raeburn 10348: my $getpropath;
10349: if ($file =~ /^userfiles\//) {
10350: $getpropath = 1;
10351: }
1.1136 raeburn 10352: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10353: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10354: return ();
10355: } else {
10356: if (ref($listref) eq 'ARRAY') {
10357: my @stats = split('&',$listref->[0]);
10358: shift(@stats); #filename is first
10359: return @stats;
10360: }
1.712 albertel 10361: }
10362: return ();
10363: }
10364:
1.26 www 10365: # -------------------------------------------------------- Value of a Condition
10366:
1.713 albertel 10367: # gets the value of a specific preevaluated condition
10368: # stored in the string $env{user.state.<cid>}
10369: # or looks up a condition reference in the bighash and if if hasn't
10370: # already been evaluated recurses into docondval to get the value of
10371: # the condition, then memoizing it to
10372: # $env{user.state.<cid>.<condition>}
1.40 www 10373: sub directcondval {
10374: my $number=shift;
1.620 albertel 10375: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10376: &Apache::lonuserstate::evalstate();
10377: }
1.713 albertel 10378: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10379: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10380: } elsif ($number =~ /^_/) {
10381: my $sub_condition;
10382: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10383: &GDBM_READER(),0640)) {
10384: $sub_condition=$bighash{'conditions'.$number};
10385: untie(%bighash);
10386: }
10387: my $value = &docondval($sub_condition);
1.949 raeburn 10388: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10389: return $value;
10390: }
1.620 albertel 10391: if ($env{'user.state.'.$env{'request.course.id'}}) {
10392: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10393: } else {
10394: return 2;
10395: }
10396: }
10397:
1.713 albertel 10398: # get the collection of conditions for this resource
1.26 www 10399: sub condval {
10400: my $condidx=shift;
1.54 www 10401: my $allpathcond='';
1.713 albertel 10402: foreach my $cond (split(/\|/,$condidx)) {
10403: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10404: $allpathcond.=
10405: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10406: }
1.191 harris41 10407: }
1.54 www 10408: $allpathcond=~s/\|$//;
1.713 albertel 10409: return &docondval($allpathcond);
10410: }
10411:
10412: #evaluates an expression of conditions
10413: sub docondval {
10414: my ($allpathcond) = @_;
10415: my $result=0;
10416: if ($env{'request.course.id'}
10417: && defined($allpathcond)) {
10418: my $operand='|';
10419: my @stack;
10420: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10421: if ($chunk eq '(') {
10422: push @stack,($operand,$result);
10423: } elsif ($chunk eq ')') {
10424: my $before=pop @stack;
10425: if (pop @stack eq '&') {
10426: $result=$result>$before?$before:$result;
10427: } else {
10428: $result=$result>$before?$result:$before;
10429: }
10430: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10431: $operand=$chunk;
10432: } else {
10433: my $new=directcondval($chunk);
10434: if ($operand eq '&') {
10435: $result=$result>$new?$new:$result;
10436: } else {
10437: $result=$result>$new?$result:$new;
10438: }
10439: }
10440: }
1.26 www 10441: }
10442: return $result;
1.421 albertel 10443: }
10444:
10445: # ---------------------------------------------------- Devalidate courseresdata
10446:
10447: sub devalidatecourseresdata {
10448: my ($coursenum,$coursedomain)=@_;
10449: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10450: &devalidate_cache_new('courseres',$hashid);
1.28 www 10451: }
10452:
1.763 www 10453:
1.200 www 10454: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10455: #
10456: # Parameters:
10457: # $coursenum - Number of the course.
10458: # $coursedomain - Domain at which the course was created.
10459: # Returns:
10460: # A hash of the course parameters along (I think) with timestamps
10461: # and version info.
1.877 foxr 10462:
1.624 albertel 10463: sub get_courseresdata {
10464: my ($coursenum,$coursedomain)=@_;
1.200 www 10465: my $coursehom=&homeserver($coursenum,$coursedomain);
10466: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10467: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10468: my %dumpreply;
1.417 albertel 10469: unless (defined($cached)) {
1.624 albertel 10470: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10471: $result=\%dumpreply;
1.251 albertel 10472: my ($tmp) = keys(%dumpreply);
10473: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10474: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10475: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10476: return $tmp;
1.416 albertel 10477: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10478: $result=undef;
1.599 albertel 10479: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10480: }
10481: }
1.624 albertel 10482: return $result;
10483: }
10484:
1.633 albertel 10485: sub devalidateuserresdata {
10486: my ($uname,$udom)=@_;
10487: my $hashid="$udom:$uname";
10488: &devalidate_cache_new('userres',$hashid);
10489: }
10490:
1.624 albertel 10491: sub get_userresdata {
10492: my ($uname,$udom)=@_;
10493: #most student don\'t have any data set, check if there is some data
10494: if (&EXT_cache_status($udom,$uname)) { return undef; }
10495:
10496: my $hashid="$udom:$uname";
10497: my ($result,$cached)=&is_cached_new('userres',$hashid);
10498: if (!defined($cached)) {
10499: my %resourcedata=&dump('resourcedata',$udom,$uname);
10500: $result=\%resourcedata;
10501: &do_cache_new('userres',$hashid,$result,600);
10502: }
10503: my ($tmp)=keys(%$result);
10504: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10505: return $result;
10506: }
10507: #error 2 occurs when the .db doesn't exist
10508: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10509: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10510: &logthis("<font color=\"blue\">WARNING:".
10511: " Trying to get resource data for ".
10512: $uname." at ".$udom.": ".
10513: $tmp."</font>");
10514: }
1.624 albertel 10515: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10516: #&EXT_cache_set($udom,$uname);
10517: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10518: undef($tmp); # not really an error so don't send it back
1.624 albertel 10519: }
10520: return $tmp;
10521: }
1.879 foxr 10522: #----------------------------------------------- resdata - return resource data
10523: # Purpose:
10524: # Return resource data for either users or for a course.
10525: # Parameters:
10526: # $name - Course/user name.
10527: # $domain - Name of the domain the user/course is registered on.
10528: # $type - Type of thing $name is (must be 'course' or 'user'
10529: # @which - Array of names of resources desired.
10530: # Returns:
10531: # The value of the first reasource in @which that is found in the
10532: # resource hash.
10533: # Exceptional Conditions:
10534: # If the $type passed in is not valid (not the string 'course' or
10535: # 'user', an undefined reference is returned.
10536: # If none of the resources are found, an undef is returned
1.624 albertel 10537: sub resdata {
10538: my ($name,$domain,$type,@which)=@_;
10539: my $result;
10540: if ($type eq 'course') {
10541: $result=&get_courseresdata($name,$domain);
10542: } elsif ($type eq 'user') {
10543: $result=&get_userresdata($name,$domain);
10544: }
10545: if (!ref($result)) { return $result; }
1.251 albertel 10546: foreach my $item (@which) {
1.927 albertel 10547: if (defined($result->{$item->[0]})) {
10548: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10549: }
1.250 albertel 10550: }
1.291 albertel 10551: return undef;
1.200 www 10552: }
10553:
1.1172.2.31 raeburn 10554: sub get_numsuppfiles {
10555: my ($cnum,$cdom,$ignorecache)=@_;
10556: my $hashid=$cnum.':'.$cdom;
10557: my ($suppcount,$cached);
10558: unless ($ignorecache) {
10559: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10560: }
10561: unless (defined($cached)) {
10562: my $chome=&homeserver($cnum,$cdom);
10563: unless ($chome eq 'no_host') {
10564: ($suppcount,my $errors) = (0,0);
10565: my $suppmap = 'supplemental.sequence';
10566: ($suppcount,$errors) =
10567: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10568: }
10569: &do_cache_new('suppcount',$hashid,$suppcount,600);
10570: }
10571: return $suppcount;
10572: }
10573:
1.379 matthew 10574: #
10575: # EXT resource caching routines
10576: #
10577:
10578: sub clear_EXT_cache_status {
1.383 albertel 10579: &delenv('cache.EXT.');
1.379 matthew 10580: }
10581:
10582: sub EXT_cache_status {
10583: my ($target_domain,$target_user) = @_;
1.383 albertel 10584: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10585: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10586: # We know already the user has no data
10587: return 1;
10588: } else {
10589: return 0;
10590: }
10591: }
10592:
10593: sub EXT_cache_set {
10594: my ($target_domain,$target_user) = @_;
1.383 albertel 10595: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10596: #&appenv({$cachename => time});
1.379 matthew 10597: }
10598:
1.28 www 10599: # --------------------------------------------------------- Value of a Variable
1.58 www 10600: sub EXT {
1.715 albertel 10601:
1.1172.2.28 raeburn 10602: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10603: unless ($varname) { return ''; }
1.218 albertel 10604: #get real user name/domain, courseid and symb
10605: my $courseid;
1.359 albertel 10606: my $publicuser;
1.427 www 10607: if ($symbparm) {
10608: $symbparm=&get_symb_from_alias($symbparm);
10609: }
1.218 albertel 10610: if (!($uname && $udom)) {
1.790 albertel 10611: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10612: if (!$symbparm) { $symbparm=$cursymb; }
10613: } else {
1.620 albertel 10614: $courseid=$env{'request.course.id'};
1.218 albertel 10615: }
1.48 www 10616: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10617: my $rest;
1.320 albertel 10618: if (defined($therest[0])) {
1.48 www 10619: $rest=join('.',@therest);
10620: } else {
10621: $rest='';
10622: }
1.320 albertel 10623:
1.57 www 10624: my $qualifierrest=$qualifier;
10625: if ($rest) { $qualifierrest.='.'.$rest; }
10626: my $spacequalifierrest=$space;
10627: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10628: if ($realm eq 'user') {
1.48 www 10629: # --------------------------------------------------------------- user.resource
10630: if ($space eq 'resource') {
1.651 albertel 10631: if ( (defined($Apache::lonhomework::parsing_a_problem)
10632: || defined($Apache::lonhomework::parsing_a_task))
10633: &&
1.744 albertel 10634: ($symbparm eq &symbread()) ) {
10635: # if we are in the middle of processing the resource the
10636: # get the value we are planning on committing
10637: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10638: return $Apache::lonhomework::results{$qualifierrest};
10639: } else {
10640: return $Apache::lonhomework::history{$qualifierrest};
10641: }
1.335 albertel 10642: } else {
1.359 albertel 10643: my %restored;
1.620 albertel 10644: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10645: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10646: } else {
10647: %restored=&restore($symbparm,$courseid,$udom,$uname);
10648: }
1.335 albertel 10649: return $restored{$qualifierrest};
10650: }
1.48 www 10651: # ----------------------------------------------------------------- user.access
10652: } elsif ($space eq 'access') {
1.218 albertel 10653: # FIXME - not supporting calls for a specific user
1.48 www 10654: return &allowed($qualifier,$rest);
10655: # ------------------------------------------ user.preferences, user.environment
10656: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10657: if (($uname eq $env{'user.name'}) &&
10658: ($udom eq $env{'user.domain'})) {
10659: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10660: } else {
1.359 albertel 10661: my %returnhash;
10662: if (!$publicuser) {
10663: %returnhash=&userenvironment($udom,$uname,
10664: $qualifierrest);
10665: }
1.218 albertel 10666: return $returnhash{$qualifierrest};
10667: }
1.48 www 10668: # ----------------------------------------------------------------- user.course
10669: } elsif ($space eq 'course') {
1.218 albertel 10670: # FIXME - not supporting calls for a specific user
1.620 albertel 10671: return $env{join('.',('request.course',$qualifier))};
1.48 www 10672: # ------------------------------------------------------------------- user.role
10673: } elsif ($space eq 'role') {
1.218 albertel 10674: # FIXME - not supporting calls for a specific user
1.620 albertel 10675: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10676: if ($qualifier eq 'value') {
10677: return $role;
10678: } elsif ($qualifier eq 'extent') {
10679: return $where;
10680: }
10681: # ----------------------------------------------------------------- user.domain
10682: } elsif ($space eq 'domain') {
1.218 albertel 10683: return $udom;
1.48 www 10684: # ------------------------------------------------------------------- user.name
10685: } elsif ($space eq 'name') {
1.218 albertel 10686: return $uname;
1.48 www 10687: # ---------------------------------------------------- Any other user namespace
1.29 www 10688: } else {
1.359 albertel 10689: my %reply;
10690: if (!$publicuser) {
10691: %reply=&get($space,[$qualifierrest],$udom,$uname);
10692: }
10693: return $reply{$qualifierrest};
1.48 www 10694: }
1.236 www 10695: } elsif ($realm eq 'query') {
10696: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10697: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10698: [$spacequalifierrest]);
1.620 albertel 10699: return $env{'form.'.$spacequalifierrest};
1.236 www 10700: } elsif ($realm eq 'request') {
1.48 www 10701: # ------------------------------------------------------------- request.browser
10702: if ($space eq 'browser') {
1.1145 bisitz 10703: return $env{'browser.'.$qualifier};
1.57 www 10704: # ------------------------------------------------------------ request.filename
10705: } else {
1.620 albertel 10706: return $env{'request.'.$spacequalifierrest};
1.29 www 10707: }
1.28 www 10708: } elsif ($realm eq 'course') {
1.48 www 10709: # ---------------------------------------------------------- course.description
1.620 albertel 10710: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10711: } elsif ($realm eq 'resource') {
1.165 www 10712:
1.620 albertel 10713: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10714: if (!$symbparm) { $symbparm=&symbread(); }
10715: }
1.693 albertel 10716:
1.1172.2.30 raeburn 10717: if ($qualifier eq '') {
10718: if ($space eq 'title') {
10719: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10720: return &gettitle($symbparm);
10721: }
1.693 albertel 10722:
1.1172.2.30 raeburn 10723: if ($space eq 'map') {
10724: my ($map) = &decode_symb($symbparm);
10725: return &symbread($map);
10726: }
10727: if ($space eq 'maptitle') {
10728: my ($map) = &decode_symb($symbparm);
10729: return &gettitle($map);
10730: }
10731: if ($space eq 'filename') {
10732: if ($symbparm) {
10733: return &clutter((&decode_symb($symbparm))[2]);
10734: }
10735: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10736: }
1.1172.2.30 raeburn 10737:
10738: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10739: if ($space eq 'visibleparts') {
10740: my $navmap = Apache::lonnavmaps::navmap->new();
10741: my $item;
10742: if (ref($navmap)) {
10743: my $res = $navmap->getBySymb($symbparm);
10744: my $parts = $res->parts();
10745: if (ref($parts) eq 'ARRAY') {
10746: $item = join(',',@{$parts});
10747: }
10748: undef($navmap);
10749: }
10750: return $item;
10751: }
10752: }
10753: }
1.693 albertel 10754:
10755: my ($section, $group, @groups);
1.593 albertel 10756: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10757: if (($courseid eq '') && ($cid)) {
10758: $courseid = $cid;
10759: }
10760: if (($symbparm && $courseid) &&
10761: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10762:
1.218 albertel 10763: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10764:
1.60 www 10765: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10766: my $symbp=$symbparm;
1.735 albertel 10767: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10768:
10769: my $symbparm=$symbp.'.'.$spacequalifierrest;
10770: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10771:
1.620 albertel 10772: if (($env{'user.name'} eq $uname) &&
10773: ($env{'user.domain'} eq $udom)) {
10774: $section=$env{'request.course.sec'};
1.733 raeburn 10775: @groups = split(/:/,$env{'request.course.groups'});
10776: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10777: } else {
1.539 albertel 10778: if (! defined($usection)) {
1.551 albertel 10779: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10780: } else {
10781: $section = $usection;
10782: }
1.733 raeburn 10783: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10784: }
10785:
10786: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10787: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10788: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10789:
1.593 albertel 10790: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10791: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10792: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10793:
1.60 www 10794: # ----------------------------------------------------------- first, check user
1.624 albertel 10795:
10796: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10797: ([$courselevelr,'resource'],
10798: [$courselevelm,'map' ],
10799: [$courselevel, 'course' ]));
1.931 albertel 10800: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10801:
1.594 albertel 10802: # ------------------------------------------------ second, check some of course
1.684 raeburn 10803: my $coursereply;
1.691 raeburn 10804: if (@groups > 0) {
10805: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10806: $mapparm,$spacequalifierrest);
1.927 albertel 10807: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10808: }
1.96 www 10809:
1.684 raeburn 10810: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10811: $env{'course.'.$courseid.'.domain'},
10812: 'course',
10813: ([$seclevelr, 'resource'],
10814: [$seclevelm, 'map' ],
10815: [$seclevel, 'course' ],
10816: [$courselevelr,'resource']));
10817: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10818:
1.60 www 10819: # ------------------------------------------------------ third, check map parms
1.218 albertel 10820: my %parmhash=();
10821: my $thisparm='';
10822: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10823: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10824: &GDBM_READER(),0640)) {
1.218 albertel 10825: $thisparm=$parmhash{$symbparm};
10826: untie(%parmhash);
10827: }
1.927 albertel 10828: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10829: }
1.594 albertel 10830: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10831:
1.218 albertel 10832: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10833: my $filename;
10834: if (!$symbparm) { $symbparm=&symbread(); }
10835: if ($symbparm) {
1.409 www 10836: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10837: } else {
1.620 albertel 10838: $filename=$env{'request.filename'};
1.282 albertel 10839: }
10840: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10841: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10842: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10843: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10844:
1.927 albertel 10845: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10846: if ($symbparm && defined($courseid) &&
1.620 albertel 10847: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10848: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10849: $env{'course.'.$courseid.'.domain'},
10850: 'course',
1.927 albertel 10851: ([$courselevelm,'map' ],
10852: [$courselevel, 'course']));
10853: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10854: }
1.145 www 10855: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10856: unless ($space eq '0') {
1.336 albertel 10857: my @parts=split(/_/,$space);
10858: my $id=pop(@parts);
10859: my $part=join('_',@parts);
10860: if ($part eq '') { $part='0'; }
1.927 albertel 10861: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10862: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10863: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10864: }
1.395 albertel 10865: if ($recurse) { return undef; }
10866: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10867: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10868: # ---------------------------------------------------- Any other user namespace
10869: } elsif ($realm eq 'environment') {
10870: # ----------------------------------------------------------------- environment
1.620 albertel 10871: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10872: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10873: } else {
1.770 albertel 10874: if ($uname eq 'anonymous' && $udom eq '') {
10875: return '';
10876: }
1.219 albertel 10877: my %returnhash=&userenvironment($udom,$uname,
10878: $spacequalifierrest);
10879: return $returnhash{$spacequalifierrest};
10880: }
1.28 www 10881: } elsif ($realm eq 'system') {
1.48 www 10882: # ----------------------------------------------------------------- system.time
10883: if ($space eq 'time') {
10884: return time;
10885: }
1.696 albertel 10886: } elsif ($realm eq 'server') {
10887: # ----------------------------------------------------------------- system.time
10888: if ($space eq 'name') {
10889: return $ENV{'SERVER_NAME'};
10890: }
1.28 www 10891: }
1.48 www 10892: return '';
1.61 www 10893: }
10894:
1.927 albertel 10895: sub get_reply {
10896: my ($reply_value) = @_;
1.940 raeburn 10897: if (ref($reply_value) eq 'ARRAY') {
10898: if (wantarray) {
10899: return @$reply_value;
10900: }
10901: return $reply_value->[0];
10902: } else {
10903: return $reply_value;
1.927 albertel 10904: }
10905: }
10906:
1.691 raeburn 10907: sub check_group_parms {
10908: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10909: my @groupitems = ();
10910: my $resultitem;
1.927 albertel 10911: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10912: foreach my $group (@{$groups}) {
10913: foreach my $level (@levels) {
1.927 albertel 10914: my $item = $courseid.'.['.$group.'].'.$level->[0];
10915: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10916: }
10917: }
10918: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10919: $env{'course.'.$courseid.'.domain'},
10920: 'course',@groupitems);
10921: return $coursereply;
10922: }
10923:
10924: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10925: my ($courseid,@groups) = @_;
10926: @groups = sort(@groups);
1.691 raeburn 10927: return @groups;
10928: }
10929:
1.395 albertel 10930: sub packages_tab_default {
10931: my ($uri,$varname)=@_;
10932: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10933:
10934: my (@extension,@specifics,$do_default);
10935: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10936: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10937: if ($pack_type eq 'default') {
10938: $do_default=1;
10939: } elsif ($pack_type eq 'extension') {
10940: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10941: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10942: # only look at packages defaults for packages that this id is
1.738 albertel 10943: push(@specifics,[$package,$pack_type,$pack_part]);
10944: }
10945: }
10946: # first look for a package that matches the requested part id
10947: foreach my $package (@specifics) {
10948: my (undef,$pack_type,$pack_part)=@{$package};
10949: next if ($pack_part ne $part);
10950: if (defined($packagetab{"$pack_type&$name&default"})) {
10951: return $packagetab{"$pack_type&$name&default"};
10952: }
10953: }
10954: # look for any possible matching non extension_ package
10955: foreach my $package (@specifics) {
10956: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10957: if (defined($packagetab{"$pack_type&$name&default"})) {
10958: return $packagetab{"$pack_type&$name&default"};
10959: }
1.585 albertel 10960: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10961: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10962: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10963: }
10964: }
1.738 albertel 10965: # look for any posible extension_ match
10966: foreach my $package (@extension) {
10967: my ($package,$pack_type)=@{$package};
10968: if (defined($packagetab{"$pack_type&$name&default"})) {
10969: return $packagetab{"$pack_type&$name&default"};
10970: }
10971: if (defined($packagetab{$package."&$name&default"})) {
10972: return $packagetab{$package."&$name&default"};
10973: }
10974: }
10975: # look for a global default setting
10976: if ($do_default && defined($packagetab{"default&$name&default"})) {
10977: return $packagetab{"default&$name&default"};
10978: }
1.395 albertel 10979: return undef;
10980: }
10981:
1.334 albertel 10982: sub add_prefix_and_part {
10983: my ($prefix,$part)=@_;
10984: my $keyroot;
10985: if (defined($prefix) && $prefix !~ /^__/) {
10986: # prefix that has a part already
10987: $keyroot=$prefix;
10988: } elsif (defined($prefix)) {
10989: # prefix that is missing a part
10990: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10991: } else {
10992: # no prefix at all
10993: if (defined($part)) { $keyroot='_'.$part; }
10994: }
10995: return $keyroot;
10996: }
10997:
1.71 www 10998: # ---------------------------------------------------------------- Get metadata
10999:
1.599 albertel 11000: my %metaentry;
1.1070 www 11001: my %importedpartids;
1.71 www 11002: sub metadata {
1.176 www 11003: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11004: $uri=&declutter($uri);
1.288 albertel 11005: # if it is a non metadata possible uri return quickly
1.529 albertel 11006: if (($uri eq '') ||
11007: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11008: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11009: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11010: return undef;
11011: }
1.1172.2.49 raeburn 11012: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11013: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11014: return undef;
1.288 albertel 11015: }
1.73 www 11016: my $filename=$uri;
11017: $uri=~s/\.meta$//;
1.172 www 11018: #
11019: # Is the metadata already cached?
1.177 www 11020: # Look at timestamp of caching
1.172 www 11021: # Everything is cached by the main uri, libraries are never directly cached
11022: #
1.428 albertel 11023: if (!defined($liburi)) {
1.599 albertel 11024: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11025: if (defined($cached)) { return $result->{':'.$what}; }
11026: }
11027: {
1.1069 www 11028: # Imported parts would go here
1.1070 www 11029: my %importedids=();
11030: my @origfileimportpartids=();
1.1069 www 11031: my $importedparts=0;
1.172 www 11032: #
11033: # Is this a recursive call for a library?
11034: #
1.599 albertel 11035: # if (! exists($metacache{$uri})) {
11036: # $metacache{$uri}={};
11037: # }
1.924 albertel 11038: my $cachetime = 60*60;
1.171 www 11039: if ($liburi) {
11040: $liburi=&declutter($liburi);
11041: $filename=$liburi;
1.401 bowersj2 11042: } else {
1.599 albertel 11043: &devalidate_cache_new('meta',$uri);
11044: undef(%metaentry);
1.401 bowersj2 11045: }
1.140 www 11046: my %metathesekeys=();
1.73 www 11047: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11048: my $metastring;
1.1140 www 11049: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11050: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11051: $metastring =
1.929 albertel 11052: &Apache::lonnet::ssi_body($which,
1.924 albertel 11053: ('grade_target' => 'meta'));
11054: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11055: } elsif (($uri !~ m -^(editupload)/-) &&
11056: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11057: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11058: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11059: $metastring=&getfile($file);
1.489 albertel 11060: }
1.208 albertel 11061: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11062: my $token;
1.140 www 11063: undef %metathesekeys;
1.71 www 11064: while ($token=$parser->get_token) {
1.339 albertel 11065: if ($token->[0] eq 'S') {
11066: if (defined($token->[2]->{'package'})) {
1.172 www 11067: #
11068: # This is a package - get package info
11069: #
1.339 albertel 11070: my $package=$token->[2]->{'package'};
11071: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11072: if (defined($token->[2]->{'id'})) {
11073: $keyroot.='_'.$token->[2]->{'id'};
11074: }
1.599 albertel 11075: if ($metaentry{':packages'}) {
11076: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11077: } else {
1.599 albertel 11078: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11079: }
1.736 albertel 11080: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11081: my $part=$keyroot;
11082: $part=~s/^\_//;
1.736 albertel 11083: if ($pack_entry=~/^\Q$package\E\&/ ||
11084: $pack_entry=~/^\Q$package\E_0\&/) {
11085: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11086: # ignore package.tab specified default values
11087: # here &package_tab_default() will fetch those
11088: if ($subp eq 'default') { next; }
1.736 albertel 11089: my $value=$packagetab{$pack_entry};
1.432 albertel 11090: my $unikey;
11091: if ($pack =~ /_0$/) {
11092: $unikey='parameter_0_'.$name;
11093: $part=0;
11094: } else {
11095: $unikey='parameter'.$keyroot.'_'.$name;
11096: }
1.339 albertel 11097: if ($subp eq 'display') {
11098: $value.=' [Part: '.$part.']';
11099: }
1.599 albertel 11100: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11101: $metathesekeys{$unikey}=1;
1.599 albertel 11102: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11103: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11104: }
1.599 albertel 11105: if (defined($metaentry{':'.$unikey.'.default'})) {
11106: $metaentry{':'.$unikey}=
11107: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11108: }
1.339 albertel 11109: }
11110: }
11111: } else {
1.172 www 11112: #
11113: # This is not a package - some other kind of start tag
1.339 albertel 11114: #
11115: my $entry=$token->[1];
1.1068 www 11116: my $unikey='';
1.175 www 11117:
1.339 albertel 11118: if ($entry eq 'import') {
1.175 www 11119: #
11120: # Importing a library here
1.339 albertel 11121: #
1.1067 www 11122: my $location=$parser->get_text('/import');
11123: my $dir=$filename;
11124: $dir=~s|[^/]*$||;
11125: $location=&filelocation($dir,$location);
1.1069 www 11126:
1.1068 www 11127: my $importmode=$token->[2]->{'importmode'};
11128: if ($importmode eq 'problem') {
1.1069 www 11129: # Import as problem/response
1.1068 www 11130: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11131: } elsif ($importmode eq 'part') {
11132: # Import as part(s)
1.1069 www 11133: $importedparts=1;
11134: # We need to get the original file and the imported file to get the part order correct
11135: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11136: # Load and inspect original file
1.1070 www 11137: if ($#origfileimportpartids<0) {
11138: undef(%importedpartids);
11139: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11140: my $origfile=&getfile($origfilelocation);
11141: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11142: }
11143:
1.1069 www 11144: # Load and inspect imported file
11145: my $impfile=&getfile($location);
11146: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11147: if ($#impfilepartids>=0) {
11148: # This problem had parts
1.1070 www 11149: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11150: } else {
11151: # Importing by turning a single problem into a problem part
11152: # It gets the import-tags ID as part-ID
11153: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11154: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11155: }
1.1068 www 11156: } else {
11157: # Normal import
11158: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11159: if (defined($token->[2]->{'id'})) {
11160: $unikey.='_'.$token->[2]->{'id'};
11161: }
1.1067 www 11162: }
11163:
1.339 albertel 11164: if ($depthcount<20) {
1.736 albertel 11165: my $metadata =
11166: &metadata($uri,'keys', $location,$unikey,
11167: $depthcount+1);
11168: foreach my $meta (split(',',$metadata)) {
11169: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11170: $metathesekeys{$meta}=1;
1.339 albertel 11171: }
1.1068 www 11172:
11173: }
1.1067 www 11174: } else {
11175: #
11176: # Not importing, some other kind of non-package, non-library start tag
11177: #
11178: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11179: if (defined($token->[2]->{'id'})) {
11180: $unikey.='_'.$token->[2]->{'id'};
11181: }
1.339 albertel 11182: if (defined($token->[2]->{'name'})) {
11183: $unikey.='_'.$token->[2]->{'name'};
11184: }
11185: $metathesekeys{$unikey}=1;
1.736 albertel 11186: foreach my $param (@{$token->[3]}) {
11187: $metaentry{':'.$unikey.'.'.$param} =
11188: $token->[2]->{$param};
1.339 albertel 11189: }
11190: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11191: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11192: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11193: # only ws inside the tag, and not in default, so use default
11194: # as value
1.599 albertel 11195: $metaentry{':'.$unikey}=$default;
1.908 albertel 11196: } elsif ( $internaltext =~ /\S/ ) {
11197: # something interesting inside the tag
11198: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11199: } else {
1.908 albertel 11200: # no interesting values, don't set a default
1.339 albertel 11201: }
1.172 www 11202: # end of not-a-package not-a-library import
1.339 albertel 11203: }
1.172 www 11204: # end of not-a-package start tag
1.339 albertel 11205: }
1.172 www 11206: # the next is the end of "start tag"
1.339 albertel 11207: }
11208: }
1.483 albertel 11209: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11210: $extension = lc($extension);
11211: if ($extension eq 'htm') { $extension='html'; }
11212:
1.737 albertel 11213: foreach my $key (keys(%packagetab)) {
1.483 albertel 11214: #no specific packages #how's our extension
11215: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11216: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11217: \%metathesekeys);
11218: }
1.883 albertel 11219:
11220: if (!exists($metaentry{':packages'})
11221: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11222: foreach my $key (keys(%packagetab)) {
1.483 albertel 11223: #no specific packages well let's get default then
11224: if ($key!~/^default&/) { next; }
1.488 albertel 11225: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11226: \%metathesekeys);
11227: }
11228: }
1.338 www 11229: # are there custom rights to evaluate
1.599 albertel 11230: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11231:
1.338 www 11232: #
11233: # Importing a rights file here
1.339 albertel 11234: #
11235: unless ($depthcount) {
1.599 albertel 11236: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11237: my $dir=$filename;
11238: $dir=~s|[^/]*$||;
11239: $location=&filelocation($dir,$location);
1.736 albertel 11240: my $rights_metadata =
11241: &metadata($uri,'keys',$location,'_rights',
11242: $depthcount+1);
11243: foreach my $rights (split(',',$rights_metadata)) {
11244: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11245: $metathesekeys{$rights}=1;
1.339 albertel 11246: }
11247: }
11248: }
1.737 albertel 11249: # uniqifiy package listing
11250: my %seen;
11251: my @uniq_packages =
11252: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11253: $metaentry{':packages'} = join(',',@uniq_packages);
11254:
1.1070 www 11255: if ($importedparts) {
11256: # We had imported parts and need to rebuild partorder
11257: $metaentry{':partorder'}='';
11258: $metathesekeys{'partorder'}=1;
11259: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11260: if ($origfileimportpartids[$index] eq 'part') {
11261: # original part, part of the problem
11262: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11263: } else {
11264: # we have imported parts at this position
11265: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11266: }
11267: }
11268: $metaentry{':partorder'}=~s/^\,//;
11269: }
11270:
1.737 albertel 11271: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11272: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11273: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11274: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11275: # this is the end of "was not already recently cached
1.71 www 11276: }
1.599 albertel 11277: return $metaentry{':'.$what};
1.261 albertel 11278: }
11279:
1.488 albertel 11280: sub metadata_create_package_def {
1.483 albertel 11281: my ($uri,$key,$package,$metathesekeys)=@_;
11282: my ($pack,$name,$subp)=split(/\&/,$key);
11283: if ($subp eq 'default') { next; }
11284:
1.599 albertel 11285: if (defined($metaentry{':packages'})) {
11286: $metaentry{':packages'}.=','.$package;
1.483 albertel 11287: } else {
1.599 albertel 11288: $metaentry{':packages'}=$package;
1.483 albertel 11289: }
11290: my $value=$packagetab{$key};
11291: my $unikey;
11292: $unikey='parameter_0_'.$name;
1.599 albertel 11293: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11294: $$metathesekeys{$unikey}=1;
1.599 albertel 11295: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11296: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11297: }
1.599 albertel 11298: if (defined($metaentry{':'.$unikey.'.default'})) {
11299: $metaentry{':'.$unikey}=
11300: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11301: }
11302: }
11303:
1.261 albertel 11304: sub metadata_generate_part0 {
11305: my ($metadata,$metacache,$uri) = @_;
11306: my %allnames;
1.737 albertel 11307: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11308: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11309: my $part=$$metacache{':'.$metakey.'.part'};
11310: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11311: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11312: $allnames{$name}=$part;
11313: }
11314: }
11315: }
11316: foreach my $name (keys(%allnames)) {
11317: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11318: my $key=":parameter_0_$name";
1.261 albertel 11319: $$metacache{"$key.part"}='0';
11320: $$metacache{"$key.name"}=$name;
1.428 albertel 11321: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11322: $allnames{$name}.'_'.$name.
11323: '.type'};
1.428 albertel 11324: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11325: '.display'};
1.644 www 11326: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11327: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11328: $$metacache{"$key.display"}=$olddis;
11329: }
1.71 www 11330: }
11331:
1.764 albertel 11332: # ------------------------------------------------------ Devalidate title cache
11333:
11334: sub devalidate_title_cache {
11335: my ($url)=@_;
11336: if (!$env{'request.course.id'}) { return; }
11337: my $symb=&symbread($url);
11338: if (!$symb) { return; }
11339: my $key=$env{'request.course.id'}."\0".$symb;
11340: &devalidate_cache_new('title',$key);
11341: }
11342:
1.1014 droeschl 11343: # ------------------------------------------------- Get the title of a course
11344:
11345: sub current_course_title {
11346: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11347: }
1.301 www 11348: # ------------------------------------------------- Get the title of a resource
11349:
11350: sub gettitle {
11351: my $urlsymb=shift;
11352: my $symb=&symbread($urlsymb);
1.534 albertel 11353: if ($symb) {
1.620 albertel 11354: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11355: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11356: if (defined($cached)) {
11357: return $result;
11358: }
1.534 albertel 11359: my ($map,$resid,$url)=&decode_symb($symb);
11360: my $title='';
1.907 albertel 11361: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11362: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11363: } else {
11364: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11365: &GDBM_READER(),0640)) {
11366: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11367: $title=$bighash{'title_'.$mapid.'.'.$resid};
11368: untie(%bighash);
11369: }
1.534 albertel 11370: }
11371: $title=~s/\&colon\;/\:/gs;
11372: if ($title) {
1.1159 www 11373: # Remember both $symb and $title for dynamic metadata
11374: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11375: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11376: # Cache this title and then return it
1.599 albertel 11377: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11378: }
11379: $urlsymb=$url;
11380: }
11381: my $title=&metadata($urlsymb,'title');
11382: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11383: return $title;
1.301 www 11384: }
1.613 albertel 11385:
1.614 albertel 11386: sub get_slot {
11387: my ($which,$cnum,$cdom)=@_;
11388: if (!$cnum || !$cdom) {
1.790 albertel 11389: (undef,my $courseid)=&whichuser();
1.620 albertel 11390: $cdom=$env{'course.'.$courseid.'.domain'};
11391: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11392: }
1.703 albertel 11393: my $key=join("\0",'slots',$cdom,$cnum,$which);
11394: my %slotinfo;
11395: if (exists($remembered{$key})) {
11396: $slotinfo{$which} = $remembered{$key};
11397: } else {
11398: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11399: &Apache::lonhomework::showhash(%slotinfo);
11400: my ($tmp)=keys(%slotinfo);
11401: if ($tmp=~/^error:/) { return (); }
11402: $remembered{$key} = $slotinfo{$which};
11403: }
1.616 albertel 11404: if (ref($slotinfo{$which}) eq 'HASH') {
11405: return %{$slotinfo{$which}};
11406: }
11407: return $slotinfo{$which};
1.614 albertel 11408: }
1.1150 raeburn 11409:
11410: sub get_reservable_slots {
11411: my ($cnum,$cdom,$uname,$udom) = @_;
11412: my $now = time;
11413: my $reservable_info;
11414: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11415: if (exists($remembered{$key})) {
11416: $reservable_info = $remembered{$key};
11417: } else {
11418: my %resv;
11419: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11420: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11421: $reservable_info = \%resv;
11422: $remembered{$key} = $reservable_info;
11423: }
11424: return $reservable_info;
11425: }
11426:
11427: sub get_course_slots {
11428: my ($cnum,$cdom) = @_;
11429: my $hashid=$cnum.':'.$cdom;
11430: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11431: if (defined($cached)) {
11432: if (ref($result) eq 'HASH') {
11433: return %{$result};
11434: }
11435: } else {
11436: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11437: my ($tmp) = keys(%slots);
11438: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11439: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11440: return %slots;
11441: }
11442: }
11443: return;
11444: }
11445:
11446: sub devalidate_slots_cache {
11447: my ($cnum,$cdom)=@_;
11448: my $hashid=$cnum.':'.$cdom;
11449: &devalidate_cache_new('allslots',$hashid);
11450: }
11451:
1.1172.2.8 raeburn 11452: sub get_coursechange {
11453: my ($cdom,$cnum) = @_;
11454: if ($cdom eq '' || $cnum eq '') {
11455: return unless ($env{'request.course.id'});
11456: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11457: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11458: }
11459: my $hashid=$cdom.'_'.$cnum;
11460: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11461: if ((defined($cached)) && ($change ne '')) {
11462: return $change;
11463: } else {
11464: my %crshash;
11465: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11466: if ($crshash{'internal.contentchange'} eq '') {
11467: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11468: if ($change eq '') {
11469: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11470: $change = $crshash{'internal.created'};
11471: }
11472: } else {
11473: $change = $crshash{'internal.contentchange'};
11474: }
11475: my $cachetime = 600;
11476: &do_cache_new('crschange',$hashid,$change,$cachetime);
11477: }
11478: return $change;
11479: }
11480:
11481: sub devalidate_coursechange_cache {
11482: my ($cnum,$cdom)=@_;
11483: my $hashid=$cnum.':'.$cdom;
11484: &devalidate_cache_new('crschange',$hashid);
11485: }
11486:
1.31 www 11487: # ------------------------------------------------- Update symbolic store links
11488:
11489: sub symblist {
11490: my ($mapname,%newhash)=@_;
1.438 www 11491: $mapname=&deversion(&declutter($mapname));
1.31 www 11492: my %hash;
1.620 albertel 11493: if (($env{'request.course.fn'}) && (%newhash)) {
11494: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11495: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11496: foreach my $url (keys(%newhash)) {
1.711 albertel 11497: next if ($url eq 'last_known'
11498: && $env{'form.no_update_last_known'});
11499: $hash{declutter($url)}=&encode_symb($mapname,
11500: $newhash{$url}->[1],
11501: $newhash{$url}->[0]);
1.191 harris41 11502: }
1.31 www 11503: if (untie(%hash)) {
11504: return 'ok';
11505: }
11506: }
11507: }
11508: return 'error';
1.212 www 11509: }
11510:
11511: # --------------------------------------------------------------- Verify a symb
11512:
11513: sub symbverify {
1.1172.2.11 raeburn 11514: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11515: my $thisfn=$thisurl;
1.439 www 11516: $thisfn=&declutter($thisfn);
1.215 www 11517: # direct jump to resource in page or to a sequence - will construct own symbs
11518: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11519: # check URL part
1.409 www 11520: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11521:
1.431 www 11522: unless ($url eq $thisfn) { return 0; }
1.213 www 11523:
1.216 www 11524: $symb=&symbclean($symb);
1.510 www 11525: $thisurl=&deversion($thisurl);
1.439 www 11526: $thisfn=&deversion($thisfn);
1.213 www 11527:
11528: my %bighash;
11529: my $okay=0;
1.431 www 11530:
1.620 albertel 11531: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11532: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11533: my $noclutter;
1.1032 raeburn 11534: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11535: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11536: if ($map =~ m{^uploaded/.+\.page$}) {
11537: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11538: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11539: $noclutter = 1;
11540: }
11541: }
11542: my $ids;
11543: if ($noclutter) {
11544: $ids=$bighash{'ids_'.$thisurl};
11545: } else {
11546: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11547: }
1.1102 raeburn 11548: unless ($ids) {
1.1172.2.13 raeburn 11549: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11550: $ids=$bighash{$idkey};
1.216 www 11551: }
11552: if ($ids) {
11553: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11554: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11555: $symb =~ s/\?.+$//;
11556: }
1.800 albertel 11557: foreach my $id (split(/\,/,$ids)) {
11558: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11559: if (
11560: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11561: eq $symb) {
1.1172.2.11 raeburn 11562: if (ref($encstate)) {
11563: $$encstate = $bighash{'encrypted_'.$id};
11564: }
1.1172.2.13 raeburn 11565: if (($env{'request.role.adv'}) ||
11566: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11567: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11568: $okay=1;
11569: last;
11570: }
11571: }
11572: }
1.216 www 11573: }
1.213 www 11574: untie(%bighash);
11575: }
11576: return $okay;
1.31 www 11577: }
11578:
1.210 www 11579: # --------------------------------------------------------------- Clean-up symb
11580:
11581: sub symbclean {
11582: my $symb=shift;
1.568 albertel 11583: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11584: # remove version from map
11585: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11586:
1.210 www 11587: # remove version from URL
11588: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11589:
1.507 www 11590: # remove wrapper
11591:
1.510 www 11592: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11593: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11594: return $symb;
1.409 www 11595: }
11596:
11597: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11598:
11599: sub encode_symb {
11600: my ($map,$resid,$url)=@_;
11601: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11602: }
1.409 www 11603:
11604: sub decode_symb {
1.568 albertel 11605: my $symb=shift;
11606: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11607: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11608: return (&fixversion($map),$resid,&fixversion($url));
11609: }
11610:
11611: sub fixversion {
11612: my $fn=shift;
1.609 banghart 11613: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11614: my %bighash;
11615: my $uri=&clutter($fn);
1.620 albertel 11616: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11617: # is this cached?
1.599 albertel 11618: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11619: if (defined($cached)) { return $result; }
11620: # unfortunately not cached, or expired
1.620 albertel 11621: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11622: &GDBM_READER(),0640)) {
11623: if ($bighash{'version_'.$uri}) {
11624: my $version=$bighash{'version_'.$uri};
1.444 www 11625: unless (($version eq 'mostrecent') ||
11626: ($version==&getversion($uri))) {
1.440 www 11627: $uri=~s/\.(\w+)$/\.$version\.$1/;
11628: }
11629: }
11630: untie %bighash;
1.413 www 11631: }
1.599 albertel 11632: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11633: }
11634:
11635: sub deversion {
11636: my $url=shift;
11637: $url=~s/\.\d+\.(\w+)$/\.$1/;
11638: return $url;
1.210 www 11639: }
11640:
1.31 www 11641: # ------------------------------------------------------ Return symb list entry
11642:
11643: sub symbread {
1.1172.2.66 raeburn 11644: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11645: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11646: if (defined($env{$cache_str})) {
11647: if ($ignorecachednull) {
11648: return $env{$cache_str} unless ($env{$cache_str} eq '');
11649: } else {
11650: return $env{$cache_str};
11651: }
11652: }
1.242 www 11653: # no filename provided? try from environment
1.1172.2.54 raeburn 11654: unless ($thisfn) {
1.620 albertel 11655: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11656: return $env{$cache_str}=&symbclean($env{'request.symb'});
11657: }
11658: $thisfn=$env{'request.filename'};
1.44 www 11659: }
1.569 albertel 11660: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11661: # is that filename actually a symb? Verify, clean, and return
11662: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11663: if (&symbverify($thisfn,$1)) {
1.620 albertel 11664: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11665: }
1.242 www 11666: }
1.44 www 11667: $thisfn=declutter($thisfn);
1.31 www 11668: my %hash;
1.37 www 11669: my %bighash;
11670: my $syval='';
1.620 albertel 11671: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11672: my $targetfn = $thisfn;
1.609 banghart 11673: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11674: $targetfn = 'adm/wrapper/'.$thisfn;
11675: }
1.687 albertel 11676: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11677: $targetfn=$1;
11678: }
1.620 albertel 11679: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11680: &GDBM_READER(),0640)) {
1.481 raeburn 11681: $syval=$hash{$targetfn};
1.37 www 11682: untie(%hash);
11683: }
11684: # ---------------------------------------------------------- There was an entry
11685: if ($syval) {
1.601 albertel 11686: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11687: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11688: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11689: #return $env{$cache_str}='';
1.601 albertel 11690: #}
11691: #$syval.=$1;
11692: #}
1.37 www 11693: } else {
11694: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11695: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11696: &GDBM_READER(),0640)) {
1.37 www 11697: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11698: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11699: unless ($ids) {
11700: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11701: }
11702: unless ($ids) {
11703: # alias?
11704: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11705: }
1.37 www 11706: if ($ids) {
11707: # ------------------------------------------------------------------- Has ID(s)
11708: my @possibilities=split(/\,/,$ids);
1.39 www 11709: if ($#possibilities==0) {
11710: # ----------------------------------------------- There is only one possibility
1.37 www 11711: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11712: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11713: $resid,$thisfn);
1.1172.2.66 raeburn 11714: if (ref($possibles) eq 'HASH') {
11715: $possibles->{$syval} = 1;
11716: }
11717: if ($checkforblock) {
11718: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11719: if (@blockers) {
11720: $syval = '';
11721: return;
11722: }
11723: }
11724: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11725: # ------------------------------------------ There is more than one possibility
11726: my $realpossible=0;
1.800 albertel 11727: foreach my $id (@possibilities) {
11728: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11729: my $canaccess;
11730: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11731: $canaccess = 1;
11732: } else {
11733: $canaccess = &allowed('bre',$file);
11734: }
11735: if ($canaccess) {
11736: my ($mapid,$resid)=split(/\./,$id);
11737: if ($bighash{'map_type_'.$mapid} ne 'page') {
11738: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11739: $resid,$thisfn);
11740: if (ref($possibles) eq 'HASH') {
11741: $possibles->{$syval} = 1;
11742: }
11743: if ($checkforblock) {
11744: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11745: unless (@blockers > 0) {
11746: $syval = $poss_syval;
11747: $realpossible++;
11748: }
11749: } else {
11750: $syval = $poss_syval;
11751: $realpossible++;
11752: }
11753: }
1.39 www 11754: }
1.191 harris41 11755: }
1.39 www 11756: if ($realpossible!=1) { $syval=''; }
1.249 www 11757: } else {
11758: $syval='';
1.37 www 11759: }
11760: }
1.1172.2.66 raeburn 11761: untie(%bighash);
1.481 raeburn 11762: }
1.31 www 11763: }
1.62 www 11764: if ($syval) {
1.620 albertel 11765: return $env{$cache_str}=$syval;
1.62 www 11766: }
1.31 www 11767: }
1.949 raeburn 11768: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11769: return $env{$cache_str}='';
1.31 www 11770: }
11771:
11772: # ---------------------------------------------------------- Return random seed
11773:
1.32 www 11774: sub numval {
11775: my $txt=shift;
11776: $txt=~tr/A-J/0-9/;
11777: $txt=~tr/a-j/0-9/;
11778: $txt=~tr/K-T/0-9/;
11779: $txt=~tr/k-t/0-9/;
11780: $txt=~tr/U-Z/0-5/;
11781: $txt=~tr/u-z/0-5/;
11782: $txt=~s/\D//g;
1.564 albertel 11783: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11784: return int($txt);
1.368 albertel 11785: }
11786:
1.484 albertel 11787: sub numval2 {
11788: my $txt=shift;
11789: $txt=~tr/A-J/0-9/;
11790: $txt=~tr/a-j/0-9/;
11791: $txt=~tr/K-T/0-9/;
11792: $txt=~tr/k-t/0-9/;
11793: $txt=~tr/U-Z/0-5/;
11794: $txt=~tr/u-z/0-5/;
11795: $txt=~s/\D//g;
11796: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11797: my $total;
11798: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11799: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11800: return int($total);
11801: }
11802:
1.575 albertel 11803: sub numval3 {
11804: use integer;
11805: my $txt=shift;
11806: $txt=~tr/A-J/0-9/;
11807: $txt=~tr/a-j/0-9/;
11808: $txt=~tr/K-T/0-9/;
11809: $txt=~tr/k-t/0-9/;
11810: $txt=~tr/U-Z/0-5/;
11811: $txt=~tr/u-z/0-5/;
11812: $txt=~s/\D//g;
11813: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11814: my $total;
11815: foreach my $val (@txts) { $total+=$val; }
11816: if ($_64bit) { $total=(($total<<32)>>32); }
11817: return $total;
11818: }
11819:
1.675 albertel 11820: sub digest {
11821: my ($data)=@_;
11822: my $digest=&Digest::MD5::md5($data);
11823: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11824: my ($e,$f);
11825: {
11826: use integer;
11827: $e=($a+$b);
11828: $f=($c+$d);
11829: if ($_64bit) {
11830: $e=(($e<<32)>>32);
11831: $f=(($f<<32)>>32);
11832: }
11833: }
11834: if (wantarray) {
11835: return ($e,$f);
11836: } else {
11837: my $g;
11838: {
11839: use integer;
11840: $g=($e+$f);
11841: if ($_64bit) {
11842: $g=(($g<<32)>>32);
11843: }
11844: }
11845: return $g;
11846: }
11847: }
11848:
1.368 albertel 11849: sub latest_rnd_algorithm_id {
1.675 albertel 11850: return '64bit5';
1.366 albertel 11851: }
1.32 www 11852:
1.503 albertel 11853: sub get_rand_alg {
11854: my ($courseid)=@_;
1.790 albertel 11855: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11856: if ($courseid) {
1.620 albertel 11857: return $env{"course.$courseid.rndseed"};
1.503 albertel 11858: }
11859: return &latest_rnd_algorithm_id();
11860: }
11861:
1.562 albertel 11862: sub validCODE {
11863: my ($CODE)=@_;
11864: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11865: return 0;
11866: }
11867:
1.491 albertel 11868: sub getCODE {
1.620 albertel 11869: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11870: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11871: defined($Apache::lonhomework::parsing_a_task) ) &&
11872: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11873: return $Apache::lonhomework::history{'resource.CODE'};
11874: }
11875: return undef;
11876: }
1.1133 foxr 11877: #
11878: # Determines the random seed for a specific context:
11879: #
11880: # parameters:
11881: # symb - in course context the symb for the seed.
11882: # course_id - The course id of the form domain_coursenum.
11883: # domain - Domain for the user.
11884: # course - Course for the user.
11885: # cenv - environment of the course.
11886: #
11887: # NOTE:
11888: # All parameters are picked out of the environment if missing
11889: # or not defined.
11890: # If a symb cannot be determined the current time is used instead.
11891: #
11892: # For a given well defined symb, courside, domain, username,
11893: # and course environment, the seed is reproducible.
11894: #
1.31 www 11895: sub rndseed {
1.1133 foxr 11896: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11897: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11898: if (!defined($symb)) {
1.366 albertel 11899: unless ($symb=$wsymb) { return time; }
11900: }
1.1146 foxr 11901: if (!defined $courseid) {
11902: $courseid=$wcourseid;
11903: }
11904: if (!defined $domain) { $domain=$wdomain; }
11905: if (!defined $username) { $username=$wusername }
1.1133 foxr 11906:
11907: my $which;
11908: if (defined($cenv->{'rndseed'})) {
11909: $which = $cenv->{'rndseed'};
11910: } else {
11911: $which =&get_rand_alg($courseid);
11912: }
1.491 albertel 11913: if (defined(&getCODE())) {
1.675 albertel 11914: if ($which eq '64bit5') {
11915: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11916: } elsif ($which eq '64bit4') {
1.575 albertel 11917: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11918: } else {
11919: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11920: }
1.675 albertel 11921: } elsif ($which eq '64bit5') {
11922: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11923: } elsif ($which eq '64bit4') {
11924: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11925: } elsif ($which eq '64bit3') {
11926: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11927: } elsif ($which eq '64bit2') {
11928: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11929: } elsif ($which eq '64bit') {
11930: return &rndseed_64bit($symb,$courseid,$domain,$username);
11931: }
11932: return &rndseed_32bit($symb,$courseid,$domain,$username);
11933: }
11934:
11935: sub rndseed_32bit {
11936: my ($symb,$courseid,$domain,$username)=@_;
11937: {
11938: use integer;
11939: my $symbchck=unpack("%32C*",$symb) << 27;
11940: my $symbseed=numval($symb) << 22;
11941: my $namechck=unpack("%32C*",$username) << 17;
11942: my $nameseed=numval($username) << 12;
11943: my $domainseed=unpack("%32C*",$domain) << 7;
11944: my $courseseed=unpack("%32C*",$courseid);
11945: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11946: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11947: #&logthis("rndseed :$num:$symb");
1.564 albertel 11948: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11949: return $num;
11950: }
11951: }
11952:
11953: sub rndseed_64bit {
11954: my ($symb,$courseid,$domain,$username)=@_;
11955: {
11956: use integer;
11957: my $symbchck=unpack("%32S*",$symb) << 21;
11958: my $symbseed=numval($symb) << 10;
11959: my $namechck=unpack("%32S*",$username);
11960:
11961: my $nameseed=numval($username) << 21;
11962: my $domainseed=unpack("%32S*",$domain) << 10;
11963: my $courseseed=unpack("%32S*",$courseid);
11964:
11965: my $num1=$symbchck+$symbseed+$namechck;
11966: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11967: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11968: #&logthis("rndseed :$num:$symb");
1.564 albertel 11969: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11970: return "$num1,$num2";
1.155 albertel 11971: }
1.366 albertel 11972: }
11973:
1.443 albertel 11974: sub rndseed_64bit2 {
11975: my ($symb,$courseid,$domain,$username)=@_;
11976: {
11977: use integer;
11978: # strings need to be an even # of cahracters long, it it is odd the
11979: # last characters gets thrown away
11980: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11981: my $symbseed=numval($symb) << 10;
11982: my $namechck=unpack("%32S*",$username.' ');
11983:
11984: my $nameseed=numval($username) << 21;
1.501 albertel 11985: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11986: my $courseseed=unpack("%32S*",$courseid.' ');
11987:
11988: my $num1=$symbchck+$symbseed+$namechck;
11989: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11990: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11991: #&logthis("rndseed :$num:$symb");
1.803 albertel 11992: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11993: return "$num1,$num2";
11994: }
11995: }
11996:
11997: sub rndseed_64bit3 {
11998: my ($symb,$courseid,$domain,$username)=@_;
11999: {
12000: use integer;
12001: # strings need to be an even # of cahracters long, it it is odd the
12002: # last characters gets thrown away
12003: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12004: my $symbseed=numval2($symb) << 10;
12005: my $namechck=unpack("%32S*",$username.' ');
12006:
12007: my $nameseed=numval2($username) << 21;
1.443 albertel 12008: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12009: my $courseseed=unpack("%32S*",$courseid.' ');
12010:
12011: my $num1=$symbchck+$symbseed+$namechck;
12012: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12013: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12014: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12015: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12016:
1.503 albertel 12017: return "$num1:$num2";
1.443 albertel 12018: }
12019: }
12020:
1.575 albertel 12021: sub rndseed_64bit4 {
12022: my ($symb,$courseid,$domain,$username)=@_;
12023: {
12024: use integer;
12025: # strings need to be an even # of cahracters long, it it is odd the
12026: # last characters gets thrown away
12027: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12028: my $symbseed=numval3($symb) << 10;
12029: my $namechck=unpack("%32S*",$username.' ');
12030:
12031: my $nameseed=numval3($username) << 21;
12032: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12033: my $courseseed=unpack("%32S*",$courseid.' ');
12034:
12035: my $num1=$symbchck+$symbseed+$namechck;
12036: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12037: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12038: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12039: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12040:
1.575 albertel 12041: return "$num1:$num2";
12042: }
12043: }
12044:
1.675 albertel 12045: sub rndseed_64bit5 {
12046: my ($symb,$courseid,$domain,$username)=@_;
12047: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12048: return "$num1:$num2";
12049: }
12050:
1.366 albertel 12051: sub rndseed_CODE_64bit {
12052: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12053: {
1.366 albertel 12054: use integer;
1.443 albertel 12055: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12056: my $symbseed=numval2($symb);
1.491 albertel 12057: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12058: my $CODEseed=numval(&getCODE());
1.443 albertel 12059: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12060: my $num1=$symbseed+$CODEchck;
12061: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12062: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12063: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12064: if ($_64bit) { $num1=(($num1<<32)>>32); }
12065: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12066: return "$num1:$num2";
1.366 albertel 12067: }
12068: }
12069:
1.575 albertel 12070: sub rndseed_CODE_64bit4 {
12071: my ($symb,$courseid,$domain,$username)=@_;
12072: {
12073: use integer;
12074: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12075: my $symbseed=numval3($symb);
12076: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12077: my $CODEseed=numval3(&getCODE());
12078: my $courseseed=unpack("%32S*",$courseid.' ');
12079: my $num1=$symbseed+$CODEchck;
12080: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12081: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12082: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12083: if ($_64bit) { $num1=(($num1<<32)>>32); }
12084: if ($_64bit) { $num2=(($num2<<32)>>32); }
12085: return "$num1:$num2";
12086: }
12087: }
12088:
1.675 albertel 12089: sub rndseed_CODE_64bit5 {
12090: my ($symb,$courseid,$domain,$username)=@_;
12091: my $code = &getCODE();
12092: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12093: return "$num1:$num2";
12094: }
12095:
1.366 albertel 12096: sub setup_random_from_rndseed {
12097: my ($rndseed)=@_;
1.503 albertel 12098: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12099: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12100: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12101: &Math::Random::random_set_seed_from_phrase($rndseed);
12102: } else {
12103: &Math::Random::random_set_seed($num1,$num2);
12104: }
1.366 albertel 12105: } else {
12106: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12107: }
1.36 albertel 12108: }
12109:
1.474 albertel 12110: sub latest_receipt_algorithm_id {
1.835 albertel 12111: return 'receipt3';
1.474 albertel 12112: }
12113:
1.480 www 12114: sub recunique {
12115: my $fucourseid=shift;
12116: my $unique;
1.835 albertel 12117: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12118: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12119: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12120: } else {
12121: $unique=$perlvar{'lonReceipt'};
12122: }
12123: return unpack("%32C*",$unique);
12124: }
12125:
12126: sub recprefix {
12127: my $fucourseid=shift;
12128: my $prefix;
1.835 albertel 12129: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12130: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12131: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12132: } else {
12133: $prefix=$perlvar{'lonHostID'};
12134: }
12135: return unpack("%32C*",$prefix);
12136: }
12137:
1.76 www 12138: sub ireceipt {
1.474 albertel 12139: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12140:
12141: my $return =&recprefix($fucourseid).'-';
12142:
12143: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12144: $env{'request.state'} eq 'construct') {
12145: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12146: return $return;
12147: }
12148:
1.76 www 12149: my $cuname=unpack("%32C*",$funame);
12150: my $cudom=unpack("%32C*",$fudom);
12151: my $cucourseid=unpack("%32C*",$fucourseid);
12152: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12153: my $cunique=&recunique($fucourseid);
1.474 albertel 12154: my $cpart=unpack("%32S*",$part);
1.835 albertel 12155: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12156:
1.790 albertel 12157: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12158:
12159: $return.= ($cunique%$cuname+
12160: $cunique%$cudom+
12161: $cusymb%$cuname+
12162: $cusymb%$cudom+
12163: $cucourseid%$cuname+
12164: $cucourseid%$cudom+
12165: $cpart%$cuname+
12166: $cpart%$cudom);
12167: } else {
12168: $return.= ($cunique%$cuname+
12169: $cunique%$cudom+
12170: $cusymb%$cuname+
12171: $cusymb%$cudom+
12172: $cucourseid%$cuname+
12173: $cucourseid%$cudom);
12174: }
12175: return $return;
1.76 www 12176: }
12177:
12178: sub receipt {
1.474 albertel 12179: my ($part)=@_;
1.790 albertel 12180: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12181: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12182: }
1.260 ng 12183:
1.790 albertel 12184: sub whichuser {
12185: my ($passedsymb)=@_;
12186: my ($symb,$courseid,$domain,$name,$publicuser);
12187: if (defined($env{'form.grade_symb'})) {
12188: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12189: my $allowed=&allowed('vgr',$tmp_courseid);
12190: if (!$allowed &&
12191: exists($env{'request.course.sec'}) &&
12192: $env{'request.course.sec'} !~ /^\s*$/) {
12193: $allowed=&allowed('vgr',$tmp_courseid.
12194: '/'.$env{'request.course.sec'});
12195: }
12196: if ($allowed) {
12197: ($symb)=&get_env_multiple('form.grade_symb');
12198: $courseid=$tmp_courseid;
12199: ($domain)=&get_env_multiple('form.grade_domain');
12200: ($name)=&get_env_multiple('form.grade_username');
12201: return ($symb,$courseid,$domain,$name,$publicuser);
12202: }
12203: }
12204: if (!$passedsymb) {
12205: $symb=&symbread();
12206: } else {
12207: $symb=$passedsymb;
12208: }
12209: $courseid=$env{'request.course.id'};
12210: $domain=$env{'user.domain'};
12211: $name=$env{'user.name'};
12212: if ($name eq 'public' && $domain eq 'public') {
12213: if (!defined($env{'form.username'})) {
12214: $env{'form.username'}.=time.rand(10000000);
12215: }
12216: $name.=$env{'form.username'};
12217: }
12218: return ($symb,$courseid,$domain,$name,$publicuser);
12219:
12220: }
12221:
1.36 albertel 12222: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12223: # returns either the contents of the file or
12224: # -1 if the file doesn't exist
1.481 raeburn 12225: #
12226: # if the target is a file that was uploaded via DOCS,
12227: # a check will be made to see if a current copy exists on the local server,
12228: # if it does this will be served, otherwise a copy will be retrieved from
12229: # the home server for the course and stored in /home/httpd/html/userfiles on
12230: # the local server.
1.472 albertel 12231:
1.36 albertel 12232: sub getfile {
1.538 albertel 12233: my ($file) = @_;
1.609 banghart 12234: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12235: &repcopy($file);
12236: return &readfile($file);
12237: }
12238:
12239: sub repcopy_userfile {
12240: my ($file)=@_;
1.1142 raeburn 12241: my $londocroot = $perlvar{'lonDocRoot'};
12242: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12243: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12244: my ($cdom,$cnum,$filename) =
1.811 albertel 12245: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12246: my $uri="/uploaded/$cdom/$cnum/$filename";
12247: if (-e "$file") {
1.828 www 12248: # we already have a local copy, check it out
1.538 albertel 12249: my @fileinfo = stat($file);
1.828 www 12250: my $rtncode;
12251: my $info;
1.538 albertel 12252: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12253: if ($lwpresp ne 'ok') {
1.828 www 12254: # there is no such file anymore, even though we had a local copy
1.482 albertel 12255: if ($rtncode eq '404') {
1.538 albertel 12256: unlink($file);
1.482 albertel 12257: }
12258: return -1;
12259: }
12260: if ($info < $fileinfo[9]) {
1.828 www 12261: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12262: return 'ok';
1.828 www 12263: } else {
12264: # the file is outdated, get rid of it
12265: unlink($file);
1.482 albertel 12266: }
1.828 www 12267: }
12268: # one way or the other, at this point, we don't have the file
12269: # construct the correct path for the file
12270: my @parts = ($cdom,$cnum);
12271: if ($filename =~ m|^(.+)/[^/]+$|) {
12272: push @parts, split(/\//,$1);
12273: }
12274: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12275: foreach my $part (@parts) {
12276: $path .= '/'.$part;
12277: if (!-e $path) {
12278: mkdir($path,0770);
1.482 albertel 12279: }
12280: }
1.828 www 12281: # now the path exists for sure
12282: # get a user agent
12283: my $ua=new LWP::UserAgent;
12284: my $transferfile=$file.'.in.transfer';
12285: # FIXME: this should flock
12286: if (-e $transferfile) { return 'ok'; }
12287: my $request;
12288: $uri=~s/^\///;
1.980 raeburn 12289: my $homeserver = &homeserver($cnum,$cdom);
12290: my $protocol = $protocol{$homeserver};
12291: $protocol = 'http' if ($protocol ne 'https');
12292: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12293: my $response=$ua->request($request,$transferfile);
12294: # did it work?
12295: if ($response->is_error()) {
12296: unlink($transferfile);
12297: &logthis("Userfile repcopy failed for $uri");
12298: return -1;
12299: }
12300: # worked, rename the transfer file
12301: rename($transferfile,$file);
1.607 raeburn 12302: return 'ok';
1.481 raeburn 12303: }
12304:
1.517 albertel 12305: sub tokenwrapper {
12306: my $uri=shift;
1.980 raeburn 12307: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12308: $uri=~s|^/||;
1.620 albertel 12309: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12310: my $token=$1;
1.552 albertel 12311: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12312: if ($udom && $uname && $file) {
12313: $file=~s|(\?\.*)*$||;
1.949 raeburn 12314: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12315: my $homeserver = &homeserver($uname,$udom);
12316: my $protocol = $protocol{$homeserver};
12317: $protocol = 'http' if ($protocol ne 'https');
12318: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12319: (($uri=~/\?/)?'&':'?').'token='.$token.
12320: '&tokenissued='.$perlvar{'lonHostID'};
12321: } else {
12322: return '/adm/notfound.html';
12323: }
12324: }
12325:
1.828 www 12326: # call with reqtype HEAD: get last modification time
12327: # call with reqtype GET: get the file contents
12328: # Do not call this with reqtype GET for large files! It loads everything into memory
12329: #
1.481 raeburn 12330: sub getuploaded {
12331: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12332: $uri=~s/^\///;
1.980 raeburn 12333: my $homeserver = &homeserver($cnum,$cdom);
12334: my $protocol = $protocol{$homeserver};
12335: $protocol = 'http' if ($protocol ne 'https');
12336: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12337: my $ua=new LWP::UserAgent;
12338: my $request=new HTTP::Request($reqtype,$uri);
12339: my $response=$ua->request($request);
12340: $$rtncode = $response->code;
1.482 albertel 12341: if (! $response->is_success()) {
12342: return 'failed';
12343: }
12344: if ($reqtype eq 'HEAD') {
1.486 www 12345: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12346: } elsif ($reqtype eq 'GET') {
12347: $$info = $response->content;
1.472 albertel 12348: }
1.482 albertel 12349: return 'ok';
1.36 albertel 12350: }
12351:
1.481 raeburn 12352: sub readfile {
12353: my $file = shift;
12354: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12355: my $fh;
1.1172.2.96! raeburn 12356: open($fh,"<",$file);
1.481 raeburn 12357: my $a='';
1.800 albertel 12358: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12359: return $a;
12360: }
12361:
1.36 albertel 12362: sub filelocation {
1.590 banghart 12363: my ($dir,$file) = @_;
12364: my $location;
12365: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12366:
12367: if ($file =~ m-^/adm/-) {
12368: $file=~s-^/adm/wrapper/-/-;
12369: $file=~s-^/adm/coursedocs/showdoc/-/-;
12370: }
1.882 albertel 12371:
1.1139 www 12372: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12373: $location = $file;
1.609 banghart 12374: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12375: my ($udom,$uname,$filename)=
1.811 albertel 12376: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12377: my $home=&homeserver($uname,$udom);
12378: my $is_me=0;
12379: my @ids=¤t_machine_ids();
12380: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12381: if ($is_me) {
1.1117 foxr 12382: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12383: } else {
12384: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12385: $udom.'/'.$uname.'/'.$filename;
12386: }
1.882 albertel 12387: } elsif ($file =~ m-^/adm/-) {
12388: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12389: } else {
12390: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12391: $file=~s:^/(res|priv)/:/:;
12392: my $space=$1;
1.590 banghart 12393: if ( !( $file =~ m:^/:) ) {
12394: $location = $dir. '/'.$file;
12395: } else {
1.1142 raeburn 12396: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12397: }
1.59 albertel 12398: }
1.590 banghart 12399: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12400: while ($location=~m{/\.\./}) {
12401: if ($location =~ m{/[^/]+/\.\./}) {
12402: $location=~ s{/[^/]+/\.\./}{/}g;
12403: } else {
12404: $location=~ s{/\.\./}{/}g;
12405: }
12406: } #remove dir/..
1.590 banghart 12407: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12408: return $location;
1.46 www 12409: }
1.36 albertel 12410:
1.46 www 12411: sub hreflocation {
12412: my ($dir,$file)=@_;
1.980 raeburn 12413: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12414: $file=filelocation($dir,$file);
1.700 albertel 12415: } elsif ($file=~m-^/adm/-) {
12416: $file=~s-^/adm/wrapper/-/-;
12417: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12418: }
12419: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12420: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12421: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12422: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12423: {/uploaded/$1/$2/}x;
1.46 www 12424: }
1.913 albertel 12425: if ($file=~ m{^/userfiles/}) {
12426: $file =~ s{^/userfiles/}{/uploaded/};
12427: }
1.462 albertel 12428: return $file;
1.465 albertel 12429: }
12430:
1.1139 www 12431:
12432:
12433:
12434:
1.465 albertel 12435: sub current_machine_domains {
1.853 albertel 12436: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12437: }
12438:
12439: sub machine_domains {
12440: my ($hostname) = @_;
1.465 albertel 12441: my @domains;
1.838 albertel 12442: my %hostname = &all_hostnames();
1.465 albertel 12443: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12444: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12445: if ($hostname eq $name) {
1.844 albertel 12446: push(@domains,&host_domain($id));
1.465 albertel 12447: }
12448: }
12449: return @domains;
12450: }
12451:
12452: sub current_machine_ids {
1.853 albertel 12453: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12454: }
12455:
12456: sub machine_ids {
12457: my ($hostname) = @_;
12458: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12459: my @ids;
1.888 albertel 12460: my %name_to_host = &all_names();
1.889 albertel 12461: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12462: return @{ $name_to_host{$hostname} };
12463: }
12464: return;
1.31 www 12465: }
12466:
1.824 raeburn 12467: sub additional_machine_domains {
12468: my @domains;
1.1172.2.96! raeburn 12469: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 12470: while( my $line = <$fh>) {
12471: $line =~ s/\s//g;
12472: push(@domains,$line);
12473: }
12474: return @domains;
12475: }
12476:
12477: sub default_login_domain {
12478: my $domain = $perlvar{'lonDefDomain'};
12479: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12480: foreach my $posdom (¤t_machine_domains(),
12481: &additional_machine_domains()) {
12482: if (lc($posdom) eq lc($testdomain)) {
12483: $domain=$posdom;
12484: last;
12485: }
12486: }
12487: return $domain;
12488: }
12489:
1.31 www 12490: # ------------------------------------------------------------- Declutters URLs
12491:
12492: sub declutter {
12493: my $thisfn=shift;
1.569 albertel 12494: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12495: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12496: $thisfn=~s{^/home/httpd/html}{};
12497: }
1.31 www 12498: $thisfn=~s/^\///;
1.697 albertel 12499: $thisfn=~s|^adm/wrapper/||;
12500: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12501: $thisfn=~s/^res\///;
1.1172 bisitz 12502: $thisfn=~s/^priv\///;
1.1032 raeburn 12503: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12504: $thisfn=~s/\?.+$//;
12505: }
1.268 www 12506: return $thisfn;
12507: }
12508:
12509: # ------------------------------------------------------------- Clutter up URLs
12510:
12511: sub clutter {
12512: my $thisfn='/'.&declutter(shift);
1.887 albertel 12513: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12514: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12515: $thisfn='/res'.$thisfn;
12516: }
1.1031 raeburn 12517: if ($thisfn !~m|^/adm|) {
12518: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12519: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12520: } else {
12521: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12522: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12523: if ($embstyle eq 'ssi'
12524: || ($embstyle eq 'hdn')
12525: || ($embstyle eq 'rat')
12526: || ($embstyle eq 'prv')
12527: || ($embstyle eq 'ign')) {
12528: #do nothing with these
12529: } elsif (($embstyle eq 'img')
1.695 albertel 12530: || ($embstyle eq 'emb')
12531: || ($embstyle eq 'wrp')) {
12532: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12533: } elsif ($embstyle eq 'unk'
12534: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12535: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12536: } else {
1.718 www 12537: # &logthis("Got a blank emb style");
1.695 albertel 12538: }
1.694 albertel 12539: }
12540: }
1.31 www 12541: return $thisfn;
1.12 www 12542: }
12543:
1.787 albertel 12544: sub clutter_with_no_wrapper {
12545: my $uri = &clutter(shift);
12546: if ($uri =~ m-^/adm/-) {
12547: $uri =~ s-^/adm/wrapper/-/-;
12548: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12549: }
12550: return $uri;
12551: }
12552:
1.557 albertel 12553: sub freeze_escape {
12554: my ($value)=@_;
12555: if (ref($value)) {
12556: $value=&nfreeze($value);
12557: return '__FROZEN__'.&escape($value);
12558: }
12559: return &escape($value);
12560: }
12561:
1.11 www 12562:
1.557 albertel 12563: sub thaw_unescape {
12564: my ($value)=@_;
12565: if ($value =~ /^__FROZEN__/) {
12566: substr($value,0,10,undef);
12567: $value=&unescape($value);
12568: return &thaw($value);
12569: }
12570: return &unescape($value);
12571: }
12572:
1.436 albertel 12573: sub correct_line_ends {
12574: my ($result)=@_;
12575: $$result =~s/\r\n/\n/mg;
12576: $$result =~s/\r/\n/mg;
1.415 albertel 12577: }
1.1 albertel 12578: # ================================================================ Main Program
12579:
1.184 www 12580: sub goodbye {
1.204 albertel 12581: &logthis("Starting Shut down");
1.443 albertel 12582: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12583: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12584: #converted
1.599 albertel 12585: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12586: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12587: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12588: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12589: #1.1 only
1.870 albertel 12590: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12591: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12592: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12593: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12594: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12595: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12596: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12597: &flushcourselogs();
12598: &logthis("Shutting down");
12599: }
12600:
1.852 albertel 12601: sub get_dns {
1.1172.2.17 raeburn 12602: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12603: if (!$ignore_cache) {
12604: my ($content,$cached)=
12605: &Apache::lonnet::is_cached_new('dns',$url);
12606: if ($cached) {
1.1172.2.17 raeburn 12607: &$func($content,$hashref);
1.869 albertel 12608: return;
12609: }
12610: }
12611:
12612: my %alldns;
1.1172.2.96! raeburn 12613: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
! 12614: foreach my $dns (<$config>) {
! 12615: next if ($dns !~ /^\^(\S*)/x);
! 12616: my $line = $1;
! 12617: my ($host,$protocol) = split(/:/,$line);
! 12618: if ($protocol ne 'https') {
! 12619: $protocol = 'http';
! 12620: }
! 12621: $alldns{$host} = $protocol;
1.979 raeburn 12622: }
1.1172.2.96! raeburn 12623: close($config);
1.869 albertel 12624: }
12625: while (%alldns) {
1.1172.2.52 raeburn 12626: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12627: my $ua=new LWP::UserAgent;
1.1134 raeburn 12628: $ua->timeout(30);
1.979 raeburn 12629: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12630: my $response=$ua->request($request);
1.979 raeburn 12631: delete($alldns{$dns});
1.852 albertel 12632: next if ($response->is_error());
12633: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12634: unless ($nocache) {
1.1172.2.23 raeburn 12635: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12636: }
12637: &$func(\@content,$hashref);
1.869 albertel 12638: return;
1.852 albertel 12639: }
12640: close($config);
1.871 albertel 12641: my $which = (split('/',$url))[3];
12642: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96! raeburn 12643: open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12644: my @content = <$config>;
1.1172.2.17 raeburn 12645: &$func(\@content,$hashref);
12646: return;
12647: }
12648:
12649: # ------------------------------------------------------Get DNS checksums file
12650: sub parse_dns_checksums_tab {
12651: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12652: my $lonhost = $perlvar{'lonHostID'};
12653: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12654: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12655: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12656: my $webconfdir = '/etc/httpd/conf';
12657: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12658: $webconfdir = '/etc/apache2';
12659: } elsif ($distro =~ /^sles(\d+)$/) {
12660: if ($1 >= 10) {
12661: $webconfdir = '/etc/apache2';
12662: }
12663: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12664: if ($1 >= 10.0) {
12665: $webconfdir = '/etc/apache2';
12666: }
12667: }
1.1172.2.17 raeburn 12668: my ($release,$timestamp) = split(/\-/,$loncaparev);
12669: my (%chksum,%revnum);
12670: if (ref($lines) eq 'ARRAY') {
12671: chomp(@{$lines});
1.1172.2.34 raeburn 12672: my $version = shift(@{$lines});
12673: if ($version eq $release) {
1.1172.2.17 raeburn 12674: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12675: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12676: if ($file =~ m{^/etc/httpd/conf}) {
12677: if ($webconfdir eq '/etc/apache2') {
12678: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12679: }
12680: }
1.1172.2.34 raeburn 12681: $chksum{$file} = $shasum;
12682: $revnum{$file} = $version;
1.1172.2.17 raeburn 12683: }
12684: if (ref($hashref) eq 'HASH') {
12685: %{$hashref} = (
12686: sums => \%chksum,
12687: versions => \%revnum,
12688: );
12689: }
12690: }
12691: }
1.869 albertel 12692: return;
1.852 albertel 12693: }
1.1172.2.17 raeburn 12694:
12695: sub fetch_dns_checksums {
12696: my %checksums;
1.1172.2.34 raeburn 12697: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12698: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12699: my ($release,$timestamp) = split(/\-/,$loncaparev);
12700: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12701: \%checksums);
12702: return \%checksums;
12703: }
12704:
1.327 albertel 12705: # ------------------------------------------------------------ Read domain file
12706: {
1.852 albertel 12707: my $loaded;
1.846 albertel 12708: my %domain;
12709:
1.852 albertel 12710: sub parse_domain_tab {
12711: my ($lines) = @_;
12712: foreach my $line (@$lines) {
12713: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12714:
1.846 albertel 12715: chomp($line);
1.852 albertel 12716: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12717: my %this_domain;
12718: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12719: 'lang_def', 'city', 'longi', 'lati',
12720: 'primary') {
12721: $this_domain{$field} = shift(@elements);
12722: }
12723: $domain{$name} = \%this_domain;
1.852 albertel 12724: }
12725: }
1.864 albertel 12726:
12727: sub reset_domain_info {
12728: undef($loaded);
12729: undef(%domain);
12730: }
12731:
1.852 albertel 12732: sub load_domain_tab {
1.1172.2.70 raeburn 12733: my ($ignore_cache,$nocache) = @_;
12734: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12735: my $fh;
1.1172.2.96! raeburn 12736: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 12737: my @lines = <$fh>;
12738: &parse_domain_tab(\@lines);
1.448 albertel 12739: }
1.852 albertel 12740: close($fh);
12741: $loaded = 1;
1.327 albertel 12742: }
1.846 albertel 12743:
12744: sub domain {
1.852 albertel 12745: &load_domain_tab() if (!$loaded);
12746:
1.846 albertel 12747: my ($name,$what) = @_;
12748: return if ( !exists($domain{$name}) );
12749:
12750: if (!$what) {
12751: return $domain{$name}{'description'};
12752: }
12753: return $domain{$name}{$what};
12754: }
1.974 raeburn 12755:
12756: sub domain_info {
12757: &load_domain_tab() if (!$loaded);
12758: return %domain;
12759: }
12760:
1.327 albertel 12761: }
12762:
12763:
1.1 albertel 12764: # ------------------------------------------------------------- Read hosts file
12765: {
1.838 albertel 12766: my %hostname;
1.844 albertel 12767: my %hostdom;
1.845 albertel 12768: my %libserv;
1.852 albertel 12769: my $loaded;
1.888 albertel 12770: my %name_to_host;
1.1074 raeburn 12771: my %internetdom;
1.1107 raeburn 12772: my %LC_dns_serv;
1.852 albertel 12773:
12774: sub parse_hosts_tab {
12775: my ($file) = @_;
12776: foreach my $configline (@$file) {
12777: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12778: chomp($configline);
12779: if ($configline =~ /^\^/) {
12780: if ($configline =~ /^\^([\w.\-]+)/) {
12781: $LC_dns_serv{$1} = 1;
12782: }
12783: next;
12784: }
1.1074 raeburn 12785: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12786: $name=~s/\s//g;
12787: if ($id && $domain && $role && $name) {
1.1172.2.96! raeburn 12788: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
! 12789: my $curr = $hostname{$id};
! 12790: my $skip;
! 12791: if (ref($name_to_host{$curr}) eq 'ARRAY') {
! 12792: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
! 12793: $skip = 1;
! 12794: } else {
! 12795: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
! 12796: }
! 12797: }
! 12798: unless ($skip) {
! 12799: push(@{$name_to_host{$name}},$id);
! 12800: }
! 12801: } else {
! 12802: push(@{$name_to_host{$name}},$id);
! 12803: }
1.852 albertel 12804: $hostname{$id}=$name;
12805: $hostdom{$id}=$domain;
12806: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12807: if (defined($protocol)) {
12808: if ($protocol eq 'https') {
12809: $protocol{$id} = $protocol;
12810: } else {
12811: $protocol{$id} = 'http';
12812: }
1.968 raeburn 12813: } else {
1.969 raeburn 12814: $protocol{$id} = 'http';
1.968 raeburn 12815: }
1.1074 raeburn 12816: if (defined($intdom)) {
12817: $internetdom{$id} = $intdom;
12818: }
1.852 albertel 12819: }
12820: }
12821: }
1.864 albertel 12822:
12823: sub reset_hosts_info {
1.897 albertel 12824: &purge_remembered();
1.864 albertel 12825: &reset_domain_info();
12826: &reset_hosts_ip_info();
1.892 albertel 12827: undef(%name_to_host);
1.864 albertel 12828: undef(%hostname);
12829: undef(%hostdom);
12830: undef(%libserv);
12831: undef($loaded);
12832: }
1.1 albertel 12833:
1.852 albertel 12834: sub load_hosts_tab {
1.1172.2.70 raeburn 12835: my ($ignore_cache,$nocache) = @_;
12836: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96! raeburn 12837: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 12838: my @config = <$config>;
12839: &parse_hosts_tab(\@config);
12840: close($config);
12841: $loaded=1;
1.1 albertel 12842: }
1.852 albertel 12843:
1.838 albertel 12844: sub hostname {
1.852 albertel 12845: &load_hosts_tab() if (!$loaded);
12846:
1.838 albertel 12847: my ($lonid) = @_;
12848: return $hostname{$lonid};
12849: }
1.845 albertel 12850:
1.838 albertel 12851: sub all_hostnames {
1.852 albertel 12852: &load_hosts_tab() if (!$loaded);
12853:
1.838 albertel 12854: return %hostname;
12855: }
1.845 albertel 12856:
1.888 albertel 12857: sub all_names {
1.1172.2.70 raeburn 12858: my ($ignore_cache,$nocache) = @_;
12859: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12860:
12861: return %name_to_host;
12862: }
12863:
1.974 raeburn 12864: sub all_host_domain {
12865: &load_hosts_tab() if (!$loaded);
12866: return %hostdom;
12867: }
12868:
1.845 albertel 12869: sub is_library {
1.852 albertel 12870: &load_hosts_tab() if (!$loaded);
12871:
1.845 albertel 12872: return exists($libserv{$_[0]});
12873: }
12874:
12875: sub all_library {
1.852 albertel 12876: &load_hosts_tab() if (!$loaded);
12877:
1.845 albertel 12878: return %libserv;
12879: }
12880:
1.1062 droeschl 12881: sub unique_library {
12882: #2x reverse removes all hostnames that appear more than once
12883: my %unique = reverse &all_library();
12884: return reverse %unique;
12885: }
12886:
1.841 albertel 12887: sub get_servers {
1.852 albertel 12888: &load_hosts_tab() if (!$loaded);
12889:
1.841 albertel 12890: my ($domain,$type) = @_;
12891: my %possible_hosts = ($type eq 'library') ? %libserv
12892: : %hostname;
12893: my %result;
1.842 albertel 12894: if (ref($domain) eq 'ARRAY') {
12895: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12896: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12897: $result{$host} = $hostname;
12898: }
12899: }
12900: } else {
12901: while ( my ($host,$hostname) = each(%possible_hosts)) {
12902: if ($hostdom{$host} eq $domain) {
12903: $result{$host} = $hostname;
12904: }
1.841 albertel 12905: }
12906: }
12907: return %result;
12908: }
1.845 albertel 12909:
1.1062 droeschl 12910: sub get_unique_servers {
12911: my %unique = reverse &get_servers(@_);
12912: return reverse %unique;
12913: }
12914:
1.844 albertel 12915: sub host_domain {
1.852 albertel 12916: &load_hosts_tab() if (!$loaded);
12917:
1.844 albertel 12918: my ($lonid) = @_;
12919: return $hostdom{$lonid};
12920: }
12921:
1.841 albertel 12922: sub all_domains {
1.852 albertel 12923: &load_hosts_tab() if (!$loaded);
12924:
1.841 albertel 12925: my %seen;
12926: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12927: return @uniq;
12928: }
1.1074 raeburn 12929:
12930: sub internet_dom {
12931: &load_hosts_tab() if (!$loaded);
12932:
12933: my ($lonid) = @_;
12934: return $internetdom{$lonid};
12935: }
1.1107 raeburn 12936:
12937: sub is_LC_dns {
12938: &load_hosts_tab() if (!$loaded);
12939:
12940: my ($hostname) = @_;
12941: return exists($LC_dns_serv{$hostname});
12942: }
12943:
1.1 albertel 12944: }
12945:
1.847 albertel 12946: {
12947: my %iphost;
1.856 albertel 12948: my %name_to_ip;
12949: my %lonid_to_ip;
1.869 albertel 12950:
1.847 albertel 12951: sub get_hosts_from_ip {
12952: my ($ip) = @_;
12953: my %iphosts = &get_iphost();
12954: if (ref($iphosts{$ip})) {
12955: return @{$iphosts{$ip}};
12956: }
12957: return;
1.839 albertel 12958: }
1.864 albertel 12959:
12960: sub reset_hosts_ip_info {
12961: undef(%iphost);
12962: undef(%name_to_ip);
12963: undef(%lonid_to_ip);
12964: }
1.856 albertel 12965:
12966: sub get_host_ip {
12967: my ($lonid) = @_;
12968: if (exists($lonid_to_ip{$lonid})) {
12969: return $lonid_to_ip{$lonid};
12970: }
12971: my $name=&hostname($lonid);
12972: my $ip = gethostbyname($name);
12973: return if (!$ip || length($ip) ne 4);
12974: $ip=inet_ntoa($ip);
12975: $name_to_ip{$name} = $ip;
12976: $lonid_to_ip{$lonid} = $ip;
12977: return $ip;
12978: }
1.847 albertel 12979:
12980: sub get_iphost {
1.1172.2.70 raeburn 12981: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12982:
1.869 albertel 12983: if (!$ignore_cache) {
12984: if (%iphost) {
12985: return %iphost;
12986: }
12987: my ($ip_info,$cached)=
12988: &Apache::lonnet::is_cached_new('iphost','iphost');
12989: if ($cached) {
12990: %iphost = %{$ip_info->[0]};
12991: %name_to_ip = %{$ip_info->[1]};
12992: %lonid_to_ip = %{$ip_info->[2]};
12993: return %iphost;
12994: }
12995: }
1.894 albertel 12996:
12997: # get yesterday's info for fallback
12998: my %old_name_to_ip;
12999: my ($ip_info,$cached)=
13000: &Apache::lonnet::is_cached_new('iphost','iphost');
13001: if ($cached) {
13002: %old_name_to_ip = %{$ip_info->[1]};
13003: }
13004:
1.1172.2.70 raeburn 13005: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13006: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13007: my $ip;
13008: if (!exists($name_to_ip{$name})) {
13009: $ip = gethostbyname($name);
13010: if (!$ip || length($ip) ne 4) {
1.894 albertel 13011: if (defined($old_name_to_ip{$name})) {
13012: $ip = $old_name_to_ip{$name};
13013: &logthis("Can't find $name defaulting to old $ip");
13014: } else {
13015: &logthis("Name $name no IP found");
13016: next;
13017: }
13018: } else {
13019: $ip=inet_ntoa($ip);
1.847 albertel 13020: }
13021: $name_to_ip{$name} = $ip;
13022: } else {
13023: $ip = $name_to_ip{$name};
1.653 albertel 13024: }
1.888 albertel 13025: foreach my $id (@{ $name_to_host{$name} }) {
13026: $lonid_to_ip{$id} = $ip;
13027: }
13028: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13029: }
1.1172.2.70 raeburn 13030: unless ($nocache) {
13031: &do_cache_new('iphost','iphost',
13032: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13033: 48*60*60);
13034: }
1.869 albertel 13035:
1.847 albertel 13036: return %iphost;
1.598 albertel 13037: }
13038:
1.992 raeburn 13039: #
13040: # Given a DNS returns the loncapa host name for that DNS
13041: #
13042: sub host_from_dns {
13043: my ($dns) = @_;
13044: my @hosts;
13045: my $ip;
13046:
1.993 raeburn 13047: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13048: $ip = $name_to_ip{$dns};
13049: }
13050: if (!$ip) {
13051: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13052: if (length($ip) == 4) {
13053: $ip = &IO::Socket::inet_ntoa($ip);
13054: }
13055: }
13056: if ($ip) {
13057: @hosts = get_hosts_from_ip($ip);
13058: return $hosts[0];
13059: }
13060: return undef;
1.986 foxr 13061: }
1.992 raeburn 13062:
1.1074 raeburn 13063: sub get_internet_names {
13064: my ($lonid) = @_;
13065: return if ($lonid eq '');
13066: my ($idnref,$cached)=
13067: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13068: if ($cached) {
13069: return $idnref;
13070: }
13071: my $ip = &get_host_ip($lonid);
13072: my @hosts = &get_hosts_from_ip($ip);
13073: my %iphost = &get_iphost();
13074: my (@idns,%seen);
13075: foreach my $id (@hosts) {
13076: my $dom = &host_domain($id);
13077: my $prim_id = &domain($dom,'primary');
13078: my $prim_ip = &get_host_ip($prim_id);
13079: next if ($seen{$prim_ip});
13080: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13081: foreach my $id (@{$iphost{$prim_ip}}) {
13082: my $intdom = &internet_dom($id);
13083: unless (grep(/^\Q$intdom\E$/,@idns)) {
13084: push(@idns,$intdom);
13085: }
13086: }
13087: }
13088: $seen{$prim_ip} = 1;
13089: }
1.1172.2.23 raeburn 13090: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13091: }
13092:
1.986 foxr 13093: }
13094:
1.1079 raeburn 13095: sub all_loncaparevs {
1.1172.2.39 raeburn 13096: 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 13097: }
13098:
1.1172.2.27 raeburn 13099: # ------------------------------------------------------- Read loncaparev table
13100: {
13101: sub load_loncaparevs {
13102: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96! raeburn 13103: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13104: while (my $configline=<$config>) {
13105: chomp($configline);
13106: my ($hostid,$loncaparev)=split(/:/,$configline);
13107: $loncaparevs{$hostid}=$loncaparev;
13108: }
13109: close($config);
13110: }
13111: }
13112: }
13113: }
13114:
13115: # ----------------------------------------------------- Read serverhostID table
13116: {
13117: sub load_serverhomeIDs {
13118: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96! raeburn 13119: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 13120: while (my $configline=<$config>) {
13121: chomp($configline);
13122: my ($name,$id)=split(/:/,$configline);
13123: $serverhomeIDs{$name}=$id;
13124: }
13125: close($config);
13126: }
13127: }
13128: }
13129: }
13130:
13131:
1.862 albertel 13132: BEGIN {
13133:
13134: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13135: unless ($readit) {
13136: {
13137: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13138: %perlvar = (%perlvar,%{$configvars});
13139: }
13140:
13141:
1.1 albertel 13142: # ------------------------------------------------------ Read spare server file
13143: {
1.1172.2.96! raeburn 13144: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13145:
13146: while (my $configline=<$config>) {
13147: chomp($configline);
1.284 matthew 13148: if ($configline) {
1.784 albertel 13149: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13150: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13151: push(@{ $spareid{$type} }, $host);
1.1 albertel 13152: }
13153: }
1.448 albertel 13154: close($config);
1.1 albertel 13155: }
1.11 www 13156: # ------------------------------------------------------------ Read permissions
13157: {
1.1172.2.96! raeburn 13158: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13159:
13160: while (my $configline=<$config>) {
1.448 albertel 13161: chomp($configline);
13162: if ($configline) {
13163: my ($role,$perm)=split(/ /,$configline);
13164: if ($perm ne '') { $pr{$role}=$perm; }
13165: }
1.11 www 13166: }
1.448 albertel 13167: close($config);
1.11 www 13168: }
13169:
13170: # -------------------------------------------- Read plain texts for permissions
13171: {
1.1172.2.96! raeburn 13172: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13173:
13174: while (my $configline=<$config>) {
1.448 albertel 13175: chomp($configline);
13176: if ($configline) {
1.742 raeburn 13177: my ($short,@plain)=split(/:/,$configline);
13178: %{$prp{$short}} = ();
13179: if (@plain > 0) {
13180: $prp{$short}{'std'} = $plain[0];
13181: for (my $i=1; $i<@plain; $i++) {
13182: $prp{$short}{'alt'.$i} = $plain[$i];
13183: }
13184: }
1.448 albertel 13185: }
1.135 www 13186: }
1.448 albertel 13187: close($config);
1.135 www 13188: }
13189:
13190: # ---------------------------------------------------------- Read package table
13191: {
1.1172.2.96! raeburn 13192: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13193:
13194: while (my $configline=<$config>) {
1.483 albertel 13195: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13196: chomp($configline);
13197: my ($short,$plain)=split(/:/,$configline);
13198: my ($pack,$name)=split(/\&/,$short);
13199: if ($plain ne '') {
13200: $packagetab{$pack.'&'.$name.'&name'}=$name;
13201: $packagetab{$short}=$plain;
13202: }
1.11 www 13203: }
1.448 albertel 13204: close($config);
1.329 matthew 13205: }
13206:
1.1172.2.27 raeburn 13207: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13208:
1.1172.2.27 raeburn 13209: &load_loncaparevs();
13210:
13211: # ------------------------------------------------------- Read serverhostID table
13212:
13213: &load_serverhomeIDs();
1.1074 raeburn 13214:
1.1172.2.27 raeburn 13215: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13216: {
13217: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13218: if (-e $file) {
13219: my $parser = HTML::LCParser->new($file);
13220: while (my $token = $parser->get_token()) {
13221: if ($token->[0] eq 'S') {
13222: my $item = $token->[1];
13223: my $name = $token->[2]{'name'};
13224: my $value = $token->[2]{'value'};
13225: if ($item ne '' && $name ne '' && $value ne '') {
13226: my $release = $parser->get_text();
13227: $release =~ s/(^\s*|\s*$ )//gx;
13228: $needsrelease{$item.':'.$name.':'.$value} = $release;
13229: }
13230: }
13231: }
13232: }
1.1073 raeburn 13233: }
13234:
1.1138 raeburn 13235: # ---------------------------------------------------------- Read managers table
13236: {
13237: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96! raeburn 13238: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 13239: while (my $configline=<$config>) {
13240: chomp($configline);
13241: next if ($configline =~ /^\#/);
13242: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13243: $managerstab{$configline} = 1;
13244: }
13245: }
13246: close($config);
13247: }
13248: }
13249: }
13250:
1.329 matthew 13251: # ------------- set up temporary directory
13252: {
1.1117 foxr 13253: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13254:
1.11 www 13255: }
13256:
1.794 albertel 13257: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13258: 'compress_threshold'=> 20_000,
13259: });
1.185 www 13260:
1.281 www 13261: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13262: $dumpcount=0;
1.958 www 13263: $locknum=0;
1.22 www 13264:
1.163 harris41 13265: &logtouch();
1.672 albertel 13266: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13267: $readit=1;
1.564 albertel 13268: {
13269: use integer;
13270: my $test=(2**32)+1;
1.568 albertel 13271: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13272: &logthis(" Detected 64bit platform ($_64bit)");
13273: }
1.195 www 13274: }
1.1 albertel 13275: }
1.179 www 13276:
1.1 albertel 13277: 1;
1.191 harris41 13278: __END__
13279:
1.243 albertel 13280: =pod
13281:
1.191 harris41 13282: =head1 NAME
13283:
1.243 albertel 13284: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13285:
13286: =head1 SYNOPSIS
13287:
1.243 albertel 13288: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13289:
13290: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13291:
1.243 albertel 13292: Common parameters:
13293:
13294: =over 4
13295:
13296: =item *
13297:
13298: $uname : an internal username (if $cname expecting a course Id specifically)
13299:
13300: =item *
13301:
13302: $udom : a domain (if $cdom expecting a course's domain specifically)
13303:
13304: =item *
13305:
13306: $symb : a resource instance identifier
13307:
13308: =item *
13309:
13310: $namespace : the name of a .db file that contains the data needed or
13311: being set.
13312:
13313: =back
13314:
1.394 bowersj2 13315: =head1 OVERVIEW
1.191 harris41 13316:
1.394 bowersj2 13317: lonnet provides subroutines which interact with the
13318: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13319: about classes, users, and resources.
1.243 albertel 13320:
13321: For many of these objects you can also use this to store data about
13322: them or modify them in various ways.
1.191 harris41 13323:
1.394 bowersj2 13324: =head2 Symbs
1.191 harris41 13325:
1.394 bowersj2 13326: To identify a specific instance of a resource, LON-CAPA uses symbols
13327: or "symbs"X<symb>. These identifiers are built from the URL of the
13328: map, the resource number of the resource in the map, and the URL of
13329: the resource itself. The latter is somewhat redundant, but might help
13330: if maps change.
13331:
13332: An example is
13333:
13334: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13335:
13336: The respective map entry is
13337:
13338: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13339: title="Problem 2">
13340: </resource>
13341:
13342: Symbs are used by the random number generator, as well as to store and
13343: restore data specific to a certain instance of for example a problem.
13344:
13345: =head2 Storing And Retrieving Data
13346:
13347: X<store()>X<cstore()>X<restore()>Three of the most important functions
13348: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13349: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13350: is is the non-critical message twin of cstore. These functions are for
13351: handlers to store a perl hash to a user's permanent data space in an
13352: easy manner, and to retrieve it again on another call. It is expected
13353: that a handler would use this once at the beginning to retrieve data,
13354: and then again once at the end to send only the new data back.
13355:
13356: The data is stored in the user's data directory on the user's
13357: homeserver under the ID of the course.
13358:
13359: The hash that is returned by restore will have all of the previous
13360: value for all of the elements of the hash.
13361:
13362: Example:
13363:
13364: #creating a hash
13365: my %hash;
13366: $hash{'foo'}='bar';
13367:
13368: #storing it
13369: &Apache::lonnet::cstore(\%hash);
13370:
13371: #changing a value
13372: $hash{'foo'}='notbar';
13373:
13374: #adding a new value
13375: $hash{'bar'}='foo';
13376: &Apache::lonnet::cstore(\%hash);
13377:
13378: #retrieving the hash
13379: my %history=&Apache::lonnet::restore();
13380:
13381: #print the hash
13382: foreach my $key (sort(keys(%history))) {
13383: print("\%history{$key} = $history{$key}");
13384: }
13385:
13386: Will print out:
1.191 harris41 13387:
1.394 bowersj2 13388: %history{1:foo} = bar
13389: %history{1:keys} = foo:timestamp
13390: %history{1:timestamp} = 990455579
13391: %history{2:bar} = foo
13392: %history{2:foo} = notbar
13393: %history{2:keys} = foo:bar:timestamp
13394: %history{2:timestamp} = 990455580
13395: %history{bar} = foo
13396: %history{foo} = notbar
13397: %history{timestamp} = 990455580
13398: %history{version} = 2
13399:
13400: Note that the special hash entries C<keys>, C<version> and
13401: C<timestamp> were added to the hash. C<version> will be equal to the
13402: total number of versions of the data that have been stored. The
13403: C<timestamp> attribute will be the UNIX time the hash was
13404: stored. C<keys> is available in every historical section to list which
13405: keys were added or changed at a specific historical revision of a
13406: hash.
13407:
13408: B<Warning>: do not store the hash that restore returns directly. This
13409: will cause a mess since it will restore the historical keys as if the
13410: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13411:
1.394 bowersj2 13412: Calling convention:
1.191 harris41 13413:
1.1172.2.27 raeburn 13414: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13415: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13416:
1.394 bowersj2 13417: For more detailed information, see lonnet specific documentation.
1.191 harris41 13418:
1.394 bowersj2 13419: =head1 RETURN MESSAGES
1.191 harris41 13420:
1.394 bowersj2 13421: =over 4
1.191 harris41 13422:
1.394 bowersj2 13423: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13424:
1.394 bowersj2 13425: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13426: when the connection is brought back up
1.191 harris41 13427:
1.394 bowersj2 13428: =item * B<con_failed>: unable to contact remote host and unable to save message
13429: for later delivery
1.191 harris41 13430:
1.967 bisitz 13431: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13432:
1.394 bowersj2 13433: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13434: that was requested
1.191 harris41 13435:
1.243 albertel 13436: =back
1.191 harris41 13437:
1.243 albertel 13438: =head1 PUBLIC SUBROUTINES
1.191 harris41 13439:
1.243 albertel 13440: =head2 Session Environment Functions
1.191 harris41 13441:
1.243 albertel 13442: =over 4
1.191 harris41 13443:
1.394 bowersj2 13444: =item *
13445: X<appenv()>
1.949 raeburn 13446: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13447: the user envirnoment file, and will be restored for each access this
1.620 albertel 13448: user makes during this session, also modifies the %env for the current
1.949 raeburn 13449: process. Optional rolesarrayref - if defined contains a reference to an array
13450: of roles which are exempt from the restriction on modifying user.role entries
13451: in the user's environment.db and in %env.
1.191 harris41 13452:
13453: =item *
1.394 bowersj2 13454: X<delenv()>
1.987 raeburn 13455: B<delenv($delthis,$regexp)>: removes all items from the session
13456: environment file that begin with $delthis. If the
13457: optional second arg - $regexp - is true, $delthis is treated as a
13458: regular expression, otherwise \Q$delthis\E is used.
13459: The values are also deleted from the current processes %env.
1.191 harris41 13460:
1.795 albertel 13461: =item * get_env_multiple($name)
13462:
13463: gets $name from the %env hash, it seemlessly handles the cases where multiple
13464: values may be defined and end up as an array ref.
13465:
13466: returns an array of values
13467:
1.243 albertel 13468: =back
13469:
13470: =head2 User Information
1.191 harris41 13471:
1.243 albertel 13472: =over 4
1.191 harris41 13473:
13474: =item *
1.394 bowersj2 13475: X<queryauthenticate()>
13476: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13477: authentication scheme
13478:
13479: =item *
1.394 bowersj2 13480: X<authenticate()>
1.1073 raeburn 13481: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13482: authenticate user from domain's lib servers (first use the current
13483: one). C<$upass> should be the users password.
1.1073 raeburn 13484: $checkdefauth is optional (value is 1 if a check should be made to
13485: authenticate user using default authentication method, and allow
13486: account creation if username does not have account in the domain).
13487: $clientcancheckhost is optional (value is 1 if checking whether the
13488: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13489:
13490: =item *
1.394 bowersj2 13491: X<homeserver()>
13492: B<homeserver($uname,$udom)>: find the server which has
13493: the user's directory and files (there must be only one), this caches
13494: the answer, and also caches if there is a borken connection.
1.191 harris41 13495:
13496: =item *
1.394 bowersj2 13497: X<idget()>
13498: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13499: (IDs are a unique resource in a domain, there must be only 1 ID per
13500: username, and only 1 username per ID in a specific domain) (returns
13501: hash: id=>name,id=>name)
1.191 harris41 13502:
13503: =item *
1.394 bowersj2 13504: X<idrget()>
13505: B<idrget($udom,@unames)>: find the IDs behind a list of
13506: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13507:
13508: =item *
1.394 bowersj2 13509: X<idput()>
13510: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13511:
13512: =item *
1.394 bowersj2 13513: X<rolesinit()>
1.1169 droeschl 13514: B<rolesinit($udom,$username)>: get user privileges.
13515: returns user role, first access and timer interval hashes
1.243 albertel 13516:
13517: =item *
1.1171 droeschl 13518: X<privileged()>
13519: B<privileged($username,$domain)>: returns a true if user has a
13520: privileged and active role (i.e. su or dc), false otherwise.
13521:
13522: =item *
1.551 albertel 13523: X<getsection()>
13524: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13525: course $cname, return section name/number or '' for "not in course"
13526: and '-1' for "no section"
13527:
13528: =item *
1.394 bowersj2 13529: X<userenvironment()>
13530: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13531: passed in @what from the requested user's environment, returns a hash
13532:
1.858 raeburn 13533: =item *
13534: X<userlog_query()>
1.859 albertel 13535: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13536: activity.log file. %filters defines filters applied when parsing the
13537: log file. These can be start or end timestamps, or the type of action
13538: - log to look for Login or Logout events, check for Checkin or
13539: Checkout, role for role selection. The response is in the form
13540: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13541: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13542:
1.243 albertel 13543: =back
13544:
13545: =head2 User Roles
13546:
13547: =over 4
13548:
13549: =item *
13550:
1.1172.2.65 raeburn 13551: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13552: returns codes for allowed actions.
13553:
13554: The first argument is required, all others are optional.
13555:
13556: $priv is the privilege being checked.
13557: $uri contains additional information about what is being checked for access (e.g.,
13558: URL, course ID etc.).
13559: $symb is the unique resource instance identifier in a course; if needed,
13560: but not provided, it will be retrieved via a call to &symbread().
13561: $role is the role for which a priv is being checked (only used if priv is evb).
13562: $clientip is the user's IP address (only used when checking for access to portfolio
13563: files).
13564: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13565: prevents recursive calls to &allowed.
13566:
1.243 albertel 13567: F: full access
13568: U,I,K: authentication modes (cxx only)
13569: '': forbidden
13570: 1: user needs to choose course
13571: 2: browse allowed
1.766 albertel 13572: A: passphrase authentication needed
1.1172.2.65 raeburn 13573: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13574:
13575: =item *
13576:
1.1172.2.13 raeburn 13577: constructaccess($url,$setpriv) : check for access to construction space URL
13578:
13579: See if the owner domain and name in the URL match those in the
13580: expected environment. If so, return three element list
13581: ($ownername,$ownerdomain,$ownerhome).
13582:
13583: Otherwise return the null string.
13584:
13585: If second argument 'setpriv' is true, it assigns the privileges,
13586: and returns the same three element list, unless the owner has
13587: blocked "ad hoc" Domain Coordinator access to the Author Space,
13588: in which case the null string is returned.
13589:
13590: =item *
13591:
1.1172.2.84 raeburn 13592: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13593: define a custom role rolename set privileges in format of lonTabs/roles.tab
13594: for system, domain, and course level. $uname and $udom are optional (current
13595: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13596:
13597: =item *
13598:
1.988 raeburn 13599: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13600: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13601: $type is Course (default) or Community.
1.988 raeburn 13602: If $forcedefault evaluates to true, text returned will be default
13603: text for $type. Otherwise, if this is a course, the text returned
13604: will be a custom name for the role (if defined in the course's
13605: environment). If no custom name is defined the default is returned.
13606:
1.832 raeburn 13607: =item *
13608:
1.1172.2.23 raeburn 13609: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13610: All arguments are optional. Returns a hash of a roles, either for
13611: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13612: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13613: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13614: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13615: For each key, value is set to colon-separated start and end times for
13616: the role. If no username and domain are specified, will default to
1.934 raeburn 13617: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13618: of role statuses (active, future or previous), roles
13619: (e.g., cc,in, st etc.) and domains of the roles which can be used
13620: to restrict the list of roles reported. If no array ref is
13621: provided for types, will default to return only active roles.
1.834 albertel 13622:
1.1172.2.13 raeburn 13623: =item *
13624:
13625: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13626: user: $uname:$udom has a role in the course: $cdom_$cnum.
13627:
13628: Additional optional arguments are: $type (if role checking is to be restricted
13629: to certain user status types -- previous (expired roles), active (currently
13630: available roles) or future (roles available in the future), and
13631: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13632: have active Domain Coordinator role in course's domain or in additional
13633: domains (specified in 'Domains to check for privileged users' in course
13634: environment -- set via: Course Settings -> Classlists and staff listing).
13635:
13636: =item *
13637:
13638: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13639: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13640: $possdomains and $possroles are optional array refs -- to domains to check and
13641: roles to check. If $possdomains is not specified, a dump will be done of the
13642: users' roles.db to check for a dc or su role in any domain. This can be
13643: time consuming if &privileged is called repeatedly (e.g., when displaying a
13644: classlist), so in such cases, supplying a $possdomains array is preferred, as
13645: this then allows &privileged_by_domain() to be used, which caches the identity
13646: of privileged users, eliminating the need for repeated calls to &dump().
13647:
13648: =item *
13649:
13650: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13651: where the outer hash keys are domains specified in the $possdomains array ref,
13652: next inner hash keys are privileged roles specified in the $roles array ref,
13653: and the innermost hash contains key = value pairs for username:domain = end:start
13654: for active or future "privileged" users with that role in that domain. To avoid
13655: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13656: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13657:
1.243 albertel 13658: =back
13659:
13660: =head2 User Modification
13661:
13662: =over 4
13663:
13664: =item *
13665:
1.957 raeburn 13666: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13667: user for the level given by URL. Optional start and end dates (leave empty
13668: string or zero for "no date")
1.191 harris41 13669:
13670: =item *
13671:
1.243 albertel 13672: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13673: change a users, password, possible return values are: ok,
13674: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13675: refused
1.191 harris41 13676:
13677: =item *
13678:
1.243 albertel 13679: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13680:
13681: =item *
13682:
1.1058 raeburn 13683: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13684: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13685:
13686: will update user information (firstname,middlename,lastname,generation,
13687: permanentemail), and if forceid is true, student/employee ID also.
13688: A user's institutional affiliation(s) can also be updated.
13689: User information fields will not be overwritten with empty entries
13690: unless the field is included in the $candelete array reference.
13691: This array is included when a single user is modified via "Manage Users",
13692: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13693:
13694: =item *
13695:
1.286 matthew 13696: modifystudent
13697:
1.957 raeburn 13698: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13699: The course id is resolved based on the current user's environment.
13700: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13701: associated with a course.
13702:
1.297 matthew 13703: This call is essentially a wrapper for lonnet::modifyuser and
13704: lonnet::modify_student_enrollment
1.286 matthew 13705:
13706: Inputs:
13707:
13708: =over 4
13709:
1.957 raeburn 13710: =item B<$udom> Student's loncapa domain
1.286 matthew 13711:
1.957 raeburn 13712: =item B<$uname> Student's loncapa login name
1.286 matthew 13713:
1.964 bisitz 13714: =item B<$uid> Student/Employee ID
1.286 matthew 13715:
1.957 raeburn 13716: =item B<$umode> Student's authentication mode
1.286 matthew 13717:
1.957 raeburn 13718: =item B<$upass> Student's password
1.286 matthew 13719:
1.957 raeburn 13720: =item B<$first> Student's first name
1.286 matthew 13721:
1.957 raeburn 13722: =item B<$middle> Student's middle name
1.286 matthew 13723:
1.957 raeburn 13724: =item B<$last> Student's last name
1.286 matthew 13725:
1.957 raeburn 13726: =item B<$gene> Student's generation
1.286 matthew 13727:
1.957 raeburn 13728: =item B<$usec> Student's section in course
1.286 matthew 13729:
13730: =item B<$end> Unix time of the roles expiration
13731:
13732: =item B<$start> Unix time of the roles start date
13733:
13734: =item B<$forceid> If defined, allow $uid to be changed
13735:
13736: =item B<$desiredhome> server to use as home server for student
13737:
1.957 raeburn 13738: =item B<$email> Student's permanent e-mail address
13739:
13740: =item B<$type> Type of enrollment (auto or manual)
13741:
1.963 raeburn 13742: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13743:
13744: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13745:
1.963 raeburn 13746: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13747:
1.963 raeburn 13748: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13749:
1.1172.2.19 raeburn 13750: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13751:
13752: =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 13753:
1.286 matthew 13754: =back
1.297 matthew 13755:
13756: =item *
13757:
13758: modify_student_enrollment
13759:
1.1172.2.31 raeburn 13760: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13761: 'role.request.course' must be defined for this function to proceed.
13762:
13763: Inputs:
13764:
13765: =over 4
13766:
1.1172.2.31 raeburn 13767: =item $udom, student's domain
1.297 matthew 13768:
1.1172.2.31 raeburn 13769: =item $uname, student's name
1.297 matthew 13770:
1.1172.2.31 raeburn 13771: =item $uid, student's user id
1.297 matthew 13772:
1.1172.2.31 raeburn 13773: =item $first, student's first name
1.297 matthew 13774:
13775: =item $middle
13776:
13777: =item $last
13778:
13779: =item $gene
13780:
13781: =item $usec
13782:
13783: =item $end
13784:
13785: =item $start
13786:
1.957 raeburn 13787: =item $type
13788:
13789: =item $locktype
13790:
13791: =item $cid
13792:
13793: =item $selfenroll
13794:
13795: =item $context
13796:
1.1172.2.19 raeburn 13797: =item $credits, number of credits student will earn from this class
13798:
1.1172.2.76 raeburn 13799: =item $instsec, institutional course section code for student
13800:
1.297 matthew 13801: =back
13802:
1.191 harris41 13803:
13804: =item *
13805:
1.243 albertel 13806: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13807: custom role; give a custom role to a user for the level given by URL. Specify
13808: name and domain of role author, and role name
1.191 harris41 13809:
13810: =item *
13811:
1.243 albertel 13812: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13813:
13814: =item *
13815:
1.243 albertel 13816: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13817:
13818: =back
13819:
13820: =head2 Course Infomation
13821:
13822: =over 4
1.191 harris41 13823:
13824: =item *
13825:
1.1118 foxr 13826: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13827: specified course id, including all environment settings for the
13828: course, the description of the course will be in the hash under the
13829: key 'description'
1.191 harris41 13830:
1.1118 foxr 13831: $options is an optional parameter that if supplied is a hash reference that controls
13832: what how this function works. It has the following key/values:
13833:
13834: =over 4
13835:
13836: =item freshen_cache
13837:
13838: If defined, and the environment cache for the course is valid, it is
13839: returned in the returned hash.
13840:
13841: =item one_time
13842:
13843: If defined, the last cache time is set to _now_
13844:
13845: =item user
13846:
13847: If defined, the supplied username is used instead of the current user.
13848:
13849:
13850: =back
13851:
1.191 harris41 13852: =item *
13853:
1.624 albertel 13854: resdata($name,$domain,$type,@which) : request for current parameter
13855: setting for a specific $type, where $type is either 'course' or 'user',
13856: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13857: answers for 10 minutes.
1.243 albertel 13858:
1.877 foxr 13859: =item *
13860:
13861: get_courseresdata($courseid, $domain) : dump the entire course resource
13862: data base, returning a hash that is keyed by the resource name and has
13863: values that are the resource value. I believe that the timestamps and
13864: versions are also returned.
13865:
1.1172.2.31 raeburn 13866: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13867: supplemental content area. This routine caches the number of files for
13868: 10 minutes.
13869:
1.243 albertel 13870: =back
13871:
13872: =head2 Course Modification
13873:
13874: =over 4
1.191 harris41 13875:
13876: =item *
13877:
1.243 albertel 13878: writecoursepref($courseid,%prefs) : write preferences (environment
13879: database) for a course
1.191 harris41 13880:
13881: =item *
13882:
1.1011 raeburn 13883: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13884:
13885: =item *
13886:
1.1038 raeburn 13887: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13888:
1.1167 droeschl 13889: =item *
13890:
13891: is_course($courseid), is_course($cdom, $cnum)
13892:
13893: Accepts either a combined $courseid (in the form of domain_courseid) or the
13894: two component version $cdom, $cnum. It checks if the specified course exists.
13895:
13896: Returns:
13897: undef if the course doesn't exist, otherwise
13898: in scalar context the combined courseid.
13899: in list context the two components of the course identifier, domain and
13900: courseid.
13901:
1.243 albertel 13902: =back
13903:
13904: =head2 Resource Subroutines
13905:
13906: =over 4
1.191 harris41 13907:
13908: =item *
13909:
1.243 albertel 13910: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13911:
13912: =item *
13913:
1.243 albertel 13914: repcopy($filename) : subscribes to the requested file, and attempts to
13915: replicate from the owning library server, Might return
1.607 raeburn 13916: 'unavailable', 'not_found', 'forbidden', 'ok', or
13917: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13918: resource. Expects the local filesystem pathname
13919: (/home/httpd/html/res/....)
13920:
13921: =back
13922:
13923: =head2 Resource Information
13924:
13925: =over 4
1.191 harris41 13926:
13927: =item *
13928:
1.1172.2.28 raeburn 13929: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13930: and returns the value of a variety of different possible values,
13931: $varname should be a request string, and the other parameters can be
13932: used to specify who and what one is asking about. Ordinarily, $cid
13933: does not need to be specified, as it is retrived from
13934: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13935: within lonuserstate::loadmap() when initializing a course, before
13936: $env{'request.course.id'} has been set, so it needs to be provided
13937: in that one case.
1.243 albertel 13938:
13939: Possible values for $varname are environment.lastname (or other item
13940: from the envirnment hash), user.name (or someother aspect about the
13941: user), resource.0.maxtries (or some other part and parameter of a
13942: resource)
1.204 albertel 13943:
13944: =item *
13945:
1.243 albertel 13946: directcondval($number) : get current value of a condition; reads from a state
13947: string
1.204 albertel 13948:
13949: =item *
13950:
1.243 albertel 13951: condval($condidx) : value of condition index based on state
1.204 albertel 13952:
13953: =item *
13954:
1.243 albertel 13955: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13956: resource's metadata, $what should be either a specific key, or either
13957: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13958: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13959:
13960: this function automatically caches all requests
1.191 harris41 13961:
13962: =item *
13963:
1.243 albertel 13964: metadata_query($query,$custom,$customshow) : make a metadata query against the
13965: network of library servers; returns file handle of where SQL and regex results
13966: will be stored for query
1.191 harris41 13967:
13968: =item *
13969:
1.1172.2.66 raeburn 13970: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13971: return symbolic list entry (all arguments optional).
13972:
13973: Args: filename is the filename (including path) for the file for which a symb
13974: is required; donotrecurse, if true will prevent calls to allowed() being made
13975: to check access status if more than one resource was found in the bighash
13976: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13977: a randompick); ignorecachednull, if true will prevent a symb of '' being
13978: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13979: cause possible symbs to be checked to determine if they are subject to content
13980: blocking, if so they will not be included as possible symbs; possibles is a
13981: ref to a hash, which, as a side effect, will be populated with all possible
13982: symbs (content blocking not tested).
13983:
1.243 albertel 13984: returns the data handle
1.191 harris41 13985:
13986: =item *
13987:
1.1172.2.17 raeburn 13988: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13989: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13990: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13991: on failure, user must be in a course, as it assumes the existence of
13992: the course initial hash, and uses $env('request.course.id'}. The third
13993: arg is an optional reference to a scalar. If this arg is passed in the
13994: call to symbverify, it will be set to 1 if the symb has been set to be
13995: encrypted; otherwise it will be null.
1.243 albertel 13996:
1.191 harris41 13997: =item *
13998:
1.243 albertel 13999: symbclean($symb) : removes versions numbers from a symb, returns the
14000: cleaned symb
1.191 harris41 14001:
14002: =item *
14003:
1.243 albertel 14004: is_on_map($uri) : checks if the $uri is somewhere on the current
14005: course map, user must be in a course for it to work.
1.191 harris41 14006:
14007: =item *
14008:
1.243 albertel 14009: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14010:
14011: =item *
14012:
1.243 albertel 14013: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14014: a random seed, all arguments are optional, if they aren't sent it uses the
14015: environment to derive them. Note: if symb isn't sent and it can't get one
14016: from &symbread it will use the current time as its return value
1.191 harris41 14017:
14018: =item *
14019:
1.243 albertel 14020: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14021: unfakeable, receipt
1.191 harris41 14022:
14023: =item *
14024:
1.620 albertel 14025: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14026:
14027: =item *
14028:
1.243 albertel 14029: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14030:
14031: =item *
14032:
1.243 albertel 14033: 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 14034:
14035: =item *
14036:
1.243 albertel 14037: 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 14038:
14039: =item *
14040:
1.243 albertel 14041: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14042:
14043: =item *
14044:
1.243 albertel 14045: devalidate($symb) : devalidate temporary spreadsheet calculations,
14046: forcing spreadsheet to reevaluate the resource scores next time.
14047:
1.1172.2.13 raeburn 14048: =item *
14049:
14050: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14051: when viewing in course context.
14052:
14053: input: six args -- filename (decluttered), course number, course domain,
14054: url, symb (if registered) and group (if this is a
14055: group item -- e.g., bulletin board, group page etc.).
14056:
14057: output: array of five scalars --
14058: $cfile -- url for file editing if editable on current server
14059: $home -- homeserver of resource (i.e., for author if published,
14060: or course if uploaded.).
14061: $switchserver -- 1 if server switch will be needed.
14062: $forceedit -- 1 if icon/link should be to go to edit mode
14063: $forceview -- 1 if icon/link should be to go to view mode
14064:
14065: =item *
14066:
14067: is_course_upload($file,$cnum,$cdom)
14068:
14069: Used in course context to determine if current file was uploaded to
14070: the course (i.e., would be found in /userfiles/docs on the course's
14071: homeserver.
14072:
14073: input: 3 args -- filename (decluttered), course number and course domain.
14074: output: boolean -- 1 if file was uploaded.
14075:
1.243 albertel 14076: =back
14077:
14078: =head2 Storing/Retreiving Data
14079:
14080: =over 4
1.191 harris41 14081:
14082: =item *
14083:
1.1172.2.64 raeburn 14084: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14085: permanently for this url; hashref needs to be given and should be a \%hashname;
14086: the remaining args aren't required and if they aren't passed or are '' they will
14087: be derived from the env (with the exception of $laststore, which is an
14088: optional arg used when a user's submission is stored in grading).
14089: $laststore is $version=$timestamp, where $version is the most recent version
14090: number retrieved for the corresponding $symb in the $namespace db file, and
14091: $timestamp is the timestamp for that transaction (UNIX time).
14092: $laststore is currently only passed when cstore() is called by
14093: structuretags::finalize_storage().
1.191 harris41 14094:
14095: =item *
14096:
1.1172.2.64 raeburn 14097: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14098: but uses critical subroutine
1.191 harris41 14099:
14100: =item *
14101:
1.243 albertel 14102: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14103: all args are optional
1.191 harris41 14104:
14105: =item *
14106:
1.717 albertel 14107: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14108: dumps the complete (or key matching regexp) namespace into a hash
14109: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14110: normally &store()ed into
14111:
14112: $range should be either an integer '100' (give me the first 100
14113: matching records)
14114: or be two integers sperated by a - with no spaces
14115: '30-50' (give me the 30th through the 50th matching
14116: records)
14117:
14118:
14119: =item *
14120:
1.1172.2.59 raeburn 14121: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14122: replaces a &store() version of data with a replacement set of data
14123: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14124: reference. If $tolog is true, the transaction is logged in the courselog
14125: with an action=PUTSTORE.
1.717 albertel 14126:
14127: =item *
14128:
1.243 albertel 14129: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14130: works very similar to store/cstore, but all data is stored in a
14131: temporary location and can be reset using tmpreset, $storehash should
14132: be a hash reference, returns nothing on success
1.191 harris41 14133:
14134: =item *
14135:
1.243 albertel 14136: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14137: similar to restore, but all data is stored in a temporary location and
14138: can be reset using tmpreset. Returns a hash of values on success,
14139: error string otherwise.
1.191 harris41 14140:
14141: =item *
14142:
1.243 albertel 14143: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14144: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14145:
14146: =item *
14147:
1.243 albertel 14148: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14149: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14150:
14151: =item *
14152:
1.243 albertel 14153: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14154: namesp ($udom and $uname are optional)
1.191 harris41 14155:
14156: =item *
14157:
1.702 albertel 14158: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14159: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14160: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14161:
1.702 albertel 14162: $range should be either an integer '100' (give me the first 100
14163: matching records)
14164: or be two integers sperated by a - with no spaces
14165: '30-50' (give me the 30th through the 50th matching
14166: records)
1.449 matthew 14167: =item *
14168:
14169: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14170: $store can be a scalar, an array reference, or if the amount to be
14171: incremented is > 1, a hash reference.
14172:
14173: ($udom and $uname are optional)
1.191 harris41 14174:
14175: =item *
14176:
1.243 albertel 14177: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14178: ($udom and $uname are optional)
1.191 harris41 14179:
14180: =item *
14181:
1.243 albertel 14182: cput($namespace,$storehash,$udom,$uname) : critical put
14183: ($udom and $uname are optional)
1.191 harris41 14184:
14185: =item *
14186:
1.748 albertel 14187: newput($namespace,$storehash,$udom,$uname) :
14188:
14189: Attempts to store the items in the $storehash, but only if they don't
14190: currently exist, if this succeeds you can be certain that you have
14191: successfully created a new key value pair in the $namespace db.
14192:
14193:
14194: Args:
14195: $namespace: name of database to store values to
14196: $storehash: hashref to store to the db
14197: $udom: (optional) domain of user containing the db
14198: $uname: (optional) name of user caontaining the db
14199:
14200: Returns:
14201: 'ok' -> succeeded in storing all keys of $storehash
14202: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14203: least <key> already existed in the db (other
14204: requested keys may also already exist)
1.967 bisitz 14205: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14206: 'con_lost' -> unable to contact request server
14207: 'refused' -> action was not allowed by remote machine
14208:
14209:
14210: =item *
14211:
1.243 albertel 14212: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14213: reference filled in from namesp (encrypts the return communication)
14214: ($udom and $uname are optional)
1.191 harris41 14215:
14216: =item *
14217:
1.243 albertel 14218: log($udom,$name,$home,$message) : write to permanent log for user; use
14219: critical subroutine
14220:
1.806 raeburn 14221: =item *
14222:
1.860 raeburn 14223: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14224: array reference filled in from namespace found in domain level on either
14225: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14226:
14227: =item *
14228:
1.860 raeburn 14229: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14230: domain level either on specified domain server ($uhome) or primary domain
14231: server ($udom and $uhome are optional)
1.806 raeburn 14232:
1.943 raeburn 14233: =item *
14234:
1.1172.2.35 raeburn 14235: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14236: for: authentication, language, quotas, timezone, date locale, and portal URL in
14237: the target domain.
14238:
14239: May also include additional key => value pairs for the following groups:
14240:
14241: =over
14242:
14243: =item
14244: disk quotas (MB allocated by default to portfolios and authoring spaces).
14245:
14246: =over
14247:
14248: =item defaultquota, authorquota
14249:
14250: =back
14251:
14252: =item
14253: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14254: portfolio for users).
14255:
14256: =over
14257:
14258: =item
14259: aboutme, blog, webdav, portfolio
14260:
14261: =back
14262:
14263: =item
14264: requestcourses: ability to request courses, and how requests are processed.
14265:
14266: =over
14267:
14268: =item
1.1172.2.37 raeburn 14269: official, unofficial, community, textbook
1.1172.2.35 raeburn 14270:
14271: =back
14272:
14273: =item
14274: inststatus: types of institutional affiliation, and order in which they are displayed.
14275:
14276: =over
14277:
14278: =item
1.1172.2.44 raeburn 14279: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14280:
14281: =back
14282:
14283: =item
14284: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14285: for course's uploaded content.
14286:
14287: =over
14288:
14289: =item
1.1172.2.68 raeburn 14290: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14291: communityquota, textbookquota
1.1172.2.35 raeburn 14292:
14293: =back
14294:
14295: =item
14296: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14297: on your servers.
14298:
14299: =over
14300:
14301: =item
14302: remotesessions, hostedsessions
14303:
14304: =back
14305:
14306: =back
14307:
14308: In cases where a domain coordinator has never used the "Set Domain Configuration"
14309: utility to create a configuration.db file on a domain's primary library server
14310: only the following domain defaults: auth_def, auth_arg_def, lang_def
14311: -- corresponding values are authentication type (internal, krb4, krb5,
14312: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14313: will be available. Values are retrieved from cache (if current), unless the
14314: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14315: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14316:
14317: Typical usage:
1.943 raeburn 14318:
1.1172.2.35 raeburn 14319: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14320:
1.243 albertel 14321: =back
14322:
14323: =head2 Network Status Functions
14324:
14325: =over 4
1.191 harris41 14326:
14327: =item *
14328:
1.1137 raeburn 14329: dirlist() : return directory list based on URI (first arg).
14330:
14331: Inputs: 1 required, 5 optional.
14332:
14333: =over
14334:
14335: =item
14336: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14337:
14338: =item
14339: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14340:
14341: =item
14342: $username - username of user/course to be listed. Extracted from $uri if absent.
14343:
14344: =item
14345: $getpropath - boolean: 1 if prepend path using &propath().
14346:
14347: =item
14348: $getuserdir - boolean: 1 if prepend path for "userfiles".
14349:
14350: =item
14351: $alternateRoot - path to prepend in place of path from $uri.
14352:
14353: =back
14354:
14355: Returns: Array of up to two items.
14356:
14357: =over
14358:
14359: a reference to an array of files/subdirectories
14360:
14361: =over
14362:
14363: Each element in the array of files/subdirectories is a & separated list of
14364: item name and the result of running stat on the item. If dirlist was requested
14365: for a file instead of a directory, the item name will be ''. For a directory
14366: listing, if the item is a metadata file, the element will end &N&M
14367: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14368: default copyright set (1).
14369:
14370: =back
14371:
14372: a scalar containing error condition (if encountered).
14373:
14374: =over
14375:
14376: =item
14377: no_host (no homeserver identified for $username:$domain).
14378:
14379: =item
14380: no_such_host (server contacted for listing not identified as valid host).
14381:
14382: =item
14383: con_lost (connection to remote server failed).
14384:
14385: =item
14386: refused (invalid $username:$domain received on lond side).
14387:
14388: =item
14389: no_such_dir (directory at specified path on lond side does not exist).
14390:
14391: =item
14392: empty (directory at specified path on lond side is empty).
14393:
14394: =over
14395:
14396: This is currently not encountered because the &ls3, &ls2,
14397: &ls (_handler) routines on the lond side do not filter out
14398: . and .. from a directory listing.
14399:
14400: =back
14401:
14402: =back
14403:
14404: =back
1.191 harris41 14405:
14406: =item *
14407:
1.243 albertel 14408: spareserver() : find server with least workload from spare.tab
14409:
1.986 foxr 14410:
14411: =item *
14412:
14413: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14414: if there is no corresponding loncapa host.
14415:
1.243 albertel 14416: =back
14417:
1.986 foxr 14418:
1.243 albertel 14419: =head2 Apache Request
14420:
14421: =over 4
1.191 harris41 14422:
14423: =item *
14424:
1.243 albertel 14425: ssi($url,%hash) : server side include, does a complete request cycle on url to
14426: localhost, posts hash
14427:
14428: =back
14429:
14430: =head2 Data to String to Data
14431:
14432: =over 4
1.191 harris41 14433:
14434: =item *
14435:
1.243 albertel 14436: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14437: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14438:
14439: =item *
14440:
1.243 albertel 14441: hashref2str($hashref) : convert a hashref into a string complete with
14442: escaping and '=' and '&' separators, supports elements that are
14443: arrayrefs and hashrefs
1.191 harris41 14444:
14445: =item *
14446:
1.243 albertel 14447: arrayref2str($arrayref) : convert an arrayref into a string complete
14448: with escaping and '&' separators, supports elements that are arrayrefs
14449: and hashrefs
1.191 harris41 14450:
14451: =item *
14452:
1.243 albertel 14453: str2hash($string) : convert string to hash using unescaping and
14454: splitting on '=' and '&', supports elements that are arrayrefs and
14455: hashrefs
1.191 harris41 14456:
14457: =item *
14458:
1.243 albertel 14459: str2array($string) : convert string to hash using unescaping and
14460: splitting on '&', supports elements that are arrayrefs and hashrefs
14461:
14462: =back
14463:
14464: =head2 Logging Routines
14465:
14466:
14467: These routines allow one to make log messages in the lonnet.log and
14468: lonnet.perm logfiles.
1.191 harris41 14469:
1.1119 foxr 14470: =over 4
14471:
1.191 harris41 14472: =item *
14473:
1.243 albertel 14474: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14475:
14476: =item *
14477:
1.243 albertel 14478: logthis() : append message to the normal lonnet.log file, it gets
14479: preiodically rolled over and deleted.
1.191 harris41 14480:
14481: =item *
14482:
1.243 albertel 14483: logperm() : append a permanent message to lonnet.perm.log, this log
14484: file never gets deleted by any automated portion of the system, only
14485: messages of critical importance should go in here.
14486:
1.1119 foxr 14487:
1.243 albertel 14488: =back
14489:
14490: =head2 General File Helper Routines
14491:
14492: =over 4
1.191 harris41 14493:
14494: =item *
14495:
1.481 raeburn 14496: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14497: (a) files in /uploaded
14498: (i) If a local copy of the file exists -
14499: compares modification date of local copy with last-modified date for
14500: definitive version stored on home server for course. If local copy is
14501: stale, requests a new version from the home server and stores it.
14502: If the original has been removed from the home server, then local copy
14503: is unlinked.
14504: (ii) If local copy does not exist -
14505: requests the file from the home server and stores it.
14506:
14507: If $caller is 'uploadrep':
14508: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14509: for request for files originally uploaded via DOCS.
14510: - returns 'ok' if fresh local copy now available, -1 otherwise.
14511:
14512: Otherwise:
14513: This indicates a call from the content generation phase of the request.
14514: - returns the entire contents of the file or -1.
14515:
14516: (b) files in /res
14517: - returns the entire contents of a file or -1;
14518: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14519:
1.712 albertel 14520:
14521: =item *
14522:
14523: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14524: reference
14525:
14526: returns either a stat() list of data about the file or an empty list
14527: if the file doesn't exist or couldn't find out about it (connection
14528: problems or user unknown)
14529:
1.191 harris41 14530: =item *
14531:
1.243 albertel 14532: filelocation($dir,$file) : returns file system location of a file
14533: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14534: directory that relative $file lookups are to looked in ($dir of /a/dir
14535: and a file of ../bob will become /a/bob)
1.191 harris41 14536:
14537: =item *
14538:
14539: hreflocation($dir,$file) : returns file system location or a URL; same as
14540: filelocation except for hrefs
14541:
14542: =item *
14543:
1.1172.2.49 raeburn 14544: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14545: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14546:
1.243 albertel 14547: =back
14548:
1.608 albertel 14549: =head2 Usererfile file routines (/uploaded*)
14550:
14551: =over 4
14552:
14553: =item *
14554:
14555: userfileupload(): main rotine for putting a file in a user or course's
14556: filespace, arguments are,
14557:
1.620 albertel 14558: formname - required - this is the name of the element in $env where the
1.608 albertel 14559: filename, and the contents of the file to create/modifed exist
1.620 albertel 14560: the filename is in $env{'form.'.$formname.'.filename'} and the
14561: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14562: context - if coursedoc, store the file in the course of the active role
14563: of the current user;
14564: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14565: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14566: subdir - required - subdirectory to put the file in under ../userfiles/
14567: if undefined, it will be placed in "unknown"
14568:
14569: (This routine calls clean_filename() to remove any dangerous
14570: characters from the filename, and then calls finuserfileupload() to
14571: complete the transaction)
14572:
14573: returns either the url of the uploaded file (/uploaded/....) if successful
14574: and /adm/notfound.html if unsuccessful
14575:
14576: =item *
14577:
14578: clean_filename(): routine for cleaing a filename up for storage in
14579: userfile space, argument is:
14580:
14581: filename - proposed filename
14582:
14583: returns: the new clean filename
14584:
14585: =item *
14586:
1.1090 raeburn 14587: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14588: userspace, probably shouldn't be called directly
14589:
14590: docuname: username or courseid of destination for the file
14591: docudom: domain of user/course of destination for the file
14592: formname: same as for userfileupload()
1.1090 raeburn 14593: fname: filename (including subdirectories) for the file
14594: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14595: allfiles: reference to hash used to store objects found by parser
14596: codebase: reference to hash used for codebases of java objects found by parser
14597: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14598: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14599: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14600: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14601: context: if 'overwrite', will move the uploaded file from its temporary location to
14602: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14603: mimetype: reference to scalar to accommodate mime type determined
14604: from File::MMagic if $parser = parse.
1.608 albertel 14605:
14606: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14607: and /adm/notfound.html if unsuccessful (or an error message if context
14608: was 'overwrite').
14609:
1.608 albertel 14610:
14611: =item *
14612:
14613: renameuserfile(): renames an existing userfile to a new name
14614:
14615: Args:
14616: docuname: username or courseid of destination for the file
14617: docudom: domain of user/course of destination for the file
14618: old: current file name (including any subdirs under userfiles)
14619: new: desired file name (including any subdirs under userfiles)
14620:
14621: =item *
14622:
14623: mkdiruserfile(): creates a directory is a userfiles dir
14624:
14625: Args:
14626: docuname: username or courseid of destination for the file
14627: docudom: domain of user/course of destination for the file
14628: dir: dir to create (including any subdirs under userfiles)
14629:
14630: =item *
14631:
14632: removeuserfile(): removes a file that exists in userfiles
14633:
14634: Args:
14635: docuname: username or courseid of destination for the file
14636: docudom: domain of user/course of destination for the file
14637: fname: filname to delete (including any subdirs under userfiles)
14638:
14639: =item *
14640:
14641: removeuploadedurl(): convience function for removeuserfile()
14642:
14643: Args:
14644: url: a full /uploaded/... url to delete
14645:
1.747 albertel 14646: =item *
14647:
14648: get_portfile_permissions():
14649: Args:
14650: domain: domain of user or course contain the portfolio files
14651: user: name of user or num of course contain the portfolio files
14652: Returns:
14653: hashref of a dump of the proper file_permissions.db
14654:
14655:
14656: =item *
14657:
14658: get_access_controls():
14659:
14660: Args:
14661: current_permissions: the hash ref returned from get_portfile_permissions()
14662: group: (optional) the group you want the files associated with
14663: file: (optional) the file you want access info on
14664:
14665: Returns:
1.749 raeburn 14666: a hash (keys are file names) of hashes containing
14667: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14668: values are XML containing access control settings (see below)
1.747 albertel 14669:
14670: Internal notes:
14671:
1.749 raeburn 14672: access controls are stored in file_permissions.db as key=value pairs.
14673: key -> path to file/file_name\0uniqueID:scope_end_start
14674: where scope -> public,guest,course,group,domains or users.
14675: end -> UNIX time for end of access (0 -> no end date)
14676: start -> UNIX time for start of access
14677:
14678: value -> XML description of access control
14679: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14680: <start></start>
14681: <end></end>
14682:
14683: <password></password> for scope type = guest
14684:
14685: <domain></domain> for scope type = course or group
14686: <number></number>
14687: <roles id="">
14688: <role></role>
14689: <access></access>
14690: <section></section>
14691: <group></group>
14692: </roles>
14693:
14694: <dom></dom> for scope type = domains
14695:
14696: <users> for scope type = users
14697: <user>
14698: <uname></uname>
14699: <udom></udom>
14700: </user>
14701: </users>
14702: </scope>
14703:
14704: Access data is also aggregated for each file in an additional key=value pair:
14705: key -> path to file/file_name\0accesscontrol
14706: value -> reference to hash
14707: hash contains key = value pairs
14708: where key = uniqueID:scope_end_start
14709: value = UNIX time record was last updated
14710:
14711: Used to improve speed of look-ups of access controls for each file.
14712:
14713: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14714:
1.1172.2.13 raeburn 14715: =item *
14716:
1.749 raeburn 14717: modify_access_controls():
14718:
14719: Modifies access controls for a portfolio file
14720: Args
14721: 1. file name
14722: 2. reference to hash of required changes,
14723: 3. domain
14724: 4. username
14725: where domain,username are the domain of the portfolio owner
14726: (either a user or a course)
14727:
14728: Returns:
14729: 1. result of additions or updates ('ok' or 'error', with error message).
14730: 2. result of deletions ('ok' or 'error', with error message).
14731: 3. reference to hash of any new or updated access controls.
14732: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14733: key = integer (inbound ID)
1.1172.2.13 raeburn 14734: value = uniqueID
14735:
14736: =item *
14737:
14738: get_timebased_id():
14739:
14740: Attempts to get a unique timestamp-based suffix for use with items added to a
14741: course via the Course Editor (e.g., folders, composite pages,
14742: group bulletin boards).
14743:
14744: Args: (first three required; six others optional)
14745:
14746: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14747: docssequence, or name of group
14748:
14749: 2. keyid (alphanumeric): name of temporary locking key in hash,
14750: e.g., num, boardids
14751:
14752: 3. namespace: name of gdbm file used to store suffixes already assigned;
14753: file will be named nohist_namespace.db
14754:
14755: 4. cdom: domain of course; default is current course domain from %env
14756:
14757: 5. cnum: course number; default is current course number from %env
14758:
14759: 6. idtype: set to concat if an additional digit is to be appended to the
14760: unix timestamp to form the suffix, if the plain timestamp is already
14761: in use. Default is to not do this, but simply increment the unix
14762: timestamp by 1 until a unique key is obtained.
14763:
14764: 7. who: holder of locking key; defaults to user:domain for user.
14765:
14766: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14767: retrying); default is 3.
14768:
14769: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14770:
14771: Returns:
14772:
14773: 1. suffix obtained (numeric)
14774:
14775: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14776:
14777: 3. error: contains (localized) error message if an error occurred.
14778:
1.747 albertel 14779:
1.608 albertel 14780: =back
14781:
1.243 albertel 14782: =head2 HTTP Helper Routines
14783:
14784: =over 4
14785:
1.191 harris41 14786: =item *
14787:
14788: escape() : unpack non-word characters into CGI-compatible hex codes
14789:
14790: =item *
14791:
14792: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14793:
1.243 albertel 14794: =back
14795:
14796: =head1 PRIVATE SUBROUTINES
14797:
14798: =head2 Underlying communication routines (Shouldn't call)
14799:
14800: =over 4
14801:
14802: =item *
14803:
14804: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14805:
14806: =item *
14807:
14808: reply() : uses subreply to send a message to remote machine, logs all failures
14809:
14810: =item *
14811:
14812: critical() : passes a critical message to another server; if cannot
14813: get through then place message in connection buffer directory and
14814: returns con_delayed, if incapable of saving message, returns
14815: con_failed
14816:
14817: =item *
14818:
14819: reconlonc() : tries to reconnect lonc client processes.
14820:
14821: =back
14822:
14823: =head2 Resource Access Logging
14824:
14825: =over 4
14826:
14827: =item *
14828:
14829: flushcourselogs() : flush (save) buffer logs and access logs
14830:
14831: =item *
14832:
14833: courselog($what) : save message for course in hash
14834:
14835: =item *
14836:
14837: courseacclog($what) : save message for course using &courselog(). Perform
14838: special processing for specific resource types (problems, exams, quizzes, etc).
14839:
1.191 harris41 14840: =item *
14841:
14842: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14843: as a PerlChildExitHandler
1.243 albertel 14844:
14845: =back
14846:
14847: =head2 Other
14848:
14849: =over 4
14850:
14851: =item *
14852:
14853: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14854:
14855: =back
14856:
14857: =cut
1.877 foxr 14858:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>