Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.93.4.3
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.93.4 3(raebur 4:7): # $Id: lonnet.pm,v 1.1172.2.93.4.2 2017/06/22 02:11:28 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") {
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.448 albertel 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.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
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.448 albertel 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;
479: if (open($dfh,">$dfilename")) {
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;
488: if (open($dfh,"<$dfilename")) {
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.93.4 3(raebur 604:7): 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.93.4 3(raebur 619:7): if (!-e "$lonidsdir/$handle.id") {
620:7): if ((ref($domref)) && ($name eq 'lonID') &&
621:7): ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
622:7): my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
623:7): if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
624:7): $$domref = $possudom;
625:7): }
626:7): }
627:7): return undef;
628:7): }
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: }
698: my $opened = open(my $env_file,'+<',$env{'user.environment'});
699: if ($opened
700: && &timed_flock($env_file,LOCK_EX)
701: &&
702: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
703: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
704: while (my ($key,$value) = each(%{$newenv})) {
705: $disk_env{$key} = $value;
706: }
707: untie(%disk_env);
1.35 www 708: }
1.191 harris41 709: }
1.56 www 710: return 'ok';
711: }
712: # ----------------------------------------------------- Delete from Environment
713:
714: sub delenv {
1.1104 raeburn 715: my ($delthis,$regexp,$roles) = @_;
716: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
717: my $refused = 1;
718: if (ref($roles) eq 'ARRAY') {
719: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
720: if (grep(/^\Q$role\E$/,@{$roles})) {
721: $refused = 0;
722: }
723: }
724: if ($refused) {
725: &logthis("<font color=\"blue\">WARNING: ".
726: "Attempt to delete from environment ".$delthis);
727: return 'error';
728: }
1.56 www 729: }
1.917 albertel 730: my $opened = open(my $env_file,'+<',$env{'user.environment'});
731: if ($opened
1.915 albertel 732: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 733: &&
734: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
735: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 736: foreach my $key (keys(%disk_env)) {
1.987 raeburn 737: if ($regexp) {
738: if ($key=~/^$delthis/) {
739: delete($env{$key});
740: delete($disk_env{$key});
741: }
742: } else {
743: if ($key=~/^\Q$delthis\E/) {
744: delete($env{$key});
745: delete($disk_env{$key});
746: }
747: }
1.448 albertel 748: }
1.783 albertel 749: untie(%disk_env);
1.5 www 750: }
751: return 'ok';
1.369 albertel 752: }
753:
1.790 albertel 754: sub get_env_multiple {
755: my ($name) = @_;
756: my @values;
757: if (defined($env{$name})) {
758: # exists is it an array
759: if (ref($env{$name})) {
760: @values=@{ $env{$name} };
761: } else {
762: $values[0]=$env{$name};
763: }
764: }
765: return(@values);
766: }
767:
1.958 www 768: # ------------------------------------------------------------------- Locking
769:
770: sub set_lock {
771: my ($text)=@_;
772: $locknum++;
773: my $id=$$.'-'.$locknum;
774: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
775: 'session.lock.'.$id => $text});
776: return $id;
777: }
778:
779: sub get_locks {
780: my $num=0;
781: my %texts=();
782: foreach my $lock (split(/\,/,$env{'session.locks'})) {
783: if ($lock=~/\w/) {
784: $num++;
785: $texts{$lock}=$env{'session.lock.'.$lock};
786: }
787: }
788: return ($num,%texts);
789: }
790:
791: sub remove_lock {
792: my ($id)=@_;
793: my $newlocks='';
794: foreach my $lock (split(/\,/,$env{'session.locks'})) {
795: if (($lock=~/\w/) && ($lock ne $id)) {
796: $newlocks.=','.$lock;
797: }
798: }
799: &appenv({'session.locks' => $newlocks});
800: &delenv('session.lock.'.$id);
801: }
802:
803: sub remove_all_locks {
804: my $activelocks=$env{'session.locks'};
805: foreach my $lock (split(/\,/,$env{'session.locks'})) {
806: if ($lock=~/\w/) {
807: &remove_lock($lock);
808: }
809: }
810: }
811:
812:
1.369 albertel 813: # ------------------------------------------ Find out current server userload
814: sub userload {
815: my $numusers=0;
816: {
817: opendir(LONIDS,$perlvar{'lonIDsDir'});
818: my $filename;
819: my $curtime=time;
820: while ($filename=readdir(LONIDS)) {
1.925 albertel 821: next if ($filename eq '.' || $filename eq '..');
822: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 823: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 824: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 825: }
826: closedir(LONIDS);
827: }
828: my $userloadpercent=0;
829: my $maxuserload=$perlvar{'lonUserLoadLim'};
830: if ($maxuserload) {
1.371 albertel 831: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 832: }
1.372 albertel 833: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 834: return $userloadpercent;
1.283 www 835: }
836:
1.1 albertel 837: # ------------------------------ Find server with least workload from spare.tab
1.11 www 838:
1.1 albertel 839: sub spareserver {
1.1083 raeburn 840: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 841: my $spare_server;
1.370 albertel 842: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 843: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
844: : $userloadpercent;
1.1083 raeburn 845: my ($uint_dom,$remotesessions);
846: if (($udom ne '') && (&domain($udom) ne '')) {
847: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
848: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
849: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
850: $remotesessions = $udomdefaults{'remotesessions'};
851: }
1.1123 raeburn 852: my $spareshash = &this_host_spares($udom);
853: if (ref($spareshash) eq 'HASH') {
854: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
855: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 856: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
857: $try_server));
1.1123 raeburn 858: ($spare_server, $lowest_load) =
859: &compare_server_load($try_server, $spare_server, $lowest_load);
860: }
1.1083 raeburn 861: }
1.784 albertel 862:
1.1123 raeburn 863: my $found_server = ($spare_server ne '' && $lowest_load < 100);
864:
865: if (!$found_server) {
866: if (ref($spareshash->{'default'}) eq 'ARRAY') {
867: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 868: next unless (&spare_can_host($udom,$uint_dom,
869: $remotesessions,$try_server));
1.1123 raeburn 870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
1.1172.2.41 raeburn 893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
1.784 albertel 904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 909: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
1.411 albertel 918: } else {
1.784 albertel 919: $load = $loadans;
1.411 albertel 920: }
1.784 albertel 921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
1.370 albertel 928: }
1.784 albertel 929: return ($spare_server,$lowest_load);
1.202 matthew 930: }
1.914 albertel 931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
1.1123 raeburn 935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
1.914 albertel 947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
1.1076 raeburn 961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
1.1172.2.47 raeburn 964: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 966: my %servers = &get_servers($udom);
1.1076 raeburn 967: my $lowest_load = 30000;
1.1172.2.47 raeburn 968: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
969: if ($skiploadbal) {
970: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
971: unless (defined($cached)) {
972: my $cachetime = 60*60*24;
973: my %domconfig =
974: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
975: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
976: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
977: $cachetime);
978: }
979: }
980: }
1.1076 raeburn 981: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 982: my $loginvia;
1.1172.2.47 raeburn 983: if ($skiploadbal) {
984: if (ref($balancers) eq 'HASH') {
985: next if (exists($balancers->{$lonhost}));
986: }
987: }
1.1115 raeburn 988: if ($checkloginvia) {
989: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 990: if ($loginvia) {
991: my ($server,$path) = split(/:/,$loginvia);
992: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 993: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 994: if ($login_host eq $server) {
995: $portal_path = $path;
1.1151 raeburn 996: $isredirect = 1;
1.1116 raeburn 997: }
998: } else {
999: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1000: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1001: if ($login_host eq $lonhost) {
1002: $portal_path = '';
1.1151 raeburn 1003: $isredirect = '';
1.1116 raeburn 1004: }
1005: }
1006: } else {
1.1076 raeburn 1007: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1008: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1009: }
1010: }
1011: if ($login_host ne '') {
1.1116 raeburn 1012: $hostname = &hostname($login_host);
1.1076 raeburn 1013: }
1.1172.2.88 raeburn 1014: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1015: }
1016:
1.202 matthew 1017: # --------------------------------------------- Try to change a user's password
1018:
1019: sub changepass {
1.799 raeburn 1020: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1021: $currentpass = &escape($currentpass);
1022: $newpass = &escape($newpass);
1.1030 raeburn 1023: my $lonhost = $perlvar{'lonHostID'};
1024: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1025: $server);
1026: if (! $answer) {
1027: &logthis("No reply on password change request to $server ".
1028: "by $uname in domain $udom.");
1029: } elsif ($answer =~ "^ok") {
1030: &logthis("$uname in $udom successfully changed their password ".
1031: "on $server.");
1032: } elsif ($answer =~ "^pwchange_failure") {
1033: &logthis("$uname in $udom was unable to change their password ".
1034: "on $server. The action was blocked by either lcpasswd ".
1035: "or pwchange");
1036: } elsif ($answer =~ "^non_authorized") {
1037: &logthis("$uname in $udom did not get their password correct when ".
1038: "attempting to change it on $server.");
1039: } elsif ($answer =~ "^auth_mode_error") {
1040: &logthis("$uname in $udom attempted to change their password despite ".
1041: "not being locally or internally authenticated on $server.");
1042: } elsif ($answer =~ "^unknown_user") {
1043: &logthis("$uname in $udom attempted to change their password ".
1044: "on $server but were unable to because $server is not ".
1045: "their home server.");
1046: } elsif ($answer =~ "^refused") {
1047: &logthis("$server refused to change $uname in $udom password because ".
1048: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1049: } elsif ($answer =~ "invalid_client") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1052: }
1053: return $answer;
1.1 albertel 1054: }
1055:
1.169 harris41 1056: # ----------------------- Try to determine user's current authentication scheme
1057:
1058: sub queryauthenticate {
1059: my ($uname,$udom)=@_;
1.456 albertel 1060: my $uhome=&homeserver($uname,$udom);
1061: if (!$uhome) {
1062: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1063: return 'no_host';
1064: }
1065: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1066: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1067: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1068: }
1.456 albertel 1069: return $answer;
1.169 harris41 1070: }
1071:
1.1 albertel 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1073:
1.1 albertel 1074: sub authenticate {
1.1073 raeburn 1075: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1076: $upass=&escape($upass);
1077: $uname= &LONCAPA::clean_username($uname);
1.836 www 1078: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1079: my $newhome;
1.836 www 1080: if ((!$uhome) || ($uhome eq 'no_host')) {
1081: # Maybe the machine was offline and only re-appeared again recently?
1082: &reconlonc();
1083: # One more
1.952 raeburn 1084: $uhome=&homeserver($uname,$udom,1);
1085: if (($uhome eq 'no_host') && $checkdefauth) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $newhome=&domain($udom,'primary');
1088: }
1089: if ($newhome ne '') {
1090: $uhome = $newhome;
1091: }
1092: }
1.836 www 1093: if ((!$uhome) || ($uhome eq 'no_host')) {
1094: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1095: return 'no_host';
1096: }
1.1 albertel 1097: }
1.1073 raeburn 1098: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1099: if ($answer eq 'authorized') {
1.952 raeburn 1100: if ($newhome) {
1101: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1102: return 'no_account_on_host';
1103: } else {
1104: &logthis("User $uname at $udom authorized by $uhome");
1105: return $uhome;
1106: }
1.471 albertel 1107: }
1108: if ($answer eq 'non_authorized') {
1109: &logthis("User $uname at $udom rejected by $uhome");
1110: return 'no_host';
1.9 www 1111: }
1.471 albertel 1112: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1113: return 'no_host';
1114: }
1115:
1.1073 raeburn 1116: sub can_host_session {
1.1074 raeburn 1117: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1118: my $canhost = 1;
1.1074 raeburn 1119: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1120: if (ref($remotesessions) eq 'HASH') {
1121: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1122: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1123: $canhost = 0;
1124: } else {
1125: $canhost = 1;
1126: }
1127: }
1128: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1129: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1130: $canhost = 1;
1131: } else {
1132: $canhost = 0;
1133: }
1134: }
1135: if ($canhost) {
1136: if ($remotesessions->{'version'} ne '') {
1137: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1138: if ($reqmajor ne '' && $reqminor ne '') {
1139: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1140: my $major = $1;
1141: my $minor = $2;
1142: if (($major < $reqmajor ) ||
1143: (($major == $reqmajor) && ($minor < $reqminor))) {
1144: $canhost = 0;
1145: }
1146: } else {
1147: $canhost = 0;
1148: }
1149: }
1150: }
1151: }
1152: }
1153: if ($canhost) {
1154: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1155: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1156: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1157: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1158: if (($uint_dom ne '') &&
1159: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1160: $canhost = 0;
1161: } else {
1162: $canhost = 1;
1163: }
1164: }
1165: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1166: if (($uint_dom ne '') &&
1167: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: }
1174: }
1175: return $canhost;
1176: }
1177:
1.1083 raeburn 1178: sub spare_can_host {
1179: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1180: my $canhost=1;
1.1172.2.62 raeburn 1181: my $try_server_hostname = &hostname($try_server);
1182: my $serverhomeID = &get_server_homeID($try_server_hostname);
1183: my $serverhomedom = &host_domain($serverhomeID);
1184: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1185: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1186: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1187: $canhost = 0;
1188: }
1189: }
1190: if (($canhost) && ($uint_dom)) {
1191: my @intdoms;
1192: my $internet_names = &get_internet_names($try_server);
1193: if (ref($internet_names) eq 'ARRAY') {
1194: @intdoms = @{$internet_names};
1195: }
1196: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1197: my $remoterev = &get_server_loncaparev(undef,$try_server);
1198: $canhost = &can_host_session($udom,$try_server,$remoterev,
1199: $remotesessions,
1200: $defdomdefaults{'hostedsessions'});
1201: }
1.1083 raeburn 1202: }
1203: return $canhost;
1204: }
1205:
1.1123 raeburn 1206: sub this_host_spares {
1207: my ($dom) = @_;
1.1126 raeburn 1208: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1209: my @hosts = ¤t_machine_ids();
1210: foreach my $lonhost (@hosts) {
1211: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1212: $dom_in_use = $dom;
1213: $lonhost_in_use = $lonhost;
1.1123 raeburn 1214: last;
1215: }
1216: }
1.1126 raeburn 1217: if ($dom_in_use ne '') {
1218: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1219: }
1220: if (ref($result) ne 'HASH') {
1221: $lonhost_in_use = $perlvar{'lonHostID'};
1222: $dom_in_use = &host_domain($lonhost_in_use);
1223: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1224: if (ref($result) ne 'HASH') {
1225: $result = \%spareid;
1226: }
1227: }
1228: return $result;
1229: }
1230:
1231: sub spares_for_offload {
1232: my ($dom_in_use,$lonhost_in_use) = @_;
1233: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1234: if (defined($cached)) {
1235: return $result;
1236: } else {
1.1126 raeburn 1237: my $cachetime = 60*60*24;
1238: my %domconfig =
1239: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1240: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1241: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1242: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1243: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1244: }
1245: }
1246: }
1247: }
1.1126 raeburn 1248: return;
1.1123 raeburn 1249: }
1250:
1.1129 raeburn 1251: sub get_lonbalancer_config {
1252: my ($servers) = @_;
1253: my ($currbalancer,$currtargets);
1254: if (ref($servers) eq 'HASH') {
1255: foreach my $server (keys(%{$servers})) {
1256: my %what = (
1257: spareid => 1,
1258: perlvar => 1,
1259: );
1260: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1261: if ($result eq 'ok') {
1262: if (ref($returnhash) eq 'HASH') {
1263: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1264: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1265: $currbalancer = $server;
1266: $currtargets = {};
1267: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1268: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1269: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1270: }
1271: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1272: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1273: }
1274: }
1275: last;
1276: }
1277: }
1278: }
1279: }
1280: }
1281: }
1282: return ($currbalancer,$currtargets);
1283: }
1284:
1285: sub check_loadbalancing {
1.1172.2.88 raeburn 1286: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1287: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1288: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1289: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1290: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1291: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1292: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1293: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1294: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1295: my $domneedscache;
1.1129 raeburn 1296: my $cachetime = 60*60*24;
1297:
1298: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1299: $dom_in_use = $udom;
1300: $homeintdom = 1;
1301: } else {
1302: $dom_in_use = $serverhomedom;
1303: }
1304: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1305: unless (defined($cached)) {
1306: my %domconfig =
1307: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1308: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1309: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1310: } else {
1311: $domneedscache = $dom_in_use;
1.1129 raeburn 1312: }
1313: }
1314: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1315: ($is_balancer,$currtargets,$currrules) =
1316: &check_balancer_result($result,@hosts);
1.1129 raeburn 1317: if ($is_balancer) {
1318: if (ref($currrules) eq 'HASH') {
1319: if ($homeintdom) {
1320: if ($uname ne '') {
1321: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1322: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1323: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1324: $rule_in_effect = $currrules->{'_LC_author'};
1325: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1326: $rule_in_effect = $currrules->{'_LC_adv'}
1327: }
1328: }
1329: if ($rule_in_effect eq '') {
1330: my %userenv = &userenvironment($udom,$uname,'inststatus');
1331: if ($userenv{'inststatus'} ne '') {
1332: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1333: my ($othertitle,$usertypes,$types) =
1334: &Apache::loncommon::sorted_inst_types($udom);
1335: if (ref($types) eq 'ARRAY') {
1336: foreach my $type (@{$types}) {
1337: if (grep(/^\Q$type\E$/,@statuses)) {
1338: if (exists($currrules->{$type})) {
1339: $rule_in_effect = $currrules->{$type};
1340: }
1341: }
1342: }
1343: }
1344: } else {
1345: if (exists($currrules->{'default'})) {
1346: $rule_in_effect = $currrules->{'default'};
1347: }
1348: }
1349: }
1350: } else {
1351: if (exists($currrules->{'default'})) {
1352: $rule_in_effect = $currrules->{'default'};
1353: }
1354: }
1355: } else {
1356: if ($currrules->{'_LC_external'} ne '') {
1357: $rule_in_effect = $currrules->{'_LC_external'};
1358: }
1359: }
1360: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1361: $uname,$udom);
1362: }
1363: }
1364: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1365: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1366: unless (defined($cached)) {
1367: my %domconfig =
1368: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1369: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1370: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1371: } else {
1372: $domneedscache = $serverhomedom;
1.1129 raeburn 1373: }
1374: }
1375: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1376: ($is_balancer,$currtargets,$currrules) =
1377: &check_balancer_result($result,@hosts);
1378: if ($is_balancer) {
1.1129 raeburn 1379: if (ref($currrules) eq 'HASH') {
1380: if ($currrules->{'_LC_internetdom'} ne '') {
1381: $rule_in_effect = $currrules->{'_LC_internetdom'};
1382: }
1383: }
1384: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1385: $uname,$udom);
1386: }
1387: } else {
1388: if ($perlvar{'lonBalancer'} eq 'yes') {
1389: $is_balancer = 1;
1390: $offloadto = &this_host_spares($dom_in_use);
1391: }
1.1172.2.75 raeburn 1392: unless (defined($cached)) {
1393: $domneedscache = $serverhomedom;
1394: }
1.1129 raeburn 1395: }
1396: } else {
1397: if ($perlvar{'lonBalancer'} eq 'yes') {
1398: $is_balancer = 1;
1399: $offloadto = &this_host_spares($dom_in_use);
1400: }
1.1172.2.75 raeburn 1401: unless (defined($cached)) {
1402: $domneedscache = $serverhomedom;
1403: }
1404: }
1405: if ($domneedscache) {
1406: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1407: }
1.1172.2.5 raeburn 1408: if ($is_balancer) {
1409: my $lowest_load = 30000;
1410: if (ref($offloadto) eq 'HASH') {
1411: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1412: foreach my $try_server (@{$offloadto->{'primary'}}) {
1413: ($otherserver,$lowest_load) =
1414: &compare_server_load($try_server,$otherserver,$lowest_load);
1415: }
1.1129 raeburn 1416: }
1.1172.2.5 raeburn 1417: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1418:
1.1172.2.5 raeburn 1419: if (!$found_server) {
1420: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1421: foreach my $try_server (@{$offloadto->{'default'}}) {
1422: ($otherserver,$lowest_load) =
1423: &compare_server_load($try_server,$otherserver,$lowest_load);
1424: }
1425: }
1426: }
1427: } elsif (ref($offloadto) eq 'ARRAY') {
1428: if (@{$offloadto} == 1) {
1429: $otherserver = $offloadto->[0];
1430: } elsif (@{$offloadto} > 1) {
1431: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1432: ($otherserver,$lowest_load) =
1433: &compare_server_load($try_server,$otherserver,$lowest_load);
1434: }
1435: }
1436: }
1.1172.2.88 raeburn 1437: unless ($caller eq 'login') {
1438: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1439: $is_balancer = 0;
1440: if ($uname ne '' && $udom ne '') {
1441: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5 raeburn 1442:
1.1172.2.88 raeburn 1443: &appenv({'user.loadbalexempt' => $lonhost,
1444: 'user.loadbalcheck.time' => time});
1445: }
1.1172.2.5 raeburn 1446: }
1.1129 raeburn 1447: }
1448: }
1449: }
1450: return ($is_balancer,$otherserver);
1451: }
1452:
1.1172.2.12 raeburn 1453: sub check_balancer_result {
1454: my ($result,@hosts) = @_;
1455: my ($is_balancer,$currtargets,$currrules);
1456: if (ref($result) eq 'HASH') {
1457: if ($result->{'lonhost'} ne '') {
1458: my $currbalancer = $result->{'lonhost'};
1459: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1460: $is_balancer = 1;
1461: $currtargets = $result->{'targets'};
1462: $currrules = $result->{'rules'};
1463: }
1464: } else {
1465: foreach my $key (keys(%{$result})) {
1466: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1467: (ref($result->{$key}) eq 'HASH')) {
1468: $is_balancer = 1;
1469: $currrules = $result->{$key}{'rules'};
1470: $currtargets = $result->{$key}{'targets'};
1471: last;
1472: }
1473: }
1474: }
1475: }
1476: return ($is_balancer,$currtargets,$currrules);
1477: }
1478:
1.1129 raeburn 1479: sub get_loadbalancer_targets {
1480: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1481: my $offloadto;
1.1172.2.4 raeburn 1482: if ($rule_in_effect eq 'none') {
1483: return [$perlvar{'lonHostID'}];
1484: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1485: $offloadto = $currtargets;
1486: } else {
1487: if ($rule_in_effect eq 'homeserver') {
1488: my $homeserver = &homeserver($uname,$udom);
1489: if ($homeserver ne 'no_host') {
1490: $offloadto = [$homeserver];
1491: }
1492: } elsif ($rule_in_effect eq 'externalbalancer') {
1493: my %domconfig =
1494: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1495: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1496: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1497: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1498: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1499: }
1500: }
1501: } else {
1.1172.2.7 raeburn 1502: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1503: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1504: if (&hostname($remotebalancer) ne '') {
1505: $offloadto = [$remotebalancer];
1506: }
1507: }
1508: } elsif (&hostname($rule_in_effect) ne '') {
1509: $offloadto = [$rule_in_effect];
1510: }
1511: }
1512: return $offloadto;
1513: }
1514:
1.1127 raeburn 1515: sub internet_dom_servers {
1516: my ($dom) = @_;
1517: my (%uniqservers,%servers);
1518: my $primaryserver = &hostname(&domain($dom,'primary'));
1519: my @machinedoms = &machine_domains($primaryserver);
1520: foreach my $mdom (@machinedoms) {
1521: my %currservers = %servers;
1522: my %server = &get_servers($mdom);
1523: %servers = (%currservers,%server);
1524: }
1525: my %by_hostname;
1526: foreach my $id (keys(%servers)) {
1527: push(@{$by_hostname{$servers{$id}}},$id);
1528: }
1529: foreach my $hostname (sort(keys(%by_hostname))) {
1530: if (@{$by_hostname{$hostname}} > 1) {
1531: my $match = 0;
1532: foreach my $id (@{$by_hostname{$hostname}}) {
1533: if (&host_domain($id) eq $dom) {
1534: $uniqservers{$id} = $hostname;
1535: $match = 1;
1536: }
1537: }
1538: unless ($match) {
1539: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1540: }
1541: } else {
1542: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1543: }
1544: }
1545: return %uniqservers;
1546: }
1547:
1.1 albertel 1548: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1549:
1.599 albertel 1550: my %homecache;
1.1 albertel 1551: sub homeserver {
1.230 stredwic 1552: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1553: my $index="$uname:$udom";
1.426 albertel 1554:
1.599 albertel 1555: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1556:
1557: my %servers = &get_servers($udom,'library');
1558: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1559: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1560: exists($badServerCache{$tryserver}));
1.841 albertel 1561:
1562: my $answer=reply("home:$udom:$uname",$tryserver);
1563: if ($answer eq 'found') {
1564: delete($badServerCache{$tryserver});
1565: return $homecache{$index}=$tryserver;
1566: } elsif ($answer eq 'no_host') {
1567: $badServerCache{$tryserver}=1;
1568: }
1.1 albertel 1569: }
1570: return 'no_host';
1.70 www 1571: }
1572:
1573: # ------------------------------------- Find the usernames behind a list of IDs
1574:
1575: sub idget {
1576: my ($udom,@ids)=@_;
1577: my %returnhash=();
1578:
1.841 albertel 1579: my %servers = &get_servers($udom,'library');
1580: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1581: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1582: $idlist=~tr/A-Z/a-z/;
1583: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1584: my @answer=();
1585: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1586: @answer=split(/\&/,$reply);
1587: } ;
1588: my $i;
1589: for ($i=0;$i<=$#ids;$i++) {
1590: if ($answer[$i]) {
1.1172.2.73 raeburn 1591: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1592: }
1593: }
1594: }
1.70 www 1595: return %returnhash;
1596: }
1597:
1598: # ------------------------------------- Find the IDs behind a list of usernames
1599:
1600: sub idrget {
1601: my ($udom,@unames)=@_;
1602: my %returnhash=();
1.800 albertel 1603: foreach my $uname (@unames) {
1604: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1605: }
1.70 www 1606: return %returnhash;
1607: }
1608:
1609: # ------------------------------- Store away a list of names and associated IDs
1610:
1611: sub idput {
1612: my ($udom,%ids)=@_;
1613: my %servers=();
1.800 albertel 1614: foreach my $uname (keys(%ids)) {
1615: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1616: my $uhom=&homeserver($uname,$udom);
1.70 www 1617: if ($uhom ne 'no_host') {
1.800 albertel 1618: my $id=&escape($ids{$uname});
1.70 www 1619: $id=~tr/A-Z/a-z/;
1.800 albertel 1620: my $esc_unam=&escape($uname);
1.70 www 1621: if ($servers{$uhom}) {
1.800 albertel 1622: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1623: } else {
1.800 albertel 1624: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1625: }
1626: }
1.191 harris41 1627: }
1.800 albertel 1628: foreach my $server (keys(%servers)) {
1629: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1630: }
1.344 www 1631: }
1632:
1.1172.2.30 raeburn 1633: # ---------------------------------------- Delete unwanted IDs from ids.db file
1634:
1635: sub iddel {
1636: my ($udom,$idshashref,$uhome)=@_;
1637: my %result=();
1638: unless (ref($idshashref) eq 'HASH') {
1639: return %result;
1640: }
1641: my %servers=();
1642: while (my ($id,$uname) = each(%{$idshashref})) {
1643: my $uhom;
1644: if ($uhome) {
1645: $uhom = $uhome;
1646: } else {
1647: $uhom=&homeserver($uname,$udom);
1648: }
1649: if ($uhom ne 'no_host') {
1650: if ($servers{$uhom}) {
1651: $servers{$uhom}.='&'.&escape($id);
1652: } else {
1653: $servers{$uhom}=&escape($id);
1654: }
1655: }
1656: }
1657: foreach my $server (keys(%servers)) {
1658: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1659: }
1660: return %result;
1661: }
1662:
1.1023 raeburn 1663: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1664: sub dump_dom {
1.1165 droeschl 1665: my ($namespace, $udom, $regexp) = @_;
1666:
1667: $udom ||= $env{'user.domain'};
1668:
1669: return () unless $udom;
1670:
1671: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1672: }
1673:
1.1023 raeburn 1674: # ------------------------------------------ get items from domain db files
1.806 raeburn 1675:
1676: sub get_dom {
1.860 raeburn 1677: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1678: return if ($udom eq 'public');
1.806 raeburn 1679: my $items='';
1680: foreach my $item (@$storearr) {
1681: $items.=&escape($item).'&';
1682: }
1683: $items=~s/\&$//;
1.860 raeburn 1684: if (!$udom) {
1685: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1686: return if ($udom eq 'public');
1.860 raeburn 1687: if (defined(&domain($udom,'primary'))) {
1688: $uhome=&domain($udom,'primary');
1689: } else {
1.874 albertel 1690: undef($uhome);
1.860 raeburn 1691: }
1692: } else {
1693: if (!$uhome) {
1694: if (defined(&domain($udom,'primary'))) {
1695: $uhome=&domain($udom,'primary');
1696: }
1697: }
1698: }
1699: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.93.4 2(raebur 1700:7): my $rep;
1701:7): if ($namespace =~ /^enc/) {
1702:7): $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1703:7): } else {
1704:7): $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1705:7): }
1.866 raeburn 1706: my %returnhash;
1.875 albertel 1707: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1708: return %returnhash;
1709: }
1.806 raeburn 1710: my @pairs=split(/\&/,$rep);
1711: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1712: return @pairs;
1713: }
1714: my $i=0;
1715: foreach my $item (@$storearr) {
1716: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1717: $i++;
1718: }
1719: return %returnhash;
1720: } else {
1.880 banghart 1721: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1722: }
1723: }
1724:
1725: # -------------------------------------------- put items in domain db files
1726:
1727: sub put_dom {
1.860 raeburn 1728: my ($namespace,$storehash,$udom,$uhome)=@_;
1729: if (!$udom) {
1730: $udom=$env{'user.domain'};
1731: if (defined(&domain($udom,'primary'))) {
1732: $uhome=&domain($udom,'primary');
1733: } else {
1.874 albertel 1734: undef($uhome);
1.860 raeburn 1735: }
1736: } else {
1737: if (!$uhome) {
1738: if (defined(&domain($udom,'primary'))) {
1739: $uhome=&domain($udom,'primary');
1740: }
1741: }
1742: }
1743: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1744: my $items='';
1745: foreach my $item (keys(%$storehash)) {
1746: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1747: }
1748: $items=~s/\&$//;
1.1172.2.93.4 2(raebur 1749:7): if ($namespace =~ /^enc/) {
1750:7): return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
1751:7): } else {
1752:7): return &reply("putdom:$udom:$namespace:$items",$uhome);
1753:7): }
1.806 raeburn 1754: } else {
1.860 raeburn 1755: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1756: }
1757: }
1758:
1.1023 raeburn 1759: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1760: sub newput_dom {
1.1023 raeburn 1761: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1762: my $result;
1763: if (!$udom) {
1764: $udom=$env{'user.domain'};
1765: }
1.1023 raeburn 1766: if ($udom) {
1767: my $uname = &get_domainconfiguser($udom);
1768: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1769: }
1770: return $result;
1771: }
1772:
1.1023 raeburn 1773: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1774: sub del_dom {
1.1023 raeburn 1775: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1776: if (ref($storearr) eq 'ARRAY') {
1777: if (!$udom) {
1778: $udom=$env{'user.domain'};
1779: }
1.1023 raeburn 1780: if ($udom) {
1781: my $uname = &get_domainconfiguser($udom);
1782: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1783: }
1784: }
1785: }
1786:
1.1023 raeburn 1787: # ----------------------------------construct domainconfig user for a domain
1788: sub get_domainconfiguser {
1789: my ($udom) = @_;
1790: return $udom.'-domainconfig';
1791: }
1792:
1.837 raeburn 1793: sub retrieve_inst_usertypes {
1794: my ($udom) = @_;
1795: my (%returnhash,@order);
1.989 raeburn 1796: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1797: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1798: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1799: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1800: } else {
1801: if (defined(&domain($udom,'primary'))) {
1802: my $uhome=&domain($udom,'primary');
1803: my $rep=&reply("inst_usertypes:$udom",$uhome);
1804: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1805: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1806: return (\%returnhash,\@order);
1807: }
1808: my ($hashitems,$orderitems) = split(/:/,$rep);
1809: my @pairs=split(/\&/,$hashitems);
1810: foreach my $item (@pairs) {
1811: my ($key,$value)=split(/=/,$item,2);
1812: $key = &unescape($key);
1813: next if ($key =~ /^error: 2 /);
1814: $returnhash{$key}=&thaw_unescape($value);
1815: }
1816: my @esc_order = split(/\&/,$orderitems);
1817: foreach my $item (@esc_order) {
1818: push(@order,&unescape($item));
1819: }
1820: } else {
1.1172.2.44 raeburn 1821: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1822: }
1.1172.2.44 raeburn 1823: return (\%returnhash,\@order);
1.837 raeburn 1824: }
1825: }
1826:
1.868 raeburn 1827: sub is_domainimage {
1828: my ($url) = @_;
1.1172.2.74 raeburn 1829: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1830: if (&domain($1) ne '') {
1831: return '1';
1832: }
1833: }
1834: return;
1835: }
1836:
1.899 raeburn 1837: sub inst_directory_query {
1838: my ($srch) = @_;
1839: my $udom = $srch->{'srchdomain'};
1840: my %results;
1841: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1842: my $outcome;
1.899 raeburn 1843: if ($homeserver ne '') {
1.904 albertel 1844: my $queryid=&reply("querysend:instdirsearch:".
1845: &escape($srch->{'srchby'}).':'.
1846: &escape($srch->{'srchterm'}).':'.
1847: &escape($srch->{'srchtype'}),$homeserver);
1848: my $host=&hostname($homeserver);
1849: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4 1(raebur 1850:7): &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1851: return;
1852: }
1853: my $response = &get_query_reply($queryid);
1854: my $maxtries = 5;
1855: my $tries = 1;
1856: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1857: $response = &get_query_reply($queryid);
1858: $tries ++;
1859: }
1860:
1861: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1862: if ($response eq 'unavailable') {
1863: $outcome = $response;
1864: } else {
1865: $outcome = 'ok';
1866: my @matches = split(/\n/,$response);
1867: foreach my $match (@matches) {
1868: my ($key,$value) = split(/=/,$match);
1869: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1870: }
1.899 raeburn 1871: }
1872: }
1873: }
1.909 raeburn 1874: return ($outcome,%results);
1.899 raeburn 1875: }
1876:
1877: sub usersearch {
1878: my ($srch) = @_;
1879: my $dom = $srch->{'srchdomain'};
1880: my %results;
1881: my %libserv = &all_library();
1882: my $query = 'usersearch';
1883: foreach my $tryserver (keys(%libserv)) {
1884: if (&host_domain($tryserver) eq $dom) {
1885: my $host=&hostname($tryserver);
1886: my $queryid=
1.911 raeburn 1887: &reply("querysend:".&escape($query).':'.
1888: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1889: &escape($srch->{'srchtype'}).':'.
1890: &escape($srch->{'srchterm'}),$tryserver);
1891: if ($queryid !~/^\Q$host\E\_/) {
1892: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1893: next;
1.899 raeburn 1894: }
1895: my $reply = &get_query_reply($queryid);
1896: my $maxtries = 1;
1897: my $tries = 1;
1898: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1899: $reply = &get_query_reply($queryid);
1900: $tries ++;
1901: }
1902: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1903: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1904: } else {
1.911 raeburn 1905: my @matches;
1906: if ($reply =~ /\n/) {
1907: @matches = split(/\n/,$reply);
1908: } else {
1909: @matches = split(/\&/,$reply);
1910: }
1.899 raeburn 1911: foreach my $match (@matches) {
1912: my ($uname,$udom,%userhash);
1.911 raeburn 1913: foreach my $entry (split(/:/,$match)) {
1914: my ($key,$value) =
1915: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1916: $userhash{$key} = $value;
1917: if ($key eq 'username') {
1918: $uname = $value;
1919: } elsif ($key eq 'domain') {
1920: $udom = $value;
1.911 raeburn 1921: }
1.899 raeburn 1922: }
1923: $results{$uname.':'.$udom} = \%userhash;
1924: }
1925: }
1926: }
1927: }
1928: return %results;
1929: }
1930:
1.912 raeburn 1931: sub get_instuser {
1932: my ($udom,$uname,$id) = @_;
1933: my $homeserver = &domain($udom,'primary');
1934: my ($outcome,%results);
1935: if ($homeserver ne '') {
1936: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1937: &escape($id).':'.&escape($udom),$homeserver);
1938: my $host=&hostname($homeserver);
1939: if ($queryid !~/^\Q$host\E\_/) {
1940: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1941: return;
1942: }
1943: my $response = &get_query_reply($queryid);
1944: my $maxtries = 5;
1945: my $tries = 1;
1946: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1947: $response = &get_query_reply($queryid);
1948: $tries ++;
1949: }
1950: if (!&error($response) && $response ne 'refused') {
1951: if ($response eq 'unavailable') {
1952: $outcome = $response;
1953: } else {
1954: $outcome = 'ok';
1955: my @matches = split(/\n/,$response);
1956: foreach my $match (@matches) {
1957: my ($key,$value) = split(/=/,$match);
1958: $results{&unescape($key)} = &thaw_unescape($value);
1959: }
1960: }
1961: }
1962: }
1963: my %userinfo;
1964: if (ref($results{$uname}) eq 'HASH') {
1965: %userinfo = %{$results{$uname}};
1966: }
1967: return ($outcome,%userinfo);
1968: }
1969:
1.1172.2.69 raeburn 1970: sub get_multiple_instusers {
1971: my ($udom,$users,$caller) = @_;
1972: my ($outcome,$results);
1973: if (ref($users) eq 'HASH') {
1974: my $count = keys(%{$users});
1975: my $requested = &freeze_escape($users);
1976: my $homeserver = &domain($udom,'primary');
1977: if ($homeserver ne '') {
1978: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1979: my $host=&hostname($homeserver);
1980: if ($queryid !~/^\Q$host\E\_/) {
1981: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1982: ' for host: '.$homeserver.'in domain '.$udom);
1983: return ($outcome,$results);
1984: }
1985: my $response = &get_query_reply($queryid);
1986: my $maxtries = 5;
1987: if ($count > 100) {
1988: $maxtries = 1+int($count/20);
1989: }
1990: my $tries = 1;
1991: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1992: $response = &get_query_reply($queryid);
1993: $tries ++;
1994: }
1995: if ($response eq '') {
1996: $results = {};
1997: foreach my $key (keys(%{$users})) {
1998: my ($uname,$id);
1999: if ($caller eq 'id') {
2000: $id = $key;
2001: } else {
2002: $uname = $key;
2003: }
2004: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2005: $outcome = $resp;
2006: if ($resp eq 'ok') {
2007: %{$results} = (%{$results}, %info);
2008: } else {
2009: last;
2010: }
2011: }
2012: } elsif(!&error($response) && ($response ne 'refused')) {
2013: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2014: $outcome = $response;
2015: } else {
2016: ($outcome,my $userdata) = split(/=/,$response,2);
2017: if ($outcome eq 'ok') {
2018: $results = &thaw_unescape($userdata);
2019: }
2020: }
2021: }
2022: }
2023: }
2024: return ($outcome,$results);
2025: }
2026:
1.912 raeburn 2027: sub inst_rulecheck {
1.923 raeburn 2028: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2029: my %returnhash;
2030: if ($udom ne '') {
2031: if (ref($rules) eq 'ARRAY') {
2032: @{$rules} = map {&escape($_);} (@{$rules});
2033: my $rulestr = join(':',@{$rules});
2034: my $homeserver=&domain($udom,'primary');
2035: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2036: my $response;
2037: if ($item eq 'username') {
2038: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2039: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2040: $homeserver));
1.923 raeburn 2041: } elsif ($item eq 'id') {
2042: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2043: ':'.&escape($id).':'.$rulestr,
2044: $homeserver));
1.945 raeburn 2045: } elsif ($item eq 'selfcreate') {
2046: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2047: &escape($udom).':'.&escape($uname).
2048: ':'.$rulestr,$homeserver));
1.923 raeburn 2049: }
1.912 raeburn 2050: if ($response ne 'refused') {
2051: my @pairs=split(/\&/,$response);
2052: foreach my $item (@pairs) {
2053: my ($key,$value)=split(/=/,$item,2);
2054: $key = &unescape($key);
2055: next if ($key =~ /^error: 2 /);
2056: $returnhash{$key}=&thaw_unescape($value);
2057: }
2058: }
2059: }
2060: }
2061: }
2062: return %returnhash;
2063: }
2064:
2065: sub inst_userrules {
1.923 raeburn 2066: my ($udom,$check) = @_;
1.912 raeburn 2067: my (%ruleshash,@ruleorder);
2068: if ($udom ne '') {
2069: my $homeserver=&domain($udom,'primary');
2070: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2071: my $response;
2072: if ($check eq 'id') {
2073: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2074: $homeserver);
1.943 raeburn 2075: } elsif ($check eq 'email') {
2076: $response=&reply('instemailrules:'.&escape($udom),
2077: $homeserver);
1.923 raeburn 2078: } else {
2079: $response=&reply('instuserrules:'.&escape($udom),
2080: $homeserver);
2081: }
1.912 raeburn 2082: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2083: ($response ne 'unknown_cmd') &&
1.912 raeburn 2084: ($response ne 'no_such_host')) {
2085: my ($hashitems,$orderitems) = split(/:/,$response);
2086: my @pairs=split(/\&/,$hashitems);
2087: foreach my $item (@pairs) {
2088: my ($key,$value)=split(/=/,$item,2);
2089: $key = &unescape($key);
2090: next if ($key =~ /^error: 2 /);
2091: $ruleshash{$key}=&thaw_unescape($value);
2092: }
2093: my @esc_order = split(/\&/,$orderitems);
2094: foreach my $item (@esc_order) {
2095: push(@ruleorder,&unescape($item));
2096: }
2097: }
2098: }
2099: }
2100: return (\%ruleshash,\@ruleorder);
2101: }
2102:
1.976 raeburn 2103: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2104:
2105: sub get_domain_defaults {
1.1172.2.35 raeburn 2106: my ($domain,$ignore_cache) = @_;
2107: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2108: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2109: unless ($ignore_cache) {
2110: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2111: if (defined($cached)) {
2112: if (ref($result) eq 'HASH') {
2113: return %{$result};
2114: }
1.943 raeburn 2115: }
2116: }
2117: my %domdefaults;
2118: my %domconfig =
1.989 raeburn 2119: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2120: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2121: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2122: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2123: 'coursecategories','autoenroll',
2124: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2125: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2126: if (ref($domconfig{'defaults'}) eq 'HASH') {
2127: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2128: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2129: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2130: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2131: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2132: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2133: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2134: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2135: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2136: } else {
2137: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2138: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2139: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2140: }
1.976 raeburn 2141: if (ref($domconfig{'quotas'}) eq 'HASH') {
2142: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2143: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2144: } else {
2145: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2146: }
1.1172.2.6 raeburn 2147: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2148: foreach my $item (@usertools) {
2149: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2150: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2151: }
2152: }
1.1172.2.29 raeburn 2153: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2154: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2155: }
1.976 raeburn 2156: }
1.985 raeburn 2157: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2158: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2159: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2160: }
2161: }
1.1172.2.9 raeburn 2162: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2163: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2164: }
1.989 raeburn 2165: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2166: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2167: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2168: }
2169: }
1.1047 raeburn 2170: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2171: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2172: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2173: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2174: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2175: }
1.1172.2.41 raeburn 2176: foreach my $type (@coursetypes) {
2177: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2178: unless ($type eq 'community') {
2179: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2180: }
2181: }
2182: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2183: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2184: }
1.1172.2.60 raeburn 2185: if ($domdefaults{'postsubmit'} eq 'on') {
2186: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2187: $domdefaults{$type.'postsubtimeout'} =
2188: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2189: }
2190: }
1.1172.2.30 raeburn 2191: }
1.1172.2.67 raeburn 2192: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2193: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2194: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2195: if (@clonecodes) {
2196: $domdefaults{'canclone'} = join('+',@clonecodes);
2197: }
2198: }
2199: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2200: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2201: }
1.1047 raeburn 2202: }
1.1073 raeburn 2203: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2204: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2205: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2206: }
2207: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2208: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2209: }
1.1172.2.62 raeburn 2210: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2211: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2212: }
1.1073 raeburn 2213: }
1.1172.2.41 raeburn 2214: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2215: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2216: my @settings = ('types','registered','enroll_dates','access_dates','section',
2217: 'approval','limit');
2218: foreach my $type (@coursetypes) {
2219: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2220: my @mgrdc = ();
2221: foreach my $item (@settings) {
2222: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2223: push(@mgrdc,$item);
2224: }
2225: }
2226: if (@mgrdc) {
2227: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2228: }
2229: }
2230: }
2231: }
2232: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2233: foreach my $type (@coursetypes) {
2234: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2235: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2236: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2237: }
2238: }
2239: }
2240: }
2241: }
1.1172.2.46 raeburn 2242: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2243: $domdefaults{'catauth'} = 'std';
2244: $domdefaults{'catunauth'} = 'std';
2245: if ($domconfig{'coursecategories'}{'auth'}) {
2246: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2247: }
2248: if ($domconfig{'coursecategories'}{'unauth'}) {
2249: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2250: }
2251: }
1.1172.2.76 raeburn 2252: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2253: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2254: }
1.1172.2.89 raeburn 2255: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2256: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2257: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2258: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2259: }
2260: }
1.1172.2.23 raeburn 2261: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2262: return %domdefaults;
2263: }
2264:
1.1172.2.93.4 2(raebur 2265:7): sub course_portal_url {
2266:7): my ($cnum,$cdom) = @_;
2267:7): my $chome = &homeserver($cnum,$cdom);
2268:7): my $hostname = &hostname($chome);
2269:7): my $protocol = $protocol{$chome};
2270:7): $protocol = 'http' if ($protocol ne 'https');
2271:7): my %domdefaults = &get_domain_defaults($cdom);
2272:7): my $firsturl;
2273:7): if ($domdefaults{'portal_def'}) {
2274:7): $firsturl = $domdefaults{'portal_def'};
2275:7): } else {
2276:7): $firsturl = $protocol.'://'.$hostname;
2277:7): }
2278:7): return $firsturl;
2279:7): }
2280:7):
1.344 www 2281: # --------------------------------------------------- Assign a key to a student
2282:
2283: sub assign_access_key {
1.364 www 2284: #
2285: # a valid key looks like uname:udom#comments
2286: # comments are being appended
2287: #
1.498 www 2288: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2289: $kdom=
1.620 albertel 2290: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2291: $knum=
1.620 albertel 2292: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2293: $cdom=
1.620 albertel 2294: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2295: $cnum=
1.620 albertel 2296: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2297: $udom=$env{'user.name'} unless (defined($udom));
2298: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2299: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2300: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2301: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2302: # assigned to this person
2303: # - this should not happen,
1.345 www 2304: # unless something went wrong
2305: # the first time around
2306: # ready to assign
1.364 www 2307: $logentry=$1.'; '.$logentry;
1.496 www 2308: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2309: $kdom,$knum) eq 'ok') {
1.345 www 2310: # key now belongs to user
1.346 www 2311: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2312: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2313: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2314: return 'ok';
2315: } else {
2316: return
2317: 'error: Count not permanently assign key, will need to be re-entered later.';
2318: }
2319: } else {
2320: return 'error: Could not assign key, try again later.';
2321: }
1.364 www 2322: } elsif (!$existing{$ckey}) {
1.345 www 2323: # the key does not exist
2324: return 'error: The key does not exist';
2325: } else {
2326: # the key is somebody else's
2327: return 'error: The key is already in use';
2328: }
1.344 www 2329: }
2330:
1.364 www 2331: # ------------------------------------------ put an additional comment on a key
2332:
2333: sub comment_access_key {
2334: #
2335: # a valid key looks like uname:udom#comments
2336: # comments are being appended
2337: #
2338: my ($ckey,$cdom,$cnum,$logentry)=@_;
2339: $cdom=
1.620 albertel 2340: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2341: $cnum=
1.620 albertel 2342: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2343: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2344: if ($existing{$ckey}) {
2345: $existing{$ckey}.='; '.$logentry;
2346: # ready to assign
1.367 www 2347: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2348: $cdom,$cnum) eq 'ok') {
2349: return 'ok';
2350: } else {
2351: return 'error: Count not store comment.';
2352: }
2353: } else {
2354: # the key does not exist
2355: return 'error: The key does not exist';
2356: }
2357: }
2358:
1.344 www 2359: # ------------------------------------------------------ Generate a set of keys
2360:
2361: sub generate_access_keys {
1.364 www 2362: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2363: $cdom=
1.620 albertel 2364: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2365: $cnum=
1.620 albertel 2366: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2367: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2368: unless (($cdom) && ($cnum)) { return 0; }
2369: if ($number>10000) { return 0; }
2370: sleep(2); # make sure don't get same seed twice
2371: srand(time()^($$+($$<<15))); # from "Programming Perl"
2372: my $total=0;
2373: for (my $i=1;$i<=$number;$i++) {
2374: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2375: sprintf("%lx",int(100000*rand)).'-'.
2376: sprintf("%lx",int(100000*rand));
2377: $newkey=~s/1/g/g; # folks mix up 1 and l
2378: $newkey=~s/0/h/g; # and also 0 and O
2379: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2380: if ($existing{$newkey}) {
2381: $i--;
2382: } else {
1.364 www 2383: if (&put('accesskeys',
2384: { $newkey => '# generated '.localtime().
1.620 albertel 2385: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2386: '; '.$logentry },
2387: $cdom,$cnum) eq 'ok') {
1.344 www 2388: $total++;
2389: }
2390: }
2391: }
1.620 albertel 2392: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2393: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2394: return $total;
2395: }
2396:
2397: # ------------------------------------------------------- Validate an accesskey
2398:
2399: sub validate_access_key {
2400: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2401: $cdom=
1.620 albertel 2402: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2403: $cnum=
1.620 albertel 2404: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2405: $udom=$env{'user.domain'} unless (defined($udom));
2406: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2407: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2408: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2409: }
2410:
2411: # ------------------------------------- Find the section of student in a course
1.652 albertel 2412: sub devalidate_getsection_cache {
2413: my ($udom,$unam,$courseid)=@_;
2414: my $hashid="$udom:$unam:$courseid";
2415: &devalidate_cache_new('getsection',$hashid);
2416: }
1.298 matthew 2417:
1.815 albertel 2418: sub courseid_to_courseurl {
2419: my ($courseid) = @_;
2420: #already url style courseid
2421: return $courseid if ($courseid =~ m{^/});
2422:
2423: if (exists($env{'course.'.$courseid.'.num'})) {
2424: my $cnum = $env{'course.'.$courseid.'.num'};
2425: my $cdom = $env{'course.'.$courseid.'.domain'};
2426: return "/$cdom/$cnum";
2427: }
2428:
2429: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2430: if (exists($courseinfo{'num'})) {
2431: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2432: }
2433:
2434: return undef;
2435: }
2436:
1.298 matthew 2437: sub getsection {
2438: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2439: my $cachetime=1800;
1.551 albertel 2440:
2441: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2442: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2443: if (defined($cached)) { return $result; }
2444:
1.298 matthew 2445: my %Pending;
2446: my %Expired;
2447: #
2448: # Each role can either have not started yet (pending), be active,
2449: # or have expired.
2450: #
2451: # If there is an active role, we are done.
2452: #
2453: # If there is more than one role which has not started yet,
2454: # choose the one which will start sooner
2455: # If there is one role which has not started yet, return it.
2456: #
2457: # If there is more than one expired role, choose the one which ended last.
2458: # If there is a role which has expired, return it.
2459: #
1.815 albertel 2460: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2461: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2462: foreach my $key (keys(%roleshash)) {
1.479 albertel 2463: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2464: my $section=$1;
2465: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2466: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2467: my $now=time;
1.548 albertel 2468: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2469: $Expired{$end}=$section;
2470: next;
2471: }
1.548 albertel 2472: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2473: $Pending{$start}=$section;
2474: next;
2475: }
1.599 albertel 2476: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2477: }
2478: #
2479: # Presumedly there will be few matching roles from the above
2480: # loop and the sorting time will be negligible.
2481: if (scalar(keys(%Pending))) {
2482: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2483: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2484: }
2485: if (scalar(keys(%Expired))) {
2486: my @sorted = sort {$a <=> $b} keys(%Expired);
2487: my $time = pop(@sorted);
1.599 albertel 2488: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2489: }
1.599 albertel 2490: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2491: }
1.70 www 2492:
1.599 albertel 2493: sub save_cache {
2494: &purge_remembered();
1.722 albertel 2495: #&Apache::loncommon::validate_page();
1.620 albertel 2496: undef(%env);
1.780 albertel 2497: undef($env_loaded);
1.599 albertel 2498: }
1.452 albertel 2499:
1.599 albertel 2500: my $to_remember=-1;
2501: my %remembered;
2502: my %accessed;
2503: my $kicks=0;
2504: my $hits=0;
1.849 albertel 2505: sub make_key {
2506: my ($name,$id) = @_;
1.872 albertel 2507: if (length($id) > 65
2508: && length(&escape($id)) > 200) {
2509: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2510: }
1.849 albertel 2511: return &escape($name.':'.$id);
2512: }
2513:
1.599 albertel 2514: sub devalidate_cache_new {
2515: my ($name,$id,$debug) = @_;
2516: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2517: my $remembered_id=$name.':'.$id;
1.849 albertel 2518: $id=&make_key($name,$id);
1.599 albertel 2519: $memcache->delete($id);
1.1172.2.81 raeburn 2520: delete($remembered{$remembered_id});
2521: delete($accessed{$remembered_id});
1.599 albertel 2522: }
2523:
2524: sub is_cached_new {
2525: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2526: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2527: # keys in %remembered hash, which persists for
2528: # duration of request (no restriction on key length).
2529: if (exists($remembered{$remembered_id})) {
2530: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2531: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2532: $hits++;
1.1172.2.81 raeburn 2533: return ($remembered{$remembered_id},1);
1.599 albertel 2534: }
1.1172.2.81 raeburn 2535: $id=&make_key($name,$id);
1.599 albertel 2536: my $value = $memcache->get($id);
2537: if (!(defined($value))) {
2538: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2539: return (undef,undef);
1.416 albertel 2540: }
1.599 albertel 2541: if ($value eq '__undef__') {
2542: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2543: $value=undef;
2544: }
1.1172.2.81 raeburn 2545: &make_room($remembered_id,$value,$debug);
1.599 albertel 2546: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2547: return ($value,1);
2548: }
2549:
2550: sub do_cache_new {
2551: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2552: my $remembered_id=$name.':'.$id;
1.849 albertel 2553: $id=&make_key($name,$id);
1.599 albertel 2554: my $setvalue=$value;
2555: if (!defined($setvalue)) {
2556: $setvalue='__undef__';
2557: }
1.623 albertel 2558: if (!defined($time) ) {
2559: $time=600;
2560: }
1.599 albertel 2561: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2562: my $result = $memcache->set($id,$setvalue,$time);
2563: if (! $result) {
1.872 albertel 2564: &logthis("caching of id -> $id failed");
1.910 albertel 2565: $memcache->disconnect_all();
1.872 albertel 2566: }
1.600 albertel 2567: # need to make a copy of $value
1.1172.2.81 raeburn 2568: &make_room($remembered_id,$value,$debug);
1.599 albertel 2569: return $value;
2570: }
2571:
2572: sub make_room {
1.1172.2.81 raeburn 2573: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2574:
1.1172.2.81 raeburn 2575: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2576: : $value;
1.599 albertel 2577: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2578: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2579: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2580: my $to_kick;
2581: my $max_time=0;
2582: foreach my $other (keys(%accessed)) {
2583: if (&tv_interval($accessed{$other}) > $max_time) {
2584: $to_kick=$other;
2585: $max_time=&tv_interval($accessed{$other});
2586: }
2587: }
2588: delete($remembered{$to_kick});
2589: delete($accessed{$to_kick});
2590: $kicks++;
2591: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2592: return;
2593: }
2594:
1.599 albertel 2595: sub purge_remembered {
1.604 albertel 2596: #&logthis("Tossing ".scalar(keys(%remembered)));
2597: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2598: undef(%remembered);
2599: undef(%accessed);
1.428 albertel 2600: }
1.70 www 2601: # ------------------------------------- Read an entry from a user's environment
2602:
2603: sub userenvironment {
2604: my ($udom,$unam,@what)=@_;
1.976 raeburn 2605: my $items;
2606: foreach my $item (@what) {
2607: $items.=&escape($item).'&';
2608: }
2609: $items=~s/\&$//;
1.70 www 2610: my %returnhash=();
1.1009 raeburn 2611: my $uhome = &homeserver($unam,$udom);
2612: unless ($uhome eq 'no_host') {
2613: my @answer=split(/\&/,
2614: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2615: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2616: return %returnhash;
2617: }
1.1009 raeburn 2618: my $i;
2619: for ($i=0;$i<=$#what;$i++) {
2620: $returnhash{$what[$i]}=&unescape($answer[$i]);
2621: }
1.70 www 2622: }
2623: return %returnhash;
1.1 albertel 2624: }
2625:
1.617 albertel 2626: # ---------------------------------------------------------- Get a studentphoto
2627: sub studentphoto {
2628: my ($udom,$unam,$ext) = @_;
2629: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2630: if (defined($env{'request.course.id'})) {
1.708 raeburn 2631: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2632: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2633: return(&retrievestudentphoto($udom,$unam,$ext));
2634: } else {
2635: my ($result,$perm_reqd)=
1.707 albertel 2636: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2637: if ($result eq 'ok') {
2638: if (!($perm_reqd eq 'yes')) {
2639: return(&retrievestudentphoto($udom,$unam,$ext));
2640: }
2641: }
2642: }
2643: }
2644: } else {
2645: my ($result,$perm_reqd) =
1.707 albertel 2646: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2647: if ($result eq 'ok') {
2648: if (!($perm_reqd eq 'yes')) {
2649: return(&retrievestudentphoto($udom,$unam,$ext));
2650: }
2651: }
2652: }
2653: return '/adm/lonKaputt/lonlogo_broken.gif';
2654: }
2655:
2656: sub retrievestudentphoto {
2657: my ($udom,$unam,$ext,$type) = @_;
2658: my $home=&Apache::lonnet::homeserver($unam,$udom);
2659: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2660: if ($ret eq 'ok') {
2661: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2662: if ($type eq 'thumbnail') {
2663: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2664: }
2665: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2666: return $tokenurl;
2667: } else {
2668: if ($type eq 'thumbnail') {
2669: return '/adm/lonKaputt/genericstudent_tn.gif';
2670: } else {
2671: return '/adm/lonKaputt/lonlogo_broken.gif';
2672: }
1.617 albertel 2673: }
2674: }
2675:
1.263 www 2676: # -------------------------------------------------------------------- New chat
2677:
2678: sub chatsend {
1.724 raeburn 2679: my ($newentry,$anon,$group)=@_;
1.620 albertel 2680: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2681: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2682: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2683: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2684: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2685: &escape($newentry)).':'.$group,$chome);
1.292 www 2686: }
2687:
2688: # ------------------------------------------ Find current version of a resource
2689:
2690: sub getversion {
2691: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2692: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2693: return ¤tversion(&filelocation('',$fname));
2694: }
2695:
2696: sub currentversion {
2697: my $fname=shift;
2698: my $author=$fname;
2699: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2700: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2701: my $home=&homeserver($uname,$udom);
1.292 www 2702: if ($home eq 'no_host') {
2703: return -1;
2704: }
1.1112 www 2705: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2706: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2707: return -1;
2708: }
1.1112 www 2709: return $answer;
1.263 www 2710: }
2711:
1.1111 www 2712: #
2713: # Return special version number of resource if set by override, empty otherwise
2714: #
2715: sub usedversion {
2716: my $fname=shift;
2717: unless ($fname) { $fname=$env{'request.uri'}; }
2718: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2719: if ($urlversion) { return $urlversion; }
2720: return '';
2721: }
2722:
1.1 albertel 2723: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2724:
1.1 albertel 2725: sub subscribe {
2726: my $fname=shift;
1.761 raeburn 2727: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2728: $fname=~s/[\n\r]//g;
1.1 albertel 2729: my $author=$fname;
2730: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2731: my ($udom,$uname)=split(/\//,$author);
2732: my $home=homeserver($uname,$udom);
1.335 albertel 2733: if ($home eq 'no_host') {
2734: return 'not_found';
1.1 albertel 2735: }
2736: my $answer=reply("sub:$fname",$home);
1.64 www 2737: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2738: $answer.=' by '.$home;
2739: }
1.1 albertel 2740: return $answer;
2741: }
2742:
1.8 www 2743: # -------------------------------------------------------------- Replicate file
2744:
2745: sub repcopy {
2746: my $filename=shift;
1.23 www 2747: $filename=~s/\/+/\//g;
1.1142 raeburn 2748: my $londocroot = $perlvar{'lonDocRoot'};
2749: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2750: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2751: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2752: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2753: return &repcopy_userfile($filename);
2754: }
1.532 albertel 2755: $filename=~s/[\n\r]//g;
1.8 www 2756: my $transname="$filename.in.transfer";
1.828 www 2757: # FIXME: this should flock
1.607 raeburn 2758: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2759: my $remoteurl=subscribe($filename);
1.64 www 2760: if ($remoteurl =~ /^con_lost by/) {
2761: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2762: return 'unavailable';
1.8 www 2763: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2764: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2765: return 'not_found';
1.64 www 2766: } elsif ($remoteurl =~ /^rejected by/) {
2767: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2768: return 'forbidden';
1.20 www 2769: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2770: return 'ok';
1.8 www 2771: } else {
1.290 www 2772: my $author=$filename;
2773: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2774: my ($udom,$uname)=split(/\//,$author);
2775: my $home=homeserver($uname,$udom);
2776: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2777: my @parts=split(/\//,$filename);
2778: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2779: if ($path ne "$londocroot/res") {
1.8 www 2780: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2781: return 'bad_request';
1.8 www 2782: }
2783: my $count;
2784: for ($count=5;$count<$#parts;$count++) {
2785: $path.="/$parts[$count]";
2786: if ((-e $path)!=1) {
2787: mkdir($path,0777);
2788: }
2789: }
2790: my $ua=new LWP::UserAgent;
2791: my $request=new HTTP::Request('GET',"$remoteurl");
2792: my $response=$ua->request($request,$transname);
2793: if ($response->is_error()) {
2794: unlink($transname);
2795: my $message=$response->status_line;
1.672 albertel 2796: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2797: ." LWP get: $message: $filename</font>");
1.607 raeburn 2798: return 'unavailable';
1.8 www 2799: } else {
1.16 www 2800: if ($remoteurl!~/\.meta$/) {
2801: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2802: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2803: if ($mresponse->is_error()) {
2804: unlink($filename.'.meta');
2805: &logthis(
1.672 albertel 2806: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2807: }
2808: }
1.8 www 2809: rename($transname,$filename);
1.607 raeburn 2810: return 'ok';
1.8 www 2811: }
1.290 www 2812: }
1.8 www 2813: }
1.330 www 2814: }
2815:
2816: # ------------------------------------------------ Get server side include body
2817: sub ssi_body {
1.381 albertel 2818: my ($filelink,%form)=@_;
1.606 matthew 2819: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2820: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2821: }
1.953 www 2822: my $output='';
2823: my $response;
1.980 raeburn 2824: if ($filelink=~/^https?\:/) {
1.954 raeburn 2825: ($output,$response)=&externalssi($filelink);
1.953 www 2826: } else {
1.1004 droeschl 2827: $filelink .= $filelink=~/\?/ ? '&' : '?';
2828: $filelink .= 'inhibitmenu=yes';
1.953 www 2829: ($output,$response)=&ssi($filelink,%form);
2830: }
1.778 albertel 2831: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2832: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2833: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2834: if (wantarray) {
2835: return ($output, $response);
2836: } else {
2837: return $output;
2838: }
1.8 www 2839: }
2840:
1.15 www 2841: # --------------------------------------------------------- Server Side Include
2842:
1.782 albertel 2843: sub absolute_url {
2844: my ($host_name) = @_;
2845: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2846: if ($host_name eq '') {
2847: $host_name = $ENV{'SERVER_NAME'};
2848: }
2849: return $protocol.$host_name;
2850: }
2851:
1.942 foxr 2852: #
2853: # Server side include.
2854: # Parameters:
2855: # fn Possibly encrypted resource name/id.
2856: # form Hash that describes how the rendering should be done
2857: # and other things.
1.944 foxr 2858: # Returns:
1.950 raeburn 2859: # Scalar context: The content of the response.
2860: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2861: #
1.15 www 2862: sub ssi {
2863:
1.944 foxr 2864: my ($fn,%form)=@_;
1.15 www 2865: my $ua=new LWP::UserAgent;
1.23 www 2866: my $request;
1.711 albertel 2867:
2868: $form{'no_update_last_known'}=1;
1.895 albertel 2869: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2870: if (%form) {
1.782 albertel 2871: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2872: $request->content(join('&',map {
2873: my $name = escape($_);
2874: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2875: ? join("&$name=", map {escape($_) } @{$form{$_}})
2876: : &escape($form{$_}) );
2877: } keys(%form)));
1.23 www 2878: } else {
1.782 albertel 2879: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2880: }
2881:
1.15 www 2882: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2883: my $response= $ua->request($request);
1.944 foxr 2884: if (wantarray) {
1.1172.2.3 raeburn 2885: return ($response->content, $response);
1.944 foxr 2886: } else {
1.1172.2.3 raeburn 2887: return $response->content;
1.942 foxr 2888: }
1.324 www 2889: }
2890:
2891: sub externalssi {
2892: my ($url)=@_;
2893: my $ua=new LWP::UserAgent;
2894: my $request=new HTTP::Request('GET',$url);
2895: my $response=$ua->request($request);
1.954 raeburn 2896: if (wantarray) {
2897: return ($response->content, $response);
2898: } else {
2899: return $response->content;
2900: }
1.15 www 2901: }
1.254 www 2902:
1.492 albertel 2903: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2904:
2905: sub allowuploaded {
2906: my ($srcurl,$url)=@_;
2907: $url=&clutter(&declutter($url));
2908: my $dir=$url;
2909: $dir=~s/\/[^\/]+$//;
2910: my %httpref=();
2911: my $httpurl=&hreflocation('',$url);
2912: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2913: &Apache::lonnet::appenv(\%httpref);
1.254 www 2914: }
1.477 raeburn 2915:
1.1172.2.13 raeburn 2916: #
2917: # Determine if the current user should be able to edit a particular resource,
2918: # when viewing in course context.
2919: # (a) When viewing resource used to determine if "Edit" item is included in
2920: # Functions.
2921: # (b) When displaying folder contents in course editor, used to determine if
2922: # "Edit" link will be displayed alongside resource.
2923: #
2924: # input: six args -- filename (decluttered), course number, course domain,
2925: # url, symb (if registered) and group (if this is a group
2926: # item -- e.g., bulletin board, group page etc.).
2927: # output: array of five scalars --
2928: # $cfile -- url for file editing if editable on current server
2929: # $home -- homeserver of resource (i.e., for author if published,
2930: # or course if uploaded.).
2931: # $switchserver -- 1 if server switch will be needed.
2932: # $forceedit -- 1 if icon/link should be to go to edit mode
2933: # $forceview -- 1 if icon/link should be to go to view mode
2934: #
2935:
2936: sub can_edit_resource {
2937: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2938: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2939: #
2940: # For aboutme pages user can only edit his/her own.
2941: #
2942: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2943: my ($sdom,$sname) = ($1,$2);
2944: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2945: $home = $env{'user.home'};
2946: $cfile = $resurl;
2947: if ($env{'form.forceedit'}) {
2948: $forceview = 1;
2949: } else {
2950: $forceedit = 1;
2951: }
2952: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2953: } else {
2954: return;
2955: }
2956: }
2957:
2958: if ($env{'request.course.id'}) {
2959: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2960: if ($group ne '') {
2961: # if this is a group homepage or group bulletin board, check group privs
2962: my $allowed = 0;
2963: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2964: if ((&allowed('mdg',$env{'request.course.id'}.
2965: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2966: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2967: $allowed = 1;
2968: }
2969: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2970: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2971: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2972: $allowed = 1;
2973: }
2974: }
2975: if ($allowed) {
2976: $home=&homeserver($cnum,$cdom);
2977: if ($env{'form.forceedit'}) {
2978: $forceview = 1;
2979: } else {
2980: $forceedit = 1;
2981: }
2982: $cfile = $resurl;
2983: } else {
2984: return;
2985: }
2986: } else {
1.1172.2.15 raeburn 2987: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2988: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2989: return;
2990: }
2991: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2992: #
2993: # No edit allowed where CC has switched to student role.
2994: #
2995: return;
2996: }
2997: }
2998: }
2999:
3000: if ($file ne '') {
3001: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3002: if (&is_course_upload($file,$cnum,$cdom)) {
3003: $uploaded = 1;
3004: $incourse = 1;
3005: if ($file =~/\.(htm|html|css|js|txt)$/) {
3006: $cfile = &hreflocation('',$file);
3007: if ($env{'form.forceedit'}) {
3008: $forceview = 1;
3009: } else {
3010: $forceedit = 1;
3011: }
3012: }
3013: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3014: $incourse = 1;
3015: if ($env{'form.forceedit'}) {
3016: $forceview = 1;
3017: } else {
3018: $forceedit = 1;
3019: }
3020: $cfile = $resurl;
3021: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3022: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3023: $incourse = 1;
3024: if ($env{'form.forceedit'}) {
3025: $forceview = 1;
3026: } else {
3027: $forceedit = 1;
3028: }
3029: $cfile = $resurl;
3030: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3031: $incourse = 1;
3032: $cfile = $resurl.'/smpedit';
3033: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3034: $incourse = 1;
3035: if ($env{'form.forceedit'}) {
3036: $forceview = 1;
3037: } else {
3038: $forceedit = 1;
3039: }
3040: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3041:7): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3042:7): $incourse = 1;
3043:7): if ($env{'form.forceedit'}) {
3044:7): $forceview = 1;
3045:7): } else {
3046:7): $forceedit = 1;
3047:7): }
3048:7): $cfile = $resurl;
1.1172.2.15 raeburn 3049: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3050: $incourse = 1;
3051: if ($env{'form.forceedit'}) {
3052: $forceview = 1;
3053: } else {
3054: $forceedit = 1;
3055: }
3056: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3057: }
3058: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3059: my $template = '/res/lib/templates/simpleproblem.problem';
3060: if (&is_on_map($template)) {
3061: $incourse = 1;
3062: $forceview = 1;
3063: $cfile = $template;
3064: }
3065: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3066: $incourse = 1;
3067: if ($env{'form.forceedit'}) {
3068: $forceview = 1;
3069: } else {
3070: $forceedit = 1;
3071: }
3072: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3073:7): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3074:7): $incourse = 1;
3075:7): if ($env{'form.forceedit'}) {
3076:7): $forceview = 1;
3077:7): } else {
3078:7): $forceedit = 1;
3079:7): }
3080:7): $cfile = $resurl;
1.1172.2.13 raeburn 3081: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3082: $incourse = 1;
3083: $forceview = 1;
3084: if ($symb) {
3085: my ($map,$id,$res)=&decode_symb($symb);
3086: $env{'request.symb'} = $symb;
3087: $cfile = &clutter($res);
3088: } else {
3089: $cfile = $env{'form.suppurl'};
1.1172.2.93.4 1(raebur 3090:7): my $escfile = &unescape($cfile);
2(raebur 3091:7): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3092:7): $cfile = '/adm/wrapper'.$escfile;
3093:7): } else {
3094:7): $escfile =~ s{^http://}{};
3095:7): $cfile = &escape("/adm/wrapper/ext/$escfile");
3096:7): }
1.1172.2.13 raeburn 3097: }
1.1172.2.31 raeburn 3098: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3099: if ($env{'form.forceedit'}) {
3100: $forceview = 1;
3101: } else {
3102: $forceedit = 1;
3103: }
3104: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3105: }
3106: }
3107: if ($uploaded || $incourse) {
3108: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3109: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3110: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3111: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3112: # Check that the user has permission to edit this resource
3113: my $setpriv = 1;
3114: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3115: if (defined($cfudom)) {
3116: $home=&homeserver($cfuname,$cfudom);
3117: $cfile=$file;
3118: }
3119: }
3120: if (($cfile ne '') && (!$incourse || $uploaded) &&
3121: (($home ne '') && ($home ne 'no_host'))) {
3122: my @ids=¤t_machine_ids();
3123: unless (grep(/^\Q$home\E$/,@ids)) {
3124: $switchserver=1;
3125: }
3126: }
3127: }
3128: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3129: }
3130:
3131: sub is_course_upload {
3132: my ($file,$cnum,$cdom) = @_;
3133: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3134: $uploadpath =~ s{^\/}{};
3135: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3136: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3137: return 1;
3138: }
3139: return;
3140: }
3141:
3142: sub in_course {
3143: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3144: if ($hideprivileged) {
3145: my $skipuser;
1.1172.2.23 raeburn 3146: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3147: my @possdoms = ($cdom);
3148: if ($coursehash{'checkforpriv'}) {
3149: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3150: }
3151: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3152: $skipuser = 1;
3153: if ($coursehash{'nothideprivileged'}) {
3154: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3155: my $user;
3156: if ($item =~ /:/) {
3157: $user = $item;
3158: } else {
3159: $user = join(':',split(/[\@]/,$item));
3160: }
3161: if ($user eq $uname.':'.$udom) {
3162: undef($skipuser);
3163: last;
3164: }
3165: }
3166: }
3167: if ($skipuser) {
3168: return 0;
3169: }
3170: }
3171: }
3172: $type ||= 'any';
3173: if (!defined($cdom) || !defined($cnum)) {
3174: my $cid = $env{'request.course.id'};
3175: $cdom = $env{'course.'.$cid.'.domain'};
3176: $cnum = $env{'course.'.$cid.'.num'};
3177: }
3178: my $typesref;
3179: if (($type eq 'any') || ($type eq 'all')) {
3180: $typesref = ['active','previous','future'];
3181: } elsif ($type eq 'previous' || $type eq 'future') {
3182: $typesref = [$type];
3183: }
3184: my %roles = &get_my_roles($uname,$udom,'userroles',
3185: $typesref,undef,[$cdom]);
3186: my ($tmp) = keys(%roles);
3187: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3188: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3189: if (@course_roles > 0) {
3190: return 1;
3191: }
3192: return 0;
3193: }
3194:
1.478 albertel 3195: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3196: # input: action, courseID, current domain, intended
1.637 raeburn 3197: # path to file, source of file, instruction to parse file for objects,
3198: # ref to hash for embedded objects,
3199: # ref to hash for codebase of java objects.
1.1095 raeburn 3200: # reference to scalar to accommodate mime type determined
3201: # from File::MMagic if $parser = parse.
1.637 raeburn 3202: #
1.485 raeburn 3203: # output: url to file (if action was uploaddoc),
3204: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3205: #
1.478 albertel 3206: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3207: # course.
1.477 raeburn 3208: #
1.478 albertel 3209: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3210: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3211: # course's home server.
1.477 raeburn 3212: #
1.478 albertel 3213: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3214: # be copied from $source (current location) to
3215: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3216: # and will then be copied to
3217: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3218: # course's home server.
1.485 raeburn 3219: #
1.481 raeburn 3220: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3221: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3222: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3223: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3224: # in course's home server.
1.637 raeburn 3225: #
1.477 raeburn 3226:
3227: sub process_coursefile {
1.1095 raeburn 3228: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3229: $mimetype)=@_;
1.477 raeburn 3230: my $fetchresult;
1.638 albertel 3231: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3232: if ($action eq 'propagate') {
1.638 albertel 3233: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3234: $home);
1.481 raeburn 3235: } else {
1.477 raeburn 3236: my $fpath = '';
3237: my $fname = $file;
1.478 albertel 3238: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3239: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3240: my $filepath = &build_filepath($fpath);
1.481 raeburn 3241: if ($action eq 'copy') {
3242: if ($source eq '') {
3243: $fetchresult = 'no source file';
3244: return $fetchresult;
3245: } else {
3246: my $destination = $filepath.'/'.$fname;
3247: rename($source,$destination);
3248: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3249: $home);
1.481 raeburn 3250: }
3251: } elsif ($action eq 'uploaddoc') {
3252: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3253: print $fh $env{'form.'.$source};
1.481 raeburn 3254: close($fh);
1.637 raeburn 3255: if ($parser eq 'parse') {
1.1024 raeburn 3256: my $mm = new File::MMagic;
1.1095 raeburn 3257: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3258: if ($type eq 'text/html') {
1.1024 raeburn 3259: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3260: unless ($parse_result eq 'ok') {
3261: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3262: }
1.637 raeburn 3263: }
1.1095 raeburn 3264: if (ref($mimetype)) {
3265: $$mimetype = $type;
3266: }
1.637 raeburn 3267: }
1.477 raeburn 3268: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3269: $home);
1.481 raeburn 3270: if ($fetchresult eq 'ok') {
3271: return '/uploaded/'.$fpath.'/'.$fname;
3272: } else {
3273: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3274: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3275: return '/adm/notfound.html';
3276: }
1.477 raeburn 3277: }
3278: }
1.485 raeburn 3279: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3280: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3281: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3282: }
3283: return $fetchresult;
3284: }
3285:
1.637 raeburn 3286: sub build_filepath {
3287: my ($fpath) = @_;
3288: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3289: unless ($fpath eq '') {
3290: my @parts=split('/',$fpath);
3291: foreach my $part (@parts) {
3292: $filepath.= '/'.$part;
3293: if ((-e $filepath)!=1) {
3294: mkdir($filepath,0777);
3295: }
3296: }
3297: }
3298: return $filepath;
3299: }
3300:
3301: sub store_edited_file {
1.638 albertel 3302: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3303: my $file = $primary_url;
3304: $file =~ s#^/uploaded/$docudom/$docuname/##;
3305: my $fpath = '';
3306: my $fname = $file;
3307: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3308: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3309: my $filepath = &build_filepath($fpath);
3310: open(my $fh,'>'.$filepath.'/'.$fname);
3311: print $fh $content;
3312: close($fh);
1.638 albertel 3313: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3314: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3315: $home);
1.637 raeburn 3316: if ($$fetchresult eq 'ok') {
3317: return '/uploaded/'.$fpath.'/'.$fname;
3318: } else {
1.638 albertel 3319: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3320: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3321: return '/adm/notfound.html';
3322: }
3323: }
3324:
1.531 albertel 3325: sub clean_filename {
1.831 albertel 3326: my ($fname,$args)=@_;
1.315 www 3327: # Replace Windows backslashes by forward slashes
1.257 www 3328: $fname=~s/\\/\//g;
1.831 albertel 3329: if (!$args->{'keep_path'}) {
3330: # Get rid of everything but the actual filename
3331: $fname=~s/^.*\/([^\/]+)$/$1/;
3332: }
1.315 www 3333: # Replace spaces by underscores
3334: $fname=~s/\s+/\_/g;
3335: # Replace all other weird characters by nothing
1.831 albertel 3336: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3337: # Replace all .\d. sequences with _\d. so they no longer look like version
3338: # numbers
3339: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3340: return $fname;
3341: }
1.1051 raeburn 3342: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3343: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3344: # image with the same aspect ratio as the original, but with dimensions which do
3345: # not exceed $resizewidth and $resizeheight.
3346:
1.984 neumanie 3347: sub resizeImage {
1.1051 raeburn 3348: my ($img_path,$resizewidth,$resizeheight) = @_;
3349: my $ima = Image::Magick->new;
3350: my $resized;
3351: if (-e $img_path) {
3352: $ima->Read($img_path);
3353: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3354: my $width = $ima->Get('width');
3355: my $height = $ima->Get('height');
3356: if ($width > $resizewidth) {
3357: my $factor = $width/$resizewidth;
3358: my $newheight = $height/$factor;
3359: $ima->Scale(width=>$resizewidth,height=>$newheight);
3360: $resized = 1;
3361: }
3362: }
3363: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3364: my $width = $ima->Get('width');
3365: my $height = $ima->Get('height');
3366: if ($height > $resizeheight) {
3367: my $factor = $height/$resizeheight;
3368: my $newwidth = $width/$factor;
3369: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3370: $resized = 1;
3371: }
3372: }
3373: if ($resized) {
3374: $ima->Write($img_path);
3375: }
3376: }
3377: return;
1.977 amueller 3378: }
3379:
1.608 albertel 3380: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3381: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3382: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3383: # $context - possible values: coursedoc, existingfile, overwrite,
3384: # canceloverwrite, or ''.
3385: # if 'coursedoc': upload to the current course
3386: # if 'existingfile': write file to tmp/overwrites directory
3387: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3388: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3389: # $subdir - directory in userfile to store the file into
1.858 raeburn 3390: # $parser - instruction to parse file for objects ($parser = parse)
3391: # $allfiles - reference to hash for embedded objects
3392: # $codebase - reference to hash for codebase of java objects
3393: # $desuname - username for permanent storage of uploaded file
3394: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3395: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3396: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3397: # $resizewidth - width (pixels) to which to resize uploaded image
3398: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3399: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3400: # from File::MMagic.
1.858 raeburn 3401: #
1.686 albertel 3402: # output: url of file in userspace, or error: <message>
3403: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3404:
1.531 albertel 3405: sub userfileupload {
1.1090 raeburn 3406: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3407: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3408: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3409: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3410: $fname=&clean_filename($fname);
1.1090 raeburn 3411: # See if there is anything left
1.257 www 3412: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3413: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3414: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3415: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3416: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3417: my $now = time;
1.1090 raeburn 3418: my $filepath;
1.1095 raeburn 3419: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3420: $filepath = 'tmp/helprequests/'.$now;
3421: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3422: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3423: '_'.$env{'user.domain'}.'/pending';
3424: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3425: my ($docuname,$docudom);
3426: if ($destudom) {
3427: $docudom = $destudom;
3428: } else {
3429: $docudom = $env{'user.domain'};
3430: }
3431: if ($destuname) {
3432: $docuname = $destuname;
3433: } else {
3434: $docuname = $env{'user.name'};
3435: }
3436: if (exists($env{'form.group'})) {
3437: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3438: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3439: }
3440: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3441: if ($context eq 'canceloverwrite') {
3442: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3443: if (-e $tempfile) {
3444: my @info = stat($tempfile);
3445: if ($info[9] eq $env{'form.timestamp'}) {
3446: unlink($tempfile);
3447: }
3448: }
3449: return;
1.523 raeburn 3450: }
3451: }
1.1090 raeburn 3452: # Create the directory if not present
1.741 raeburn 3453: my @parts=split(/\//,$filepath);
3454: my $fullpath = $perlvar{'lonDaemons'};
3455: for (my $i=0;$i<@parts;$i++) {
3456: $fullpath .= '/'.$parts[$i];
3457: if ((-e $fullpath)!=1) {
3458: mkdir($fullpath,0777);
3459: }
3460: }
3461: open(my $fh,'>'.$fullpath.'/'.$fname);
3462: print $fh $env{'form.'.$formname};
3463: close($fh);
1.1090 raeburn 3464: if ($context eq 'existingfile') {
3465: my @info = stat($fullpath.'/'.$fname);
3466: return ($fullpath.'/'.$fname,$info[9]);
3467: } else {
3468: return $fullpath.'/'.$fname;
3469: }
1.523 raeburn 3470: }
1.995 raeburn 3471: if ($subdir eq 'scantron') {
3472: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3473: } else {
1.995 raeburn 3474: $fname="$subdir/$fname";
3475: }
1.1090 raeburn 3476: if ($context eq 'coursedoc') {
1.638 albertel 3477: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3478: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3479: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3480: return &finishuserfileupload($docuname,$docudom,
3481: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3482: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3483: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3484: } else {
1.1172.2.21 raeburn 3485: if ($env{'form.folder'}) {
3486: $fname=$env{'form.folder'}.'/'.$fname;
3487: }
1.638 albertel 3488: return &process_coursefile('uploaddoc',$docuname,$docudom,
3489: $fname,$formname,$parser,
1.1095 raeburn 3490: $allfiles,$codebase,$mimetype);
1.481 raeburn 3491: }
1.719 banghart 3492: } elsif (defined($destuname)) {
3493: my $docuname=$destuname;
3494: my $docudom=$destudom;
1.860 raeburn 3495: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3496: $parser,$allfiles,$codebase,
1.1051 raeburn 3497: $thumbwidth,$thumbheight,
1.1095 raeburn 3498: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3499: } else {
1.638 albertel 3500: my $docuname=$env{'user.name'};
3501: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3502: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3503: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3504: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3505: }
1.860 raeburn 3506: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3507: $parser,$allfiles,$codebase,
1.1051 raeburn 3508: $thumbwidth,$thumbheight,
1.1095 raeburn 3509: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3510: }
1.271 www 3511: }
3512:
3513: sub finishuserfileupload {
1.860 raeburn 3514: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3515: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3516: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3517: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3518:
1.860 raeburn 3519: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3520: $file=$fname;
3521: if ($fname=~m|/|) {
3522: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3523: $path.=$fnamepath.'/';
3524: }
1.259 www 3525: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3526: my $count;
3527: for ($count=4;$count<=$#parts;$count++) {
3528: $filepath.="/$parts[$count]";
3529: if ((-e $filepath)!=1) {
3530: mkdir($filepath,0777);
3531: }
3532: }
1.984 neumanie 3533:
1.258 www 3534: # Save the file
3535: {
1.701 albertel 3536: if (!open(FH,'>'.$filepath.'/'.$file)) {
3537: &logthis('Failed to create '.$filepath.'/'.$file);
3538: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3539: return '/adm/notfound.html';
3540: }
1.1090 raeburn 3541: if ($context eq 'overwrite') {
1.1117 foxr 3542: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3543: my $target = $filepath.'/'.$file;
3544: if (-e $source) {
3545: my @info = stat($source);
3546: if ($info[9] eq $env{'form.timestamp'}) {
3547: unless (&File::Copy::move($source,$target)) {
3548: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3549: return "Moving from $source failed";
3550: }
3551: } else {
3552: return "Temporary file: $source had unexpected date/time for last modification";
3553: }
3554: } else {
3555: return "Temporary file: $source missing";
3556: }
3557: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3558: &logthis('Failed to write to '.$filepath.'/'.$file);
3559: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3560: return '/adm/notfound.html';
3561: }
1.570 albertel 3562: close(FH);
1.1051 raeburn 3563: if ($resizewidth && $resizeheight) {
3564: my $mm = new File::MMagic;
3565: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3566: if ($mime_type =~ m{^image/}) {
3567: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3568: }
1.977 amueller 3569: }
1.258 www 3570: }
1.1152 raeburn 3571: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3572: if (ref($mimetype)) {
3573: if ($$mimetype eq '') {
3574: my $mm = new File::MMagic;
3575: my $type = $mm->checktype_filename($filepath.'/'.$file);
3576: $$mimetype = $type;
3577: }
3578: }
3579: }
1.637 raeburn 3580: if ($parser eq 'parse') {
1.1152 raeburn 3581: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3582: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3583: $allfiles,$codebase);
3584: unless ($parse_result eq 'ok') {
3585: &logthis('Failed to parse '.$filepath.$file.
3586: ' for embedded media: '.$parse_result);
3587: }
1.637 raeburn 3588: }
3589: }
1.860 raeburn 3590: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3591: my $input = $filepath.'/'.$file;
3592: my $output = $filepath.'/'.'tn-'.$file;
3593: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3594: system("convert -sample $thumbsize $input $output");
3595: if (-e $filepath.'/'.'tn-'.$file) {
3596: $fetchthumb = 1;
3597: }
3598: }
1.858 raeburn 3599:
1.259 www 3600: # Notify homeserver to grep it
3601: #
1.984 neumanie 3602: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3603: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3604: if ($fetchresult eq 'ok') {
1.860 raeburn 3605: if ($fetchthumb) {
3606: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3607: if ($thumbresult ne 'ok') {
3608: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3609: $docuhome.': '.$thumbresult);
3610: }
3611: }
1.259 www 3612: #
1.258 www 3613: # Return the URL to it
1.494 albertel 3614: return '/uploaded/'.$path.$file;
1.263 www 3615: } else {
1.494 albertel 3616: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3617: ': '.$fetchresult);
1.263 www 3618: return '/adm/notfound.html';
1.858 raeburn 3619: }
1.493 albertel 3620: }
3621:
1.637 raeburn 3622: sub extract_embedded_items {
1.961 raeburn 3623: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3624: my @state = ();
1.1164 raeburn 3625: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3626: my %javafiles = (
3627: codebase => '',
3628: code => '',
3629: archive => ''
3630: );
3631: my %mediafiles = (
3632: src => '',
3633: movie => '',
3634: );
1.648 raeburn 3635: my $p;
3636: if ($content) {
3637: $p = HTML::LCParser->new($content);
3638: } else {
1.961 raeburn 3639: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3640: }
1.641 albertel 3641: while (my $t=$p->get_token()) {
1.640 albertel 3642: if ($t->[0] eq 'S') {
3643: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3644: push(@state, $tagname);
1.648 raeburn 3645: if (lc($tagname) eq 'allow') {
3646: &add_filetype($allfiles,$attr->{'src'},'src');
3647: }
1.640 albertel 3648: if (lc($tagname) eq 'img') {
3649: &add_filetype($allfiles,$attr->{'src'},'src');
3650: }
1.886 albertel 3651: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3652: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3653: &add_filetype($allfiles,$attr->{'href'},'href');
3654: }
1.886 albertel 3655: }
1.645 raeburn 3656: if (lc($tagname) eq 'script') {
1.1164 raeburn 3657: my $src;
1.645 raeburn 3658: if ($attr->{'archive'} =~ /\.jar$/i) {
3659: &add_filetype($allfiles,$attr->{'archive'},'archive');
3660: } else {
1.1164 raeburn 3661: if ($attr->{'src'} ne '') {
3662: $src = $attr->{'src'};
3663: &add_filetype($allfiles,$src,'src');
3664: }
3665: }
3666: my $text = $p->get_trimmed_text();
3667: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3668: my @swfargs = split(/,/,$1);
3669: foreach my $item (@swfargs) {
3670: $item =~ s/["']//g;
3671: $item =~ s/^\s+//;
3672: $item =~ s/\s+$//;
3673: }
3674: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3675: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3676: push(@{$related{$swfargs[0]}},$swfargs[2]);
3677: } else {
3678: $related{$swfargs[0]} = [$swfargs[2]];
3679: }
3680: }
1.645 raeburn 3681: }
3682: }
3683: if (lc($tagname) eq 'link') {
3684: if (lc($attr->{'rel'}) eq 'stylesheet') {
3685: &add_filetype($allfiles,$attr->{'href'},'href');
3686: }
3687: }
1.640 albertel 3688: if (lc($tagname) eq 'object' ||
3689: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3690: foreach my $item (keys(%javafiles)) {
3691: $javafiles{$item} = '';
3692: }
1.1164 raeburn 3693: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3694: $lastids{lc($tagname)} = $attr->{'id'};
3695: }
1.640 albertel 3696: }
3697: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3698: my $name = lc($attr->{'name'});
3699: foreach my $item (keys(%javafiles)) {
3700: if ($name eq $item) {
3701: $javafiles{$item} = $attr->{'value'};
3702: last;
3703: }
3704: }
1.1164 raeburn 3705: my $pathfrom;
1.640 albertel 3706: foreach my $item (keys(%mediafiles)) {
3707: if ($name eq $item) {
1.1164 raeburn 3708: $pathfrom = $attr->{'value'};
3709: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3710: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3711: last;
3712: }
3713: }
1.1164 raeburn 3714: if ($name eq 'flashvars') {
3715: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3716: }
3717: if ($pathfrom ne '') {
3718: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3719: $pathfrom);
3720: }
1.640 albertel 3721: }
3722: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3723: foreach my $item (keys(%javafiles)) {
3724: if ($attr->{$item}) {
3725: $javafiles{$item} = $attr->{$item};
3726: last;
3727: }
3728: }
3729: foreach my $item (keys(%mediafiles)) {
3730: if ($attr->{$item}) {
3731: &add_filetype($allfiles,$attr->{$item},$item);
3732: last;
3733: }
3734: }
1.1164 raeburn 3735: if (lc($tagname) eq 'embed') {
3736: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3737: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3738: $attr->{'src'});
3739: }
3740: }
1.640 albertel 3741: }
1.1172.2.35 raeburn 3742: if (lc($tagname) eq 'iframe') {
3743: my $src = $attr->{'src'} ;
3744: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3745: &add_filetype($allfiles,$src,'src');
3746: } elsif ($src =~ m{^/}) {
3747: if ($env{'request.course.id'}) {
3748: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3749: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3750: my $url = &hreflocation('',$fullpath);
3751: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3752: my $relpath = $1;
3753: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3754: &add_filetype($allfiles,$1,'src');
3755: }
3756: }
3757: }
3758: }
3759: }
1.1164 raeburn 3760: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3761: pop(@state);
1.1164 raeburn 3762: }
1.640 albertel 3763: } elsif ($t->[0] eq 'E') {
3764: my ($tagname) = ($t->[1]);
3765: if ($javafiles{'codebase'} ne '') {
3766: $javafiles{'codebase'} .= '/';
3767: }
3768: if (lc($tagname) eq 'applet' ||
3769: lc($tagname) eq 'object' ||
3770: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3771: ) {
3772: foreach my $item (keys(%javafiles)) {
3773: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3774: my $file=$javafiles{'codebase'}.$javafiles{$item};
3775: &add_filetype($allfiles,$file,$item);
3776: }
3777: }
3778: }
3779: pop @state;
3780: }
3781: }
1.1164 raeburn 3782: foreach my $id (sort(keys(%flashvars))) {
3783: if ($shockwave{$id} ne '') {
3784: my @pairs = split(/\&/,$flashvars{$id});
3785: foreach my $pair (@pairs) {
3786: my ($key,$value) = split(/\=/,$pair);
3787: if ($key eq 'thumb') {
3788: &add_filetype($allfiles,$value,$key);
3789: } elsif ($key eq 'content') {
3790: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3791: my ($ext) = ($value =~ /\.([^.]+)$/);
3792: if ($ext ne '') {
3793: &add_filetype($allfiles,$path.$value,$ext);
3794: }
3795: }
3796: }
3797: }
3798: }
1.637 raeburn 3799: return 'ok';
3800: }
3801:
1.639 albertel 3802: sub add_filetype {
3803: my ($allfiles,$file,$type)=@_;
3804: if (exists($allfiles->{$file})) {
3805: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3806: push(@{$allfiles->{$file}}, &escape($type));
3807: }
3808: } else {
3809: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3810: }
3811: }
3812:
1.1164 raeburn 3813: sub embedded_dependency {
3814: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3815: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3816: if (($identifier ne '') &&
3817: (ref($related->{$identifier}) eq 'ARRAY') &&
3818: ($pathfrom ne '')) {
3819: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3820: foreach my $dep (@{$related->{$identifier}}) {
3821: &add_filetype($allfiles,$path.$dep,'object');
3822: }
3823: }
3824: }
3825: return;
3826: }
3827:
1.493 albertel 3828: sub removeuploadedurl {
1.984 neumanie 3829: my ($url)=@_;
3830: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3831: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3832: }
3833:
3834: sub removeuserfile {
3835: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3836: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3837: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3838: if ($result eq 'ok') {
1.798 raeburn 3839: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3840: my $metafile = $fname.'.meta';
3841: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3842: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3843: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3844: my $sqlresult =
1.823 albertel 3845: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3846: 'portfolio_metadata',$group,
3847: 'delete');
1.798 raeburn 3848: }
3849: }
3850: return $result;
1.257 www 3851: }
1.15 www 3852:
1.530 albertel 3853: sub mkdiruserfile {
3854: my ($docuname,$docudom,$dir)=@_;
3855: my $home=&homeserver($docuname,$docudom);
3856: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3857: }
3858:
1.531 albertel 3859: sub renameuserfile {
3860: my ($docuname,$docudom,$old,$new)=@_;
3861: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3862: my $result = &reply("renameuserfile:$docudom:$docuname:".
3863: &escape("$old").':'.&escape("$new"),$home);
3864: if ($result eq 'ok') {
3865: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3866: my $oldmeta = $old.'.meta';
3867: my $newmeta = $new.'.meta';
3868: my $metaresult =
3869: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3870: my $url = "/uploaded/$docudom/$docuname/$old";
3871: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3872: my $sqlresult =
1.823 albertel 3873: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3874: 'portfolio_metadata',$group,
3875: 'delete');
1.798 raeburn 3876: }
3877: }
3878: return $result;
1.531 albertel 3879: }
3880:
1.14 www 3881: # ------------------------------------------------------------------------- Log
3882:
3883: sub log {
3884: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3885: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3886: }
3887:
3888: # ------------------------------------------------------------------ Course Log
1.352 www 3889: #
3890: # This routine flushes several buffers of non-mission-critical nature
3891: #
1.157 www 3892:
3893: sub flushcourselogs {
1.352 www 3894: &logthis('Flushing log buffers');
3895: #
3896: # course logs
3897: # This is a log of all transactions in a course, which can be used
3898: # for data mining purposes
3899: #
3900: # It also collects the courseid database, which lists last transaction
3901: # times and course titles for all courseids
3902: #
3903: my %courseidbuffer=();
1.921 raeburn 3904: foreach my $crsid (keys(%courselogs)) {
1.352 www 3905: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3906: &escape($courselogs{$crsid}),
3907: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3908: delete $courselogs{$crsid};
3909: } else {
3910: &logthis('Failed to flush log buffer for '.$crsid);
3911: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3912: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3913: " exceeded maximum size, deleting.</font>");
3914: delete $courselogs{$crsid};
3915: }
1.352 www 3916: }
1.920 raeburn 3917: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3918: 'description' => $coursedescrbuf{$crsid},
3919: 'inst_code' => $courseinstcodebuf{$crsid},
3920: 'type' => $coursetypebuf{$crsid},
3921: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3922: };
1.191 harris41 3923: }
1.352 www 3924: #
3925: # Write course id database (reverse lookup) to homeserver of courses
3926: # Is used in pickcourse
3927: #
1.840 albertel 3928: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3929: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3930: $courseidbuffer{$crs_home},
3931: $crs_home,'timeonly');
1.352 www 3932: }
3933: #
3934: # File accesses
3935: # Writes to the dynamic metadata of resources to get hit counts, etc.
3936: #
1.449 matthew 3937: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3938: if ($entry =~ /___count$/) {
3939: my ($dom,$name);
1.807 albertel 3940: ($dom,$name,undef)=
1.811 albertel 3941: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3942: if (! defined($dom) || $dom eq '' ||
3943: ! defined($name) || $name eq '') {
1.620 albertel 3944: my $cid = $env{'request.course.id'};
3945: $dom = $env{'request.'.$cid.'.domain'};
3946: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3947: }
1.450 matthew 3948: my $value = $accesshash{$entry};
3949: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3950: my %temphash=($url => $value);
1.449 matthew 3951: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3952: if ($result eq 'ok') {
3953: delete $accesshash{$entry};
3954: }
3955: } else {
1.811 albertel 3956: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3957: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3958: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3959: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3960: delete $accesshash{$entry};
3961: }
1.185 www 3962: }
1.191 harris41 3963: }
1.352 www 3964: #
3965: # Roles
3966: # Reverse lookup of user roles for course faculty/staff and co-authorship
3967: #
1.800 albertel 3968: foreach my $entry (keys(%userrolehash)) {
1.351 www 3969: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3970: split(/\:/,$entry);
3971: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3972: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3973: $rudom,$runame) eq 'ok') {
3974: delete $userrolehash{$entry};
3975: }
3976: }
1.662 raeburn 3977: #
1.1172.2.90 raeburn 3978: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 3979: #
3980: my %domrolebuffer = ();
1.1000 raeburn 3981: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3982: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3983: if ($domrolebuffer{$rudom}) {
3984: $domrolebuffer{$rudom}.='&'.&escape($entry).
3985: '='.&escape($domainrolehash{$entry});
3986: } else {
3987: $domrolebuffer{$rudom}.=&escape($entry).
3988: '='.&escape($domainrolehash{$entry});
3989: }
3990: delete $domainrolehash{$entry};
3991: }
3992: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 3993: my %servers;
3994: if (defined(&domain($dom,'primary'))) {
3995: my $primary=&domain($dom,'primary');
3996: my $hostname=&hostname($primary);
3997: $servers{$primary} = $hostname;
3998: } else {
3999: %servers = &get_servers($dom,'library');
4000: }
1.841 albertel 4001: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4002: if (&reply('domroleput:'.$dom.':'.
4003: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4004: last;
4005: } else {
1.841 albertel 4006: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4007: }
1.662 raeburn 4008: }
4009: }
1.186 www 4010: $dumpcount++;
1.157 www 4011: }
4012:
4013: sub courselog {
4014: my $what=shift;
1.158 www 4015: $what=time.':'.$what;
1.620 albertel 4016: unless ($env{'request.course.id'}) { return ''; }
4017: $coursedombuf{$env{'request.course.id'}}=
4018: $env{'course.'.$env{'request.course.id'}.'.domain'};
4019: $coursenumbuf{$env{'request.course.id'}}=
4020: $env{'course.'.$env{'request.course.id'}.'.num'};
4021: $coursehombuf{$env{'request.course.id'}}=
4022: $env{'course.'.$env{'request.course.id'}.'.home'};
4023: $coursedescrbuf{$env{'request.course.id'}}=
4024: $env{'course.'.$env{'request.course.id'}.'.description'};
4025: $courseinstcodebuf{$env{'request.course.id'}}=
4026: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4027: $courseownerbuf{$env{'request.course.id'}}=
4028: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4029: $coursetypebuf{$env{'request.course.id'}}=
4030: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4031: if (defined $courselogs{$env{'request.course.id'}}) {
4032: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4033: } else {
1.620 albertel 4034: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4035: }
1.620 albertel 4036: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4037: &flushcourselogs();
4038: }
1.158 www 4039: }
4040:
4041: sub courseacclog {
4042: my $fnsymb=shift;
1.620 albertel 4043: unless ($env{'request.course.id'}) { return ''; }
4044: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4045: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4046: $what.=':POST';
1.583 matthew 4047: # FIXME: Probably ought to escape things....
1.800 albertel 4048: foreach my $key (keys(%env)) {
4049: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4050: my $formitem = $1;
4051: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4052: $what.=':'.$formitem.'='.$env{$key};
4053: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4054: $what.=':'.$formitem.'='.$env{$key};
4055: }
1.158 www 4056: }
1.191 harris41 4057: }
1.583 matthew 4058: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4059: # FIXME: We should not be depending on a form parameter that someone
4060: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4061: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4062: $what.= ':POST';
4063: # FIXME: Probably ought to escape things....
4064: foreach my $element ('courseexp','crsfulltext','crsrelated',
4065: 'crsdiscuss') {
1.620 albertel 4066: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4067: }
4068: }
1.158 www 4069: }
4070: &courselog($what);
1.149 www 4071: }
4072:
1.185 www 4073: sub countacc {
4074: my $url=&declutter(shift);
1.458 matthew 4075: return if (! defined($url) || $url eq '');
1.620 albertel 4076: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4077: #
4078: # Mark that this url was used in this course
4079: #
1.620 albertel 4080: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4081: #
4082: # Increase the access count for this resource in this child process
4083: #
1.281 www 4084: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4085: $accesshash{$key}++;
1.185 www 4086: }
1.349 www 4087:
1.361 www 4088: sub linklog {
4089: my ($from,$to)=@_;
4090: $from=&declutter($from);
4091: $to=&declutter($to);
4092: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4093: $accesshash{$to.'___'.$from.'___goto'}=1;
4094: }
1.1160 www 4095:
4096: sub statslog {
4097: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4098: if ($users<2) { return; }
4099: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4100: 'course' => $env{'request.course.id'},
4101: 'sections' => '"all"',
4102: 'num_students' => $users,
4103: 'part' => $part,
4104: 'symb' => $symb,
4105: 'mean_tries' => $av_attempts,
4106: 'deg_of_diff' => $degdiff});
4107: foreach my $key (keys(%dynstore)) {
4108: $accesshash{$key}=$dynstore{$key};
4109: }
4110: }
1.361 www 4111:
1.349 www 4112: sub userrolelog {
4113: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4114: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4115: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4116: $userrolehash
4117: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4118: =$tend.':'.$tstart;
1.662 raeburn 4119: }
1.1169 droeschl 4120: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4121: $userrolehash
4122: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4123: =$tend.':'.$tstart;
4124: }
1.1172.2.90 raeburn 4125: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4126: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4127: $domainrolehash
4128: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4129: = $tend.':'.$tstart;
4130: }
1.351 www 4131: }
4132:
1.957 raeburn 4133: sub courserolelog {
4134: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4135: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4136: my $cdom = $1;
4137: my $cnum = $2;
4138: my $sec = $3;
4139: my $namespace = 'rolelog';
4140: my %storehash = (
4141: role => $trole,
4142: start => $tstart,
4143: end => $tend,
4144: selfenroll => $selfenroll,
4145: context => $context,
4146: );
4147: if ($trole eq 'gr') {
4148: $namespace = 'groupslog';
4149: $storehash{'group'} = $sec;
4150: } else {
4151: $storehash{'section'} = $sec;
4152: }
4153: &write_log('course',$namespace,\%storehash,$delflag,$username,
4154: $domain,$cnum,$cdom);
4155: if (($trole ne 'st') || ($sec ne '')) {
4156: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4157: }
4158: }
4159: return;
4160: }
4161:
1.1172.2.9 raeburn 4162: sub domainrolelog {
4163: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4164: if ($area =~ m{^/($match_domain)/$}) {
4165: my $cdom = $1;
4166: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4167: my $namespace = 'rolelog';
4168: my %storehash = (
4169: role => $trole,
4170: start => $tstart,
4171: end => $tend,
4172: context => $context,
4173: );
4174: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4175: $domain,$domconfiguser,$cdom);
4176: }
4177: return;
4178:
4179: }
4180:
4181: sub coauthorrolelog {
4182: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4183: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4184: my $audom = $1;
4185: my $auname = $2;
4186: my $namespace = 'rolelog';
4187: my %storehash = (
4188: role => $trole,
4189: start => $tstart,
4190: end => $tend,
4191: context => $context,
4192: );
4193: &write_log('author',$namespace,\%storehash,$delflag,$username,
4194: $domain,$auname,$audom);
4195: }
4196: return;
4197: }
4198:
1.351 www 4199: sub get_course_adv_roles {
1.948 raeburn 4200: my ($cid,$codes) = @_;
1.620 albertel 4201: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4202: my %coursehash=&coursedescription($cid);
1.988 raeburn 4203: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4204: my %nothide=();
1.800 albertel 4205: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4206: if ($user !~ /:/) {
4207: $nothide{join(':',split(/[\@]/,$user))}=1;
4208: } else {
4209: $nothide{$user}=1;
4210: }
1.470 www 4211: }
1.1172.2.23 raeburn 4212: my @possdoms = ($coursehash{'domain'});
4213: if ($coursehash{'checkforpriv'}) {
4214: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4215: }
1.351 www 4216: my %returnhash=();
4217: my %dumphash=
4218: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4219: my $now=time;
1.997 raeburn 4220: my %privileged;
1.1000 raeburn 4221: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4222: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4223: if (($tstart) && ($tstart<0)) { next; }
4224: if (($tend) && ($tend<$now)) { next; }
4225: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4226: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4227: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4228: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4229: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4230: if ($role eq 'cr') { next; }
1.948 raeburn 4231: if ($codes) {
4232: if ($section) { $role .= ':'.$section; }
4233: if ($returnhash{$role}) {
4234: $returnhash{$role}.=','.$username.':'.$domain;
4235: } else {
4236: $returnhash{$role}=$username.':'.$domain;
4237: }
1.351 www 4238: } else {
1.988 raeburn 4239: my $key=&plaintext($role,$crstype);
1.973 bisitz 4240: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4241: if ($returnhash{$key}) {
4242: $returnhash{$key}.=','.$username.':'.$domain;
4243: } else {
4244: $returnhash{$key}=$username.':'.$domain;
4245: }
1.351 www 4246: }
1.948 raeburn 4247: }
1.400 www 4248: return %returnhash;
4249: }
4250:
4251: sub get_my_roles {
1.937 raeburn 4252: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4253: unless (defined($uname)) { $uname=$env{'user.name'}; }
4254: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4255: my (%dumphash,%nothide);
1.1086 raeburn 4256: if ($context eq 'userroles') {
1.1166 raeburn 4257: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4258: } else {
1.1172.2.23 raeburn 4259: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4260: if ($hidepriv) {
4261: my %coursehash=&coursedescription($udom.'_'.$uname);
4262: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4263: if ($user !~ /:/) {
4264: $nothide{join(':',split(/[\@]/,$user))} = 1;
4265: } else {
4266: $nothide{$user} = 1;
4267: }
4268: }
4269: }
1.858 raeburn 4270: }
1.400 www 4271: my %returnhash=();
4272: my $now=time;
1.999 raeburn 4273: my %privileged;
1.800 albertel 4274: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4275: my ($role,$tend,$tstart);
4276: if ($context eq 'userroles') {
1.1149 raeburn 4277: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4278: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4279: } else {
4280: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4281: }
1.400 www 4282: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4283: my $status = 'active';
1.939 raeburn 4284: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4285: $status = 'previous';
4286: }
4287: if (($tstart) && ($now<$tstart)) {
4288: $status = 'future';
4289: }
4290: if (ref($types) eq 'ARRAY') {
4291: if (!grep(/^\Q$status\E$/,@{$types})) {
4292: next;
4293: }
4294: } else {
4295: if ($status ne 'active') {
4296: next;
4297: }
4298: }
1.867 raeburn 4299: my ($rolecode,$username,$domain,$section,$area);
4300: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4301: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4302: (undef,$domain,$username,$section) = split(/\//,$area);
4303: } else {
4304: ($role,$username,$domain,$section) = split(/\:/,$entry);
4305: }
1.832 raeburn 4306: if (ref($roledoms) eq 'ARRAY') {
4307: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4308: next;
4309: }
4310: }
4311: if (ref($roles) eq 'ARRAY') {
4312: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4313: if ($role =~ /^cr\//) {
4314: if (!grep(/^cr$/,@{$roles})) {
4315: next;
4316: }
1.1104 raeburn 4317: } elsif ($role =~ /^gr\//) {
4318: if (!grep(/^gr$/,@{$roles})) {
4319: next;
4320: }
1.922 raeburn 4321: } else {
4322: next;
4323: }
1.832 raeburn 4324: }
1.867 raeburn 4325: }
1.937 raeburn 4326: if ($hidepriv) {
1.1172.2.23 raeburn 4327: my @privroles = ('dc','su');
1.999 raeburn 4328: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4329: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4330: } else {
1.1172.2.23 raeburn 4331: my $possdoms = [$domain];
4332: if (ref($roledoms) eq 'ARRAY') {
4333: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4334: }
1.1172.2.23 raeburn 4335: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4336: if (!$nothide{$username.':'.$domain}) {
4337: next;
4338: }
4339: }
1.937 raeburn 4340: }
4341: }
1.933 raeburn 4342: if ($withsec) {
4343: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4344: $tstart.':'.$tend;
4345: } else {
4346: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4347: }
1.832 raeburn 4348: }
1.373 www 4349: return %returnhash;
1.399 www 4350: }
4351:
1.1172.2.89 raeburn 4352: sub get_all_adhocroles {
4353: my ($dom) = @_;
4354: my @roles_by_num = ();
4355: my %domdefaults = &get_domain_defaults($dom);
4356: my (%description,%access_in_dom,%access_info);
4357: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4358: my $count = 0;
4359: my %domcurrent = %{$domdefaults{'adhocroles'}};
4360: my %ordered;
4361: foreach my $role (sort(keys(%domcurrent))) {
4362: my ($order,$desc,$access_in_dom);
4363: if (ref($domcurrent{$role}) eq 'HASH') {
4364: $order = $domcurrent{$role}{'order'};
4365: $desc = $domcurrent{$role}{'desc'};
4366: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4367: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4368: }
4369: if ($order eq '') {
4370: $order = $count;
4371: }
4372: $ordered{$order} = $role;
4373: if ($desc ne '') {
4374: $description{$role} = $desc;
4375: } else {
4376: $description{$role}= $role;
4377: }
4378: $count++;
4379: }
4380: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4381: push(@roles_by_num,$ordered{$item});
4382: }
4383: }
4384: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4385: }
4386:
4387: sub get_my_adhocroles {
4388: my ($cid,$checkreg) = @_;
4389: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4390: if ($env{'request.course.id'} eq $cid) {
4391: $cdom = $env{'course.'.$cid.'.domain'};
4392: $cnum = $env{'course.'.$cid.'.num'};
4393: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4394: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4395: $cdom = $1;
4396: $cnum = $2;
4397: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4398: $cdom,$cnum);
4399: }
4400: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4401: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4402: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4403: if ($rosterhash{$user} ne '') {
4404: my $type = (split(/:/,$rosterhash{$user}))[5];
4405: return ([],{}) if ($type eq 'auto');
4406: }
4407: }
4408: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4409: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4410: my $then=$env{'user.login.time'};
4411: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4412: if (!$update) {
4413: $update = $then;
4414: }
4415: my @liveroles;
4416: foreach my $role ('dh','da') {
4417: if ($env{"user.role.$role./$cdom/"}) {
4418: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4419: my $limit = $update;
4420: if ($env{'request.role'} eq "$role./$cdom/") {
4421: $limit = $then;
4422: }
4423: my $activerole = 1;
4424: if ($tstart && $tstart>$limit) { $activerole = 0; }
4425: if ($tend && $tend <$limit) { $activerole = 0; }
4426: if ($activerole) {
4427: push(@liveroles,$role);
4428: }
4429: }
4430: }
4431: if (@liveroles) {
1.1172.2.89 raeburn 4432: if (&homeserver($cnum,$cdom) ne 'no_host') {
4433: my ($accessref,$accessinfo,%access_in_dom);
4434: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4435: if (ref($roles_by_num) eq 'ARRAY') {
4436: if (@{$roles_by_num}) {
4437: my %settings;
4438: if ($env{'request.course.id'} eq $cid) {
4439: foreach my $envkey (keys(%env)) {
4440: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4441: $settings{$1} = $env{$envkey};
4442: }
4443: }
4444: } else {
4445: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4446: }
4447: my %setincrs;
4448: if ($settings{'internal.adhocaccess'}) {
4449: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4450: }
4451: my @statuses;
4452: if ($env{'environment.inststatus'}) {
4453: @statuses = split(/,/,$env{'environment.inststatus'});
4454: }
4455: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4456: if (ref($accessref) eq 'HASH') {
4457: %access_in_dom = %{$accessref};
4458: }
4459: foreach my $role (@{$roles_by_num}) {
4460: my ($curraccess,@okstatus,@personnel);
4461: if ($setincrs{$role}) {
4462: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4463: if ($curraccess eq 'status') {
4464: @okstatus = split(/\&/,$rest);
4465: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4466: @personnel = split(/\&/,$rest);
4467: }
4468: } else {
4469: $curraccess = $access_in_dom{$role};
4470: if (ref($accessinfo) eq 'HASH') {
4471: if ($curraccess eq 'status') {
4472: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4473: @okstatus = @{$accessinfo->{$role}};
4474: }
4475: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4476: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4477: @personnel = @{$accessinfo->{$role}};
4478: }
4479: }
4480: }
4481: }
4482: if ($curraccess eq 'none') {
4483: next;
4484: } elsif ($curraccess eq 'all') {
4485: push(@possroles,$role);
1.1172.2.90 raeburn 4486: } elsif ($curraccess eq 'dh') {
4487: if (grep(/^dh$/,@liveroles)) {
4488: push(@possroles,$role);
4489: } else {
4490: next;
4491: }
4492: } elsif ($curraccess eq 'da') {
4493: if (grep(/^da$/,@liveroles)) {
4494: push(@possroles,$role);
4495: } else {
4496: next;
4497: }
1.1172.2.89 raeburn 4498: } elsif ($curraccess eq 'status') {
4499: if (@okstatus) {
4500: if (!@statuses) {
4501: if (grep(/^default$/,@okstatus)) {
4502: push(@possroles,$role);
4503: }
4504: } else {
4505: foreach my $status (@okstatus) {
4506: if (grep(/^\Q$status\E$/,@statuses)) {
4507: push(@possroles,$role);
4508: last;
4509: }
4510: }
4511: }
4512: }
4513: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4514: if (grep(/^\Q$user\E$/,@personnel)) {
4515: if ($curraccess eq 'exc') {
4516: push(@possroles,$role);
4517: }
4518: } elsif ($curraccess eq 'inc') {
4519: push(@possroles,$role);
4520: }
4521: }
4522: }
4523: }
4524: }
4525: }
4526: }
4527: }
4528: }
4529: unless (ref($description) eq 'HASH') {
4530: if (ref($roles_by_num) eq 'ARRAY') {
4531: my %desc;
4532: map { $desc{$_} = $_; } (@{$roles_by_num});
4533: $description = \%desc;
4534: } else {
4535: $description = {};
4536: }
4537: }
4538: return (\@possroles,$description);
4539: }
4540:
1.399 www 4541: # ----------------------------------------------------- Frontpage Announcements
4542: #
4543: #
4544:
4545: sub postannounce {
4546: my ($server,$text)=@_;
1.844 albertel 4547: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4548: unless ($text=~/\w/) { $text=''; }
4549: return &reply('setannounce:'.&escape($text),$server);
4550: }
4551:
4552: sub getannounce {
1.448 albertel 4553:
4554: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4555: my $announcement='';
1.800 albertel 4556: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4557: close($fh);
1.399 www 4558: if ($announcement=~/\w/) {
4559: return
4560: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4561: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4562: } else {
4563: return '';
4564: }
4565: } else {
4566: return '';
4567: }
1.351 www 4568: }
1.353 www 4569:
4570: # ---------------------------------------------------------- Course ID routines
4571: # Deal with domain's nohist_courseid.db files
4572: #
4573:
4574: sub courseidput {
1.921 raeburn 4575: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4576: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4577: my $outcome;
4578: if ($caller eq 'timeonly') {
4579: my $cids = '';
4580: foreach my $item (keys(%$storehash)) {
4581: $cids.=&escape($item).'&';
4582: }
4583: $cids=~s/\&$//;
4584: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4585: $coursehome);
4586: } else {
4587: my $items = '';
4588: foreach my $item (keys(%$storehash)) {
4589: $items.= &escape($item).'='.
4590: &freeze_escape($$storehash{$item}).'&';
4591: }
4592: $items=~s/\&$//;
4593: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4594: $coursehome);
1.918 raeburn 4595: }
4596: if ($outcome eq 'unknown_cmd') {
4597: my $what;
4598: foreach my $cid (keys(%$storehash)) {
4599: $what .= &escape($cid).'=';
1.921 raeburn 4600: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4601: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4602: }
4603: $what =~ s/\:$/&/;
4604: }
4605: $what =~ s/\&$//;
4606: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4607: } else {
4608: return $outcome;
4609: }
1.353 www 4610: }
4611:
4612: sub courseiddump {
1.921 raeburn 4613: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4614: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4615: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4616: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4617: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4618: my $as_hash = 1;
4619: my %returnhash;
4620: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4621: my %libserv = &all_library();
4622: foreach my $tryserver (keys(%libserv)) {
4623: if ( ( $hostidflag == 1
4624: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4625: || (!defined($hostidflag)) ) {
4626:
1.918 raeburn 4627: if (($domfilter eq '') ||
4628: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4629: my $rep;
4630: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4631: $rep = &LONCAPA::Lond::dump_course_id_handler(
4632: join(":", (&host_domain($tryserver), $sincefilter,
4633: &escape($descfilter), &escape($instcodefilter),
4634: &escape($ownerfilter), &escape($coursefilter),
4635: &escape($typefilter), &escape($regexp_ok),
4636: $as_hash, &escape($selfenrollonly),
4637: &escape($catfilter), $showhidden, $caller,
4638: &escape($cloner), &escape($cc_clone), $cloneonly,
4639: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4640: &escape($creationcontext),$domcloner,$hasuniquecode,
4641: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4642: } else {
4643: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4644: $sincefilter.':'.&escape($descfilter).':'.
4645: &escape($instcodefilter).':'.&escape($ownerfilter).
4646: ':'.&escape($coursefilter).':'.&escape($typefilter).
4647: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4648: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4649: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4650: &escape($cc_clone).':'.$cloneonly.':'.
4651: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4652: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4653: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4654: }
4655:
1.918 raeburn 4656: my @pairs=split(/\&/,$rep);
4657: foreach my $item (@pairs) {
4658: my ($key,$value)=split(/\=/,$item,2);
4659: $key = &unescape($key);
4660: next if ($key =~ /^error: 2 /);
4661: my $result = &thaw_unescape($value);
4662: if (ref($result) eq 'HASH') {
4663: $returnhash{$key}=$result;
4664: } else {
1.921 raeburn 4665: my @responses = split(/:/,$value);
4666: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4667: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4668: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4669: }
1.1008 raeburn 4670: }
1.353 www 4671: }
4672: }
4673: }
4674: }
4675: return %returnhash;
4676: }
4677:
1.1055 raeburn 4678: sub courselastaccess {
4679: my ($cdom,$cnum,$hostidref) = @_;
4680: my %returnhash;
4681: if ($cdom && $cnum) {
4682: my $chome = &homeserver($cnum,$cdom);
4683: if ($chome ne 'no_host') {
4684: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4685: &extract_lastaccess(\%returnhash,$rep);
4686: }
4687: } else {
4688: if (!$cdom) { $cdom=''; }
4689: my %libserv = &all_library();
4690: foreach my $tryserver (keys(%libserv)) {
4691: if (ref($hostidref) eq 'ARRAY') {
4692: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4693: }
4694: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4695: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4696: &extract_lastaccess(\%returnhash,$rep);
4697: }
4698: }
4699: }
4700: return %returnhash;
4701: }
4702:
4703: sub extract_lastaccess {
4704: my ($returnhash,$rep) = @_;
4705: if (ref($returnhash) eq 'HASH') {
4706: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4707: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4708: $rep eq '') {
4709: my @pairs=split(/\&/,$rep);
4710: foreach my $item (@pairs) {
4711: my ($key,$value)=split(/\=/,$item,2);
4712: $key = &unescape($key);
4713: next if ($key =~ /^error: 2 /);
4714: $returnhash->{$key} = &thaw_unescape($value);
4715: }
4716: }
4717: }
4718: return;
4719: }
4720:
1.658 raeburn 4721: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4722:
4723: sub dcmailput {
1.685 raeburn 4724: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4725: my $status = &Apache::lonnet::critical(
1.740 www 4726: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4727: &escape($message),$server);
1.662 raeburn 4728: return $status;
4729: }
4730:
1.658 raeburn 4731: sub dcmaildump {
4732: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4733: my %returnhash=();
1.846 albertel 4734:
4735: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4736: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4737: &escape($enddate).':';
4738: my @esc_senders=map { &escape($_)} @$senders;
4739: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4740: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4741: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4742: if (($key) && ($value)) {
4743: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4744: }
4745: }
4746: }
4747: return %returnhash;
4748: }
1.662 raeburn 4749: # ---------------------------------------------------------- Domain roles
4750:
4751: sub get_domain_roles {
4752: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4753: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4754: $startdate = '.';
4755: }
1.1018 raeburn 4756: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4757: $enddate = '.';
4758: }
1.922 raeburn 4759: my $rolelist;
4760: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4761: $rolelist = join('&',@{$roles});
1.922 raeburn 4762: }
1.662 raeburn 4763: my %personnel = ();
1.841 albertel 4764:
4765: my %servers = &get_servers($dom,'library');
4766: foreach my $tryserver (keys(%servers)) {
4767: %{$personnel{$tryserver}}=();
4768: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4769: &escape($startdate).':'.
4770: &escape($enddate).':'.
4771: &escape($rolelist), $tryserver))) {
4772: my ($key,$value) = split(/\=/,$line,2);
4773: if (($key) && ($value)) {
4774: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4775: }
4776: }
1.662 raeburn 4777: }
4778: return %personnel;
4779: }
1.658 raeburn 4780:
1.1172.2.89 raeburn 4781: sub get_active_domroles {
4782: my ($dom,$roles) = @_;
4783: return () unless (ref($roles) eq 'ARRAY');
4784: my $now = time;
4785: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4786: my %domroles;
4787: foreach my $server (keys(%dompersonnel)) {
4788: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4789: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4790: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4791: }
4792: }
4793: return %domroles;
4794: }
4795:
1.1057 www 4796: # ----------------------------------------------------------- Interval timing
1.149 www 4797:
1.1153 www 4798: {
4799: # Caches needed for speedup of navmaps
4800: # We don't want to cache this for very long at all (5 seconds at most)
4801: #
4802: # The user for whom we cache
4803: my $cachedkey='';
4804: # The cached times for this user
4805: my %cachedtimes=();
4806: # When this was last done
1.1172.2.66 raeburn 4807: my $cachedtime='';
1.1153 www 4808:
4809: sub load_all_first_access {
1.1172.2.93.4 1(raebur 4810:7): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4811: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4 1(raebur 4812:7): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4813:7): (!$ignorecache)) {
1.1154 raeburn 4814: return;
4815: }
4816: $cachedtime=time;
4817: $cachedkey=$uname.':'.$udom;
4818: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4819: }
4820:
1.504 albertel 4821: sub get_first_access {
1.1172.2.93.4 1(raebur 4822:7): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4823: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4824: if ($argsymb) { $symb=$argsymb; }
4825: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4826: if ($argmap) { $map = $argmap; }
1.926 albertel 4827: if ($type eq 'course') {
4828: $res='course';
4829: } elsif ($type eq 'map') {
1.588 albertel 4830: $res=&symbread($map);
4831: } else {
4832: $res=$symb;
4833: }
1.1172.2.93.4 1(raebur 4834:7): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4835: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4836: }
4837:
4838: sub set_first_access {
1.1162 raeburn 4839: my ($type,$interval)=@_;
1.790 albertel 4840: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4841: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4842: if ($type eq 'course') {
4843: $res='course';
4844: } elsif ($type eq 'map') {
1.588 albertel 4845: $res=&symbread($map);
4846: } else {
4847: $res=$symb;
4848: }
1.1153 www 4849: $cachedkey='';
1.1162 raeburn 4850: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4851: if (!$firstaccess) {
1.1162 raeburn 4852: my $start = time;
4853: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4854: $udom,$uname);
4855: if ($putres eq 'ok') {
4856: &put('timerinterval',{"$courseid\0$res"=>$interval},
4857: $udom,$uname);
4858: &appenv(
4859: {
4860: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4861: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4862: }
4863: );
4864: }
4865: return $putres;
1.505 albertel 4866: }
4867: return 'already_set';
1.504 albertel 4868: }
1.1153 www 4869: }
1.1172.2.32 raeburn 4870:
4871: sub checkout {
4872: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4873: my $now=time;
4874: my $lonhost=$perlvar{'lonHostID'};
4875: my $infostr=&escape(
4876: 'CHECKOUTTOKEN&'.
4877: $tuname.'&'.
4878: $tudom.'&'.
4879: $tcrsid.'&'.
4880: $symb.'&'.
4881: $now.'&'.$ENV{'REMOTE_ADDR'});
4882: my $token=&reply('tmpput:'.$infostr,$lonhost);
4883: if ($token=~/^error\:/) {
4884: &logthis("<font color=\"blue\">WARNING: ".
4885: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4886: "</font>");
4887: return '';
4888: }
4889:
4890: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4891: $token=~tr/a-z/A-Z/;
4892:
4893: my %infohash=('resource.0.outtoken' => $token,
4894: 'resource.0.checkouttime' => $now,
4895: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4896:
4897: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4898: return '';
4899: } else {
4900: &logthis("<font color=\"blue\">WARNING: ".
4901: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4902: "</font>");
4903: }
4904:
4905: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4906: &escape('Checkout '.$infostr.' - '.
4907: $token)) ne 'ok') {
4908: return '';
4909: } else {
4910: &logthis("<font color=\"blue\">WARNING: ".
4911: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4912: "</font>");
4913: }
4914: return $token;
4915: }
4916:
4917: # ------------------------------------------------------------ Check in an item
4918:
4919: sub checkin {
4920: my $token=shift;
4921: my $now=time;
4922: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4923: $lonhost=~tr/A-Z/a-z/;
4924: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4925: $dtoken=~s/\W/\_/g;
4926: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4927: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4928:
4929: unless (($tuname) && ($tudom)) {
4930: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4931: return '';
4932: }
4933:
4934: unless (&allowed('mgr',$tcrsid)) {
4935: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4936: $env{'user.name'}.' - '.$env{'user.domain'});
4937: return '';
4938: }
4939:
4940: my %infohash=('resource.0.intoken' => $token,
4941: 'resource.0.checkintime' => $now,
4942: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4943:
4944: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4945: return '';
4946: }
4947:
4948: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4949: &escape('Checkin - '.$token)) ne 'ok') {
4950: return '';
4951: }
4952:
4953: return ($symb,$tuname,$tudom,$tcrsid);
4954: }
4955:
1.110 www 4956: # --------------------------------------------- Set Expire Date for Spreadsheet
4957:
4958: sub expirespread {
4959: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4960: my $cid=$env{'request.course.id'};
1.110 www 4961: if ($cid) {
4962: my $now=time;
4963: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4964: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4965: $env{'course.'.$cid.'.num'}.
1.110 www 4966: ':nohist_expirationdates:'.
4967: &escape($key).'='.$now,
1.620 albertel 4968: $env{'course.'.$cid.'.home'})
1.110 www 4969: }
4970: return 'ok';
1.14 www 4971: }
4972:
1.109 www 4973: # ----------------------------------------------------- Devalidate Spreadsheets
4974:
4975: sub devalidate {
1.325 www 4976: my ($symb,$uname,$udom)=@_;
1.620 albertel 4977: my $cid=$env{'request.course.id'};
1.109 www 4978: if ($cid) {
1.391 matthew 4979: # delete the stored spreadsheets for
4980: # - the student level sheet of this user in course's homespace
4981: # - the assessment level sheet for this resource
4982: # for this user in user's homespace
1.553 albertel 4983: # - current conditional state info
1.325 www 4984: my $key=$uname.':'.$udom.':';
1.109 www 4985: my $status=
1.299 matthew 4986: &del('nohist_calculatedsheets',
1.391 matthew 4987: [$key.'studentcalc:'],
1.620 albertel 4988: $env{'course.'.$cid.'.domain'},
4989: $env{'course.'.$cid.'.num'})
1.133 albertel 4990: .' '.
4991: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4992: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4993: unless ($status eq 'ok ok') {
4994: &logthis('Could not devalidate spreadsheet '.
1.325 www 4995: $uname.' at '.$udom.' for '.
1.109 www 4996: $symb.': '.$status);
1.133 albertel 4997: }
1.553 albertel 4998: &delenv('user.state.'.$cid);
1.109 www 4999: }
5000: }
5001:
1.265 albertel 5002: sub get_scalar {
5003: my ($string,$end) = @_;
5004: my $value;
5005: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5006: $value = $1;
5007: } elsif ($$string =~ s/^([^&]*?)&//) {
5008: $value = $1;
5009: }
5010: return &unescape($value);
5011: }
5012:
5013: sub array2str {
5014: my (@array) = @_;
5015: my $result=&arrayref2str(\@array);
5016: $result=~s/^__ARRAY_REF__//;
5017: $result=~s/__END_ARRAY_REF__$//;
5018: return $result;
5019: }
5020:
1.204 albertel 5021: sub arrayref2str {
5022: my ($arrayref) = @_;
1.265 albertel 5023: my $result='__ARRAY_REF__';
1.204 albertel 5024: foreach my $elem (@$arrayref) {
1.265 albertel 5025: if(ref($elem) eq 'ARRAY') {
5026: $result.=&arrayref2str($elem).'&';
5027: } elsif(ref($elem) eq 'HASH') {
5028: $result.=&hashref2str($elem).'&';
5029: } elsif(ref($elem)) {
5030: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5031: } else {
5032: $result.=&escape($elem).'&';
5033: }
5034: }
5035: $result=~s/\&$//;
1.265 albertel 5036: $result .= '__END_ARRAY_REF__';
1.204 albertel 5037: return $result;
5038: }
5039:
1.168 albertel 5040: sub hash2str {
1.204 albertel 5041: my (%hash) = @_;
5042: my $result=&hashref2str(\%hash);
1.265 albertel 5043: $result=~s/^__HASH_REF__//;
5044: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5045: return $result;
5046: }
5047:
5048: sub hashref2str {
5049: my ($hashref)=@_;
1.265 albertel 5050: my $result='__HASH_REF__';
1.800 albertel 5051: foreach my $key (sort(keys(%$hashref))) {
5052: if (ref($key) eq 'ARRAY') {
5053: $result.=&arrayref2str($key).'=';
5054: } elsif (ref($key) eq 'HASH') {
5055: $result.=&hashref2str($key).'=';
5056: } elsif (ref($key)) {
1.265 albertel 5057: $result.='=';
1.800 albertel 5058: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5059: } else {
1.1132 raeburn 5060: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5061: }
5062:
1.800 albertel 5063: if(ref($hashref->{$key}) eq 'ARRAY') {
5064: $result.=&arrayref2str($hashref->{$key}).'&';
5065: } elsif(ref($hashref->{$key}) eq 'HASH') {
5066: $result.=&hashref2str($hashref->{$key}).'&';
5067: } elsif(ref($hashref->{$key})) {
1.265 albertel 5068: $result.='&';
1.800 albertel 5069: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5070: } else {
1.800 albertel 5071: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5072: }
5073: }
1.168 albertel 5074: $result=~s/\&$//;
1.265 albertel 5075: $result .= '__END_HASH_REF__';
1.168 albertel 5076: return $result;
5077: }
5078:
5079: sub str2hash {
1.265 albertel 5080: my ($string)=@_;
5081: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5082: return %$hash;
5083: }
5084:
5085: sub str2hashref {
1.168 albertel 5086: my ($string) = @_;
1.265 albertel 5087:
5088: my %hash;
5089:
5090: if($string !~ /^__HASH_REF__/) {
5091: if (! ($string eq '' || !defined($string))) {
5092: $hash{'error'}='Not hash reference';
5093: }
5094: return (\%hash, $string);
5095: }
5096:
5097: $string =~ s/^__HASH_REF__//;
5098:
5099: while($string !~ /^__END_HASH_REF__/) {
5100: #key
5101: my $key='';
5102: if($string =~ /^__HASH_REF__/) {
5103: ($key, $string)=&str2hashref($string);
5104: if(defined($key->{'error'})) {
5105: $hash{'error'}='Bad data';
5106: return (\%hash, $string);
5107: }
5108: } elsif($string =~ /^__ARRAY_REF__/) {
5109: ($key, $string)=&str2arrayref($string);
5110: if($key->[0] eq 'Array reference error') {
5111: $hash{'error'}='Bad data';
5112: return (\%hash, $string);
5113: }
5114: } else {
5115: $string =~ s/^(.*?)=//;
1.267 albertel 5116: $key=&unescape($1);
1.265 albertel 5117: }
5118: $string =~ s/^=//;
5119:
5120: #value
5121: my $value='';
5122: if($string =~ /^__HASH_REF__/) {
5123: ($value, $string)=&str2hashref($string);
5124: if(defined($value->{'error'})) {
5125: $hash{'error'}='Bad data';
5126: return (\%hash, $string);
5127: }
5128: } elsif($string =~ /^__ARRAY_REF__/) {
5129: ($value, $string)=&str2arrayref($string);
5130: if($value->[0] eq 'Array reference error') {
5131: $hash{'error'}='Bad data';
5132: return (\%hash, $string);
5133: }
5134: } else {
5135: $value=&get_scalar(\$string,'__END_HASH_REF__');
5136: }
5137: $string =~ s/^&//;
5138:
5139: $hash{$key}=$value;
1.204 albertel 5140: }
1.265 albertel 5141:
5142: $string =~ s/^__END_HASH_REF__//;
5143:
5144: return (\%hash, $string);
1.204 albertel 5145: }
5146:
5147: sub str2array {
1.265 albertel 5148: my ($string)=@_;
5149: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5150: return @$array;
5151: }
5152:
5153: sub str2arrayref {
1.204 albertel 5154: my ($string) = @_;
1.265 albertel 5155: my @array;
5156:
5157: if($string !~ /^__ARRAY_REF__/) {
5158: if (! ($string eq '' || !defined($string))) {
5159: $array[0]='Array reference error';
5160: }
5161: return (\@array, $string);
5162: }
5163:
5164: $string =~ s/^__ARRAY_REF__//;
5165:
5166: while($string !~ /^__END_ARRAY_REF__/) {
5167: my $value='';
5168: if($string =~ /^__HASH_REF__/) {
5169: ($value, $string)=&str2hashref($string);
5170: if(defined($value->{'error'})) {
5171: $array[0] ='Array reference error';
5172: return (\@array, $string);
5173: }
5174: } elsif($string =~ /^__ARRAY_REF__/) {
5175: ($value, $string)=&str2arrayref($string);
5176: if($value->[0] eq 'Array reference error') {
5177: $array[0] ='Array reference error';
5178: return (\@array, $string);
5179: }
5180: } else {
5181: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5182: }
5183: $string =~ s/^&//;
5184:
5185: push(@array, $value);
1.191 harris41 5186: }
1.265 albertel 5187:
5188: $string =~ s/^__END_ARRAY_REF__//;
5189:
5190: return (\@array, $string);
1.168 albertel 5191: }
5192:
1.167 albertel 5193: # -------------------------------------------------------------------Temp Store
5194:
1.168 albertel 5195: sub tmpreset {
5196: my ($symb,$namespace,$domain,$stuname) = @_;
5197: if (!$symb) {
5198: $symb=&symbread();
1.620 albertel 5199: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5200: }
5201: $symb=escape($symb);
5202:
1.620 albertel 5203: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5204: $namespace=~s/\//\_/g;
5205: $namespace=~s/\W//g;
5206:
1.620 albertel 5207: if (!$domain) { $domain=$env{'user.domain'}; }
5208: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5209: if ($domain eq 'public' && $stuname eq 'public') {
5210: $stuname=$ENV{'REMOTE_ADDR'};
5211: }
1.1117 foxr 5212: my $path=LONCAPA::tempdir();
1.168 albertel 5213: my %hash;
5214: if (tie(%hash,'GDBM_File',
5215: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5216: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5217: foreach my $key (keys(%hash)) {
1.180 albertel 5218: if ($key=~ /:$symb/) {
1.168 albertel 5219: delete($hash{$key});
5220: }
5221: }
5222: }
5223: }
5224:
1.167 albertel 5225: sub tmpstore {
1.168 albertel 5226: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5227:
5228: if (!$symb) {
5229: $symb=&symbread();
1.620 albertel 5230: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5231: }
5232: $symb=escape($symb);
5233:
5234: if (!$namespace) {
5235: # I don't think we would ever want to store this for a course.
5236: # it seems this will only be used if we don't have a course.
1.620 albertel 5237: #$namespace=$env{'request.course.id'};
1.168 albertel 5238: #if (!$namespace) {
1.620 albertel 5239: $namespace=$env{'request.state'};
1.168 albertel 5240: #}
5241: }
5242: $namespace=~s/\//\_/g;
5243: $namespace=~s/\W//g;
1.620 albertel 5244: if (!$domain) { $domain=$env{'user.domain'}; }
5245: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5246: if ($domain eq 'public' && $stuname eq 'public') {
5247: $stuname=$ENV{'REMOTE_ADDR'};
5248: }
1.168 albertel 5249: my $now=time;
5250: my %hash;
1.1117 foxr 5251: my $path=LONCAPA::tempdir();
1.168 albertel 5252: if (tie(%hash,'GDBM_File',
5253: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5254: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5255: $hash{"version:$symb"}++;
5256: my $version=$hash{"version:$symb"};
5257: my $allkeys='';
5258: foreach my $key (keys(%$storehash)) {
5259: $allkeys.=$key.':';
1.591 albertel 5260: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5261: }
5262: $hash{"$version:$symb:timestamp"}=$now;
5263: $allkeys.='timestamp';
5264: $hash{"$version:keys:$symb"}=$allkeys;
5265: if (untie(%hash)) {
5266: return 'ok';
5267: } else {
5268: return "error:$!";
5269: }
5270: } else {
5271: return "error:$!";
5272: }
5273: }
1.167 albertel 5274:
1.168 albertel 5275: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5276:
1.168 albertel 5277: sub tmprestore {
5278: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5279:
1.168 albertel 5280: if (!$symb) {
5281: $symb=&symbread();
1.620 albertel 5282: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5283: }
5284: $symb=escape($symb);
5285:
1.620 albertel 5286: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5287:
1.620 albertel 5288: if (!$domain) { $domain=$env{'user.domain'}; }
5289: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5290: if ($domain eq 'public' && $stuname eq 'public') {
5291: $stuname=$ENV{'REMOTE_ADDR'};
5292: }
1.168 albertel 5293: my %returnhash;
5294: $namespace=~s/\//\_/g;
5295: $namespace=~s/\W//g;
5296: my %hash;
1.1117 foxr 5297: my $path=LONCAPA::tempdir();
1.168 albertel 5298: if (tie(%hash,'GDBM_File',
5299: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5300: &GDBM_READER(),0640)) {
1.168 albertel 5301: my $version=$hash{"version:$symb"};
5302: $returnhash{'version'}=$version;
5303: my $scope;
5304: for ($scope=1;$scope<=$version;$scope++) {
5305: my $vkeys=$hash{"$scope:keys:$symb"};
5306: my @keys=split(/:/,$vkeys);
5307: my $key;
5308: $returnhash{"$scope:keys"}=$vkeys;
5309: foreach $key (@keys) {
1.591 albertel 5310: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5311: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5312: }
5313: }
1.168 albertel 5314: if (!(untie(%hash))) {
5315: return "error:$!";
5316: }
5317: } else {
5318: return "error:$!";
5319: }
5320: return %returnhash;
1.167 albertel 5321: }
5322:
1.9 www 5323: # ----------------------------------------------------------------------- Store
5324:
5325: sub store {
1.1172.2.64 raeburn 5326: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5327: my $home='';
5328:
1.168 albertel 5329: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5330:
1.213 www 5331: $symb=&symbclean($symb);
1.122 albertel 5332: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5333:
1.620 albertel 5334: if (!$domain) { $domain=$env{'user.domain'}; }
5335: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5336:
5337: &devalidate($symb,$stuname,$domain);
1.109 www 5338:
5339: $symb=escape($symb);
1.187 www 5340: if (!$namespace) {
1.620 albertel 5341: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5342: return '';
5343: }
5344: }
1.620 albertel 5345: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5346:
5347: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5348: $$storehash{'host'}=$perlvar{'lonHostID'};
5349:
1.12 www 5350: my $namevalue='';
1.800 albertel 5351: foreach my $key (keys(%$storehash)) {
5352: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5353: }
1.12 www 5354: $namevalue=~s/\&$//;
1.187 www 5355: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5356: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5357: }
5358:
1.47 www 5359: # -------------------------------------------------------------- Critical Store
5360:
5361: sub cstore {
1.1172.2.64 raeburn 5362: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5363: my $home='';
5364:
1.168 albertel 5365: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5366:
1.213 www 5367: $symb=&symbclean($symb);
1.122 albertel 5368: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5369:
1.620 albertel 5370: if (!$domain) { $domain=$env{'user.domain'}; }
5371: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5372:
5373: &devalidate($symb,$stuname,$domain);
1.109 www 5374:
5375: $symb=escape($symb);
1.187 www 5376: if (!$namespace) {
1.620 albertel 5377: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5378: return '';
5379: }
5380: }
1.620 albertel 5381: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5382:
5383: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5384: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5385:
1.47 www 5386: my $namevalue='';
1.800 albertel 5387: foreach my $key (keys(%$storehash)) {
5388: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5389: }
1.47 www 5390: $namevalue=~s/\&$//;
1.187 www 5391: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5392: return critical
1.1172.2.64 raeburn 5393: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5394: }
5395:
1.9 www 5396: # --------------------------------------------------------------------- Restore
5397:
5398: sub restore {
1.124 www 5399: my ($symb,$namespace,$domain,$stuname) = @_;
5400: my $home='';
5401:
1.168 albertel 5402: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5403:
1.122 albertel 5404: if (!$symb) {
1.1172.2.26 raeburn 5405: return if ($namespace eq 'courserequests');
5406: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5407: } else {
1.1172.2.26 raeburn 5408: unless ($namespace eq 'courserequests') {
5409: $symb=&escape(&symbclean($symb));
5410: }
1.122 albertel 5411: }
1.188 www 5412: if (!$namespace) {
1.620 albertel 5413: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5414: return '';
5415: }
5416: }
1.620 albertel 5417: if (!$domain) { $domain=$env{'user.domain'}; }
5418: if (!$stuname) { $stuname=$env{'user.name'}; }
5419: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5420: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5421:
1.12 www 5422: my %returnhash=();
1.800 albertel 5423: foreach my $line (split(/\&/,$answer)) {
5424: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5425: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5426: }
1.75 www 5427: my $version;
5428: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5429: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5430: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5431: }
1.75 www 5432: }
1.13 www 5433: return %returnhash;
1.34 www 5434: }
5435:
5436: # ---------------------------------------------------------- Course Description
1.1118 foxr 5437: #
5438: #
1.34 www 5439:
5440: sub coursedescription {
1.731 albertel 5441: my ($courseid,$args)=@_;
1.34 www 5442: $courseid=~s/^\///;
1.49 www 5443: $courseid=~s/\_/\//g;
1.34 www 5444: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5445: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5446: my $normalid=$cdomain.'_'.$cnum;
5447: # need to always cache even if we get errors otherwise we keep
5448: # trying and trying and trying to get the course description.
5449: my %envhash=();
5450: my %returnhash=();
1.731 albertel 5451:
5452: my $expiretime=600;
5453: if ($env{'request.course.id'} eq $normalid) {
5454: $expiretime=120;
5455: }
5456:
5457: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5458: if (!$args->{'freshen_cache'}
5459: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5460: foreach my $key (keys(%env)) {
5461: next if ($key !~ /^\Q$prefix\E(.*)/);
5462: my ($setting) = $1;
5463: $returnhash{$setting} = $env{$key};
5464: }
5465: return %returnhash;
5466: }
5467:
1.1118 foxr 5468: # get the data again
5469:
1.731 albertel 5470: if (!$args->{'one_time'}) {
5471: $envhash{'course.'.$normalid.'.last_cache'}=time;
5472: }
1.811 albertel 5473:
1.34 www 5474: if ($chome ne 'no_host') {
1.302 albertel 5475: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5476: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5477: my $username = $env{'user.name'}; # Defult username
5478: if(defined $args->{'user'}) {
5479: $username = $args->{'user'};
5480: }
1.129 albertel 5481: $returnhash{'home'}= $chome;
5482: $returnhash{'domain'} = $cdomain;
5483: $returnhash{'num'} = $cnum;
1.741 raeburn 5484: if (!defined($returnhash{'type'})) {
5485: $returnhash{'type'} = 'Course';
5486: }
1.130 albertel 5487: while (my ($name,$value) = each %returnhash) {
1.53 www 5488: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5489: }
1.270 www 5490: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5491: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5492: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5493: $envhash{'course.'.$normalid.'.home'}=$chome;
5494: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5495: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5496: }
5497: }
1.731 albertel 5498: if (!$args->{'one_time'}) {
1.949 raeburn 5499: &appenv(\%envhash);
1.731 albertel 5500: }
1.302 albertel 5501: return %returnhash;
1.461 www 5502: }
5503:
1.1080 raeburn 5504: sub update_released_required {
5505: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5506: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5507: $cid = $env{'request.course.id'};
5508: $cdom = $env{'course.'.$cid.'.domain'};
5509: $cnum = $env{'course.'.$cid.'.num'};
5510: $chome = $env{'course.'.$cid.'.home'};
5511: }
5512: if ($needsrelease) {
5513: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5514: my $needsupdate;
5515: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5516: $needsupdate = 1;
5517: } else {
5518: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5519: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5520: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5521: $needsupdate = 1;
5522: }
5523: }
5524: if ($needsupdate) {
5525: my %needshash = (
5526: 'internal.releaserequired' => $needsrelease,
5527: );
5528: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5529: if ($putresult eq 'ok') {
5530: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5531: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5532: if (ref($crsinfo{$cid}) eq 'HASH') {
5533: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5534: &courseidput($cdom,\%crsinfo,$chome,'notime');
5535: }
5536: }
5537: }
5538: }
5539: return;
5540: }
5541:
1.461 www 5542: # -------------------------------------------------See if a user is privileged
5543:
5544: sub privileged {
1.1172.2.23 raeburn 5545: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5546: my $now = time;
1.1172.2.23 raeburn 5547: my $roles;
5548: if (ref($possroles) eq 'ARRAY') {
5549: $roles = $possroles;
5550: } else {
5551: $roles = ['dc','su'];
5552: }
5553: if (ref($possdomains) eq 'ARRAY') {
5554: my %privileged = &privileged_by_domain($possdomains,$roles);
5555: foreach my $dom (@{$possdomains}) {
5556: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5557: (ref($privileged{$dom}) eq 'HASH')) {
5558: foreach my $role (@{$roles}) {
5559: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5560: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5561: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5562: return 1 unless (($end && $end < $now) ||
5563: ($start && $start > $now));
5564: }
5565: }
5566: }
5567: }
5568: }
5569: } else {
5570: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5571: my $now = time;
1.1170 droeschl 5572:
1.1172.2.58 raeburn 5573: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5574: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5575: if (grep(/^\Q$trole\E$/,@{$roles})) {
5576: return 1 unless ($tend && $tend < $now)
5577: or ($tstart && $tstart > $now);
1.1170 droeschl 5578: }
1.1172.2.23 raeburn 5579: }
5580: }
1.461 www 5581: return 0;
1.9 www 5582: }
1.1 albertel 5583:
1.1172.2.23 raeburn 5584: sub privileged_by_domain {
5585: my ($domains,$roles) = @_;
5586: my %privileged = ();
5587: my $cachetime = 60*60*24;
5588: my $now = time;
5589: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5590: return %privileged;
5591: }
5592: foreach my $dom (@{$domains}) {
5593: next if (ref($privileged{$dom}) eq 'HASH');
5594: my $needroles;
5595: foreach my $role (@{$roles}) {
5596: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5597: if (defined($cached)) {
5598: if (ref($result) eq 'HASH') {
5599: $privileged{$dom}{$role} = $result;
5600: }
5601: } else {
5602: $needroles = 1;
5603: }
5604: }
5605: if ($needroles) {
5606: my %dompersonnel = &get_domain_roles($dom,$roles);
5607: $privileged{$dom} = {};
5608: foreach my $server (keys(%dompersonnel)) {
5609: if (ref($dompersonnel{$server}) eq 'HASH') {
5610: foreach my $item (keys(%{$dompersonnel{$server}})) {
5611: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5612: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5613: next if ($end && $end < $now);
5614: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5615: $dompersonnel{$server}{$item};
5616: }
5617: }
5618: }
5619: if (ref($privileged{$dom}) eq 'HASH') {
5620: foreach my $role (@{$roles}) {
5621: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5622: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5623: } else {
5624: my %hash = ();
5625: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5626: }
5627: }
5628: }
5629: }
5630: }
5631: return %privileged;
5632: }
5633:
1.103 harris41 5634: # -------------------------------------------------------- Get user privileges
1.11 www 5635:
5636: sub rolesinit {
1.1169 droeschl 5637: my ($domain, $username) = @_;
5638: my %userroles = ('user.login.time' => time);
5639: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5640:
5641: # firstaccess and timerinterval are related to timed maps/resources.
5642: # also, blocking can be triggered by an activating timer
5643: # it's saved in the user's %env.
5644: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5645: my %timerinterval = &dump('timerinterval', $domain, $username);
5646: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5647: %timerintchk, %timerintenv);
5648:
1.1162 raeburn 5649: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5650: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5651: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5652: }
1.1169 droeschl 5653:
1.1162 raeburn 5654: foreach my $key (keys(%timerinterval)) {
5655: my ($cid,$rest) = split(/\0/,$key);
5656: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5657: }
1.1169 droeschl 5658:
1.11 www 5659: my %allroles=();
1.1162 raeburn 5660: my %allgroups=();
1.11 www 5661:
1.1172.2.58 raeburn 5662: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5663: my $role = $rolesdump{$area};
5664: $area =~ s/\_\w\w$//;
5665:
5666: my ($trole, $tend, $tstart, $group_privs);
5667:
5668: if ($role =~ /^cr/) {
5669: # Custom role, defined by a user
5670: # e.g., user.role.cr/msu/smith/mynewrole
5671: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5672: $trole = $1;
5673: ($tend, $tstart) = split('_', $2);
5674: } else {
5675: $trole = $role;
5676: }
5677: } elsif ($role =~ m|^gr/|) {
5678: # Role of member in a group, defined within a course/community
5679: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5680: ($trole, $tend, $tstart) = split(/_/, $role);
5681: next if $tstart eq '-1';
5682: ($trole, $group_privs) = split(/\//, $trole);
5683: $group_privs = &unescape($group_privs);
5684: } else {
5685: # Just a normal role, defined in roles.tab
5686: ($trole, $tend, $tstart) = split(/_/,$role);
5687: }
5688:
5689: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5690: $username);
5691: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5692:
5693: # role expired or not available yet?
5694: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5695: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5696:
5697: next if $area eq '' or $trole eq '';
5698:
5699: my $spec = "$trole.$area";
5700: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5701:
5702: if ($trole =~ /^cr\//) {
5703: # Custom role, defined by a user
5704: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5705: } elsif ($trole eq 'gr') {
5706: # Role of a member in a group, defined within a course/community
5707: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5708: next;
5709: } else {
5710: # Normal role, defined in roles.tab
5711: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5712: }
5713:
5714: my $cid = $tdomain.'_'.$trest;
5715: unless ($firstaccchk{$cid}) {
5716: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5717: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5718: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5719: $coursetimerstarts{$cid}{$item};
5720: }
5721: }
5722: $firstaccchk{$cid} = 1;
5723: }
5724: unless ($timerintchk{$cid}) {
5725: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5726: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5727: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5728: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5729: }
1.12 www 5730: }
1.1169 droeschl 5731: $timerintchk{$cid} = 1;
1.191 harris41 5732: }
1.11 www 5733: }
1.1169 droeschl 5734:
1.1172.2.91 raeburn 5735: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5736: \%allroles, \%allgroups);
1.1169 droeschl 5737: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 5738: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5739:
1.1162 raeburn 5740: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5741: }
5742:
1.567 raeburn 5743: sub set_arearole {
1.1172.2.19 raeburn 5744: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5745: unless ($nolog) {
1.567 raeburn 5746: # log the associated role with the area
1.1172.2.19 raeburn 5747: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5748: }
1.743 albertel 5749: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5750: }
5751:
5752: sub custom_roleprivs {
5753: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5754: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5755: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5756: if (&hostname($homsvr) ne '') {
1.567 raeburn 5757: my ($rdummy,$roledef)=
5758: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5759: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5760: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5761: if (defined($syspriv)) {
1.1043 raeburn 5762: if ($trest =~ /^$match_community$/) {
5763: $syspriv =~ s/bre\&S//;
5764: }
1.567 raeburn 5765: $$allroles{'cm./'}.=':'.$syspriv;
5766: $$allroles{$spec.'./'}.=':'.$syspriv;
5767: }
5768: if ($tdomain ne '') {
5769: if (defined($dompriv)) {
5770: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5771: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5772: }
5773: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 5774: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5775: my $rolename = $1;
5776: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5777: }
1.567 raeburn 5778: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5779: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5780: }
5781: }
5782: }
5783: }
5784: }
5785:
1.1172.2.89 raeburn 5786: sub course_adhocrole_privs {
5787: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5788: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5789: if ($overrides{"internal.adhocpriv.$rolename"}) {
5790: my (%currprivs,%storeprivs);
5791: foreach my $item (split(/:/,$coursepriv)) {
5792: my ($priv,$restrict) = split(/\&/,$item);
5793: $currprivs{$priv} = $restrict;
5794: }
5795: my (%possadd,%possremove,%full);
5796: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5797: my ($priv,$restrict)=split(/\&/,$item);
5798: $full{$priv} = $restrict;
5799: }
5800: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5801: next if ($item eq '');
5802: my ($rule,$rest) = split(/=/,$item);
5803: next unless (($rule eq 'off') || ($rule eq 'on'));
5804: foreach my $priv (split(/:/,$rest)) {
5805: if ($priv ne '') {
5806: if ($rule eq 'off') {
5807: $possremove{$priv} = 1;
5808: } else {
5809: $possadd{$priv} = 1;
5810: }
5811: }
5812: }
5813: }
5814: foreach my $priv (sort(keys(%full))) {
5815: if (exists($currprivs{$priv})) {
5816: unless (exists($possremove{$priv})) {
5817: $storeprivs{$priv} = $currprivs{$priv};
5818: }
5819: } elsif (exists($possadd{$priv})) {
5820: $storeprivs{$priv} = $full{$priv};
5821: }
5822: }
5823: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5824: }
5825: return $coursepriv;
5826: }
5827:
1.678 raeburn 5828: sub group_roleprivs {
5829: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5830: my $access = 1;
5831: my $now = time;
5832: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5833: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5834: if ($access) {
1.811 albertel 5835: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5836: $$allgroups{$course}{$group} .=':'.$group_privs;
5837: }
5838: }
1.567 raeburn 5839:
5840: sub standard_roleprivs {
5841: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5842: if (defined($pr{$trole.':s'})) {
5843: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5844: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5845: }
5846: if ($tdomain ne '') {
5847: if (defined($pr{$trole.':d'})) {
5848: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5849: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5850: }
5851: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5852: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5853: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5854: }
5855: }
5856: }
5857:
5858: sub set_userprivs {
1.1064 raeburn 5859: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5860: my $author=0;
5861: my $adv=0;
1.1172.2.91 raeburn 5862: my $rar=0;
1.678 raeburn 5863: my %grouproles = ();
5864: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5865: my @groupkeys;
1.1000 raeburn 5866: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5867: push(@groupkeys,$role);
5868: }
5869: if (ref($groups_roles) eq 'HASH') {
5870: foreach my $key (keys(%{$groups_roles})) {
5871: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5872: push(@groupkeys,$key);
5873: }
5874: }
5875: }
5876: if (@groupkeys > 0) {
5877: foreach my $role (@groupkeys) {
5878: my ($trole,$area,$sec,$extendedarea);
5879: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5880: $trole = $1;
5881: $area = $2;
5882: $sec = $3;
5883: $extendedarea = $area.$sec;
5884: if (exists($$allgroups{$area})) {
5885: foreach my $group (keys(%{$$allgroups{$area}})) {
5886: my $spec = $trole.'.'.$extendedarea;
5887: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5888: $$allgroups{$area}{$group};
1.1064 raeburn 5889: }
1.678 raeburn 5890: }
5891: }
5892: }
5893: }
5894: }
1.800 albertel 5895: foreach my $group (keys(%grouproles)) {
5896: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5897: }
1.800 albertel 5898: foreach my $role (keys(%{$allroles})) {
5899: my %thesepriv;
1.941 raeburn 5900: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5901: foreach my $item (split(/:/,$$allroles{$role})) {
5902: if ($item ne '') {
5903: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5904: if ($restrictions eq '') {
5905: $thesepriv{$privilege}='F';
5906: } elsif ($thesepriv{$privilege} ne 'F') {
5907: $thesepriv{$privilege}.=$restrictions;
5908: }
5909: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 5910: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5911: }
5912: }
5913: my $thesestr='';
1.1104 raeburn 5914: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5915: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5916: }
5917: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5918: }
1.1172.2.91 raeburn 5919: return ($author,$adv,$rar);
1.567 raeburn 5920: }
5921:
1.994 raeburn 5922: sub role_status {
1.1104 raeburn 5923: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5924: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5925: my ($one,$two) = split(m{\./},$rolekey,2);
5926: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5927: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5928: $$where = '/'.$two;
1.994 raeburn 5929: $$trolecode=$$role.'.'.$$where;
5930: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5931: $$tstatus='is';
1.1104 raeburn 5932: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5933: $$tstatus='future';
1.1034 raeburn 5934: if ($$tstart<$now) {
5935: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5936: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5937: my (%allroles,%allgroups,$group_privs,
5938: %groups_roles,@rolecodes);
1.1002 raeburn 5939: my %userroles = (
5940: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5941: );
1.1064 raeburn 5942: @rolecodes = ('cm');
1.1002 raeburn 5943: my $spec=$$role.'.'.$$where;
5944: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5945: if ($$role =~ /^cr\//) {
5946: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5947: push(@rolecodes,'cr');
1.1002 raeburn 5948: } elsif ($$role eq 'gr') {
1.1064 raeburn 5949: push(@rolecodes,$$role);
1.1002 raeburn 5950: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5951: $env{'user.name'});
1.1064 raeburn 5952: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5953: (undef,my $group_privs) = split(/\//,$trole);
5954: $group_privs = &unescape($group_privs);
5955: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5956: 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 5957: &get_groups_roles($tdomain,$trest,
5958: \%course_roles,\@rolecodes,
5959: \%groups_roles);
1.1002 raeburn 5960: } else {
1.1064 raeburn 5961: push(@rolecodes,$$role);
1.1002 raeburn 5962: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5963: }
1.1172.2.91 raeburn 5964: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
5965: \%groups_roles);
1.1064 raeburn 5966: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 5967: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 5968: }
5969: }
1.1034 raeburn 5970: $$tstatus = 'is';
1.1002 raeburn 5971: }
1.994 raeburn 5972: }
5973: if ($$tend) {
1.1104 raeburn 5974: if ($$tend<$update) {
1.994 raeburn 5975: $$tstatus='expired';
5976: } elsif ($$tend<$now) {
5977: $$tstatus='will_not';
5978: }
5979: }
5980: }
5981: }
5982: }
5983:
1.1104 raeburn 5984: sub get_groups_roles {
5985: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5986: return unless((ref($cdom_courseroles) eq 'HASH') &&
5987: (ref($rolecodes) eq 'ARRAY') &&
5988: (ref($groups_roles) eq 'HASH'));
5989: if (keys(%{$cdom_courseroles}) > 0) {
5990: my ($cnum) = ($rest =~ /^($match_courseid)/);
5991: if ($cdom ne '' && $cnum ne '') {
5992: foreach my $key (keys(%{$cdom_courseroles})) {
5993: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5994: my $crsrole = $1;
5995: my $crssec = $2;
5996: if ($crsrole =~ /^cr/) {
5997: unless (grep(/^cr$/,@{$rolecodes})) {
5998: push(@{$rolecodes},'cr');
5999: }
6000: } else {
6001: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6002: push(@{$rolecodes},$crsrole);
6003: }
6004: }
6005: my $rolekey = "$crsrole./$cdom/$cnum";
6006: if ($crssec ne '') {
6007: $rolekey .= "/$crssec";
6008: }
6009: $rolekey .= './';
6010: $groups_roles->{$rolekey} = $rolecodes;
6011: }
6012: }
6013: }
6014: }
6015: return;
6016: }
6017:
6018: sub delete_env_groupprivs {
6019: my ($where,$courseroles,$possroles) = @_;
6020: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6021: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6022: unless (ref($courseroles->{$udom}) eq 'HASH') {
6023: %{$courseroles->{$udom}} =
6024: &get_my_roles('','','userroles',['active'],
6025: $possroles,[$udom],1);
6026: }
6027: if (ref($courseroles->{$udom}) eq 'HASH') {
6028: foreach my $item (keys(%{$courseroles->{$udom}})) {
6029: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6030: my $area = '/'.$cdom.'/'.$cnum;
6031: my $privkey = "user.priv.$crsrole.$area";
6032: if ($crssec ne '') {
6033: $privkey .= '/'.$crssec;
6034: }
6035: $privkey .= ".$area/$group";
6036: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6037: }
6038: }
6039: return;
6040: }
6041:
1.994 raeburn 6042: sub check_adhoc_privs {
1.1172.2.86 raeburn 6043: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6044: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6045: if ($sec) {
6046: $cckey .= '/'.$sec;
6047: }
1.1172.2.9 raeburn 6048: my $setprivs;
1.994 raeburn 6049: if ($env{$cckey}) {
6050: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6051: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6052: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6053: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6054: $setprivs = 1;
1.994 raeburn 6055: }
6056: } else {
1.1172.2.87 raeburn 6057: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6058: $setprivs = 1;
1.994 raeburn 6059: }
1.1172.2.9 raeburn 6060: return $setprivs;
1.994 raeburn 6061: }
6062:
6063: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6064: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6065: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6066: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6067: if ($sec ne '') {
6068: $area .= '/'.$sec;
6069: }
1.994 raeburn 6070: my $spec = $role.'.'.$area;
6071: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6072: $env{'user.name'},1);
1.1172.2.84 raeburn 6073: my %rolehash = ();
1.1172.2.89 raeburn 6074: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6075: my $rolename = $1;
1.1172.2.84 raeburn 6076: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6077: my %domdef = &get_domain_defaults($dcdom);
6078: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6079: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6080: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6081: }
6082: }
1.1172.2.84 raeburn 6083: } else {
6084: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6085: }
1.1172.2.91 raeburn 6086: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6087: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6088: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6089: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6090: &appenv( {'request.role' => $spec,
6091: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6092: 'request.course.sec' => $sec,
1.1088 raeburn 6093: }
6094: );
6095: my $tadv=0;
6096: if (&allowed('adv') eq 'F') { $tadv=1; }
6097: &appenv({'request.role.adv' => $tadv});
6098: }
1.994 raeburn 6099: }
6100:
1.12 www 6101: # --------------------------------------------------------------- get interface
6102:
6103: sub get {
1.131 albertel 6104: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6105: my $items='';
1.800 albertel 6106: foreach my $item (@$storearr) {
6107: $items.=&escape($item).'&';
1.191 harris41 6108: }
1.12 www 6109: $items=~s/\&$//;
1.620 albertel 6110: if (!$udomain) { $udomain=$env{'user.domain'}; }
6111: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6112: my $uhome=&homeserver($uname,$udomain);
6113:
1.133 albertel 6114: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6115: my @pairs=split(/\&/,$rep);
1.273 albertel 6116: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6117: return @pairs;
6118: }
1.15 www 6119: my %returnhash=();
1.42 www 6120: my $i=0;
1.800 albertel 6121: foreach my $item (@$storearr) {
6122: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6123: $i++;
1.191 harris41 6124: }
1.15 www 6125: return %returnhash;
1.27 www 6126: }
6127:
6128: # --------------------------------------------------------------- del interface
6129:
6130: sub del {
1.133 albertel 6131: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6132: my $items='';
1.800 albertel 6133: foreach my $item (@$storearr) {
6134: $items.=&escape($item).'&';
1.191 harris41 6135: }
1.984 neumanie 6136:
1.27 www 6137: $items=~s/\&$//;
1.620 albertel 6138: if (!$udomain) { $udomain=$env{'user.domain'}; }
6139: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6140: my $uhome=&homeserver($uname,$udomain);
6141: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6142: }
6143:
6144: # -------------------------------------------------------------- dump interface
6145:
1.1172.2.22 raeburn 6146: sub unserialize {
6147: my ($rep, $escapedkeys) = @_;
6148:
6149: return {} if $rep =~ /^error/;
6150:
6151: my %returnhash=();
6152: foreach my $item (split(/\&/,$rep)) {
6153: my ($key, $value) = split(/=/, $item, 2);
6154: $key = unescape($key) unless $escapedkeys;
6155: next if $key =~ /^error: 2 /;
6156: $returnhash{$key} = &thaw_unescape($value);
6157: }
6158: return \%returnhash;
6159: }
6160:
6161: # see Lond::dump_with_regexp
6162: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6163: sub dump {
1.1172.2.22 raeburn 6164: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6165: if (!$udomain) { $udomain=$env{'user.domain'}; }
6166: if (!$uname) { $uname=$env{'user.name'}; }
6167: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6168:
1.1172.2.55 raeburn 6169: if ($regexp) {
6170: $regexp=&escape($regexp);
6171: } else {
6172: $regexp='.';
6173: }
1.1172.2.22 raeburn 6174: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6175: # user is hosted on this machine
1.1172.2.55 raeburn 6176: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6177: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6178: return %{&unserialize($reply, $escapedkeys)};
6179: }
1.1166 raeburn 6180: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6181: my @pairs=split(/\&/,$rep);
6182: my %returnhash=();
1.1098 foxr 6183: if (!($rep =~ /^error/ )) {
6184: foreach my $item (@pairs) {
6185: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6186: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6187: next if ($key =~ /^error: 2 /);
6188: $returnhash{$key}=&thaw_unescape($value);
6189: }
1.755 albertel 6190: }
6191: return %returnhash;
1.407 www 6192: }
6193:
1.1098 foxr 6194:
1.717 albertel 6195: # --------------------------------------------------------- dumpstore interface
6196:
6197: sub dumpstore {
6198: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6199: # same as dump but keys must be escaped. They may contain colon separated
6200: # lists of values that may themself contain colons (e.g. symbs).
6201: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6202: }
6203:
1.407 www 6204: # -------------------------------------------------------------- keys interface
6205:
6206: sub getkeys {
6207: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6208: if (!$udomain) { $udomain=$env{'user.domain'}; }
6209: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6210: my $uhome=&homeserver($uname,$udomain);
6211: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6212: my @keyarray=();
1.800 albertel 6213: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6214: next if ($key =~ /^error: 2 /);
1.800 albertel 6215: push(@keyarray,&unescape($key));
1.407 www 6216: }
6217: return @keyarray;
1.318 matthew 6218: }
6219:
1.319 matthew 6220: # --------------------------------------------------------------- currentdump
6221: sub currentdump {
1.328 matthew 6222: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6223: $courseid = $env{'request.course.id'} if (! defined($courseid));
6224: $sdom = $env{'user.domain'} if (! defined($sdom));
6225: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6226: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6227: my $rep;
6228:
6229: if (grep { $_ eq $uhome } current_machine_ids()) {
6230: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6231: $courseid)));
6232: } else {
6233: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6234: }
6235:
1.318 matthew 6236: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6237: #
1.318 matthew 6238: my %returnhash=();
1.319 matthew 6239: #
1.1172.2.93.4 2(raebur 6240:7): if ($rep eq 'unknown_cmd') {
1.319 matthew 6241: # an old lond will not know currentdump
6242: # Do a dump and make it look like a currentdump
1.822 albertel 6243: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6244: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6245: my %hash = @tmp;
6246: @tmp=();
1.424 matthew 6247: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6248: } else {
6249: my @pairs=split(/\&/,$rep);
1.800 albertel 6250: foreach my $pair (@pairs) {
6251: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6252: my ($symb,$param) = split(/:/,$key);
6253: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6254: &thaw_unescape($value);
1.319 matthew 6255: }
1.191 harris41 6256: }
1.12 www 6257: return %returnhash;
1.424 matthew 6258: }
6259:
6260: sub convert_dump_to_currentdump{
6261: my %hash = %{shift()};
6262: my %returnhash;
6263: # Code ripped from lond, essentially. The only difference
6264: # here is the unescaping done by lonnet::dump(). Conceivably
6265: # we might run in to problems with parameter names =~ /^v\./
6266: while (my ($key,$value) = each(%hash)) {
6267: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6268: $symb = &unescape($symb);
6269: $param = &unescape($param);
1.424 matthew 6270: next if ($v eq 'version' || $symb eq 'keys');
6271: next if (exists($returnhash{$symb}) &&
6272: exists($returnhash{$symb}->{$param}) &&
6273: $returnhash{$symb}->{'v.'.$param} > $v);
6274: $returnhash{$symb}->{$param}=$value;
6275: $returnhash{$symb}->{'v.'.$param}=$v;
6276: }
6277: #
6278: # Remove all of the keys in the hashes which keep track of
6279: # the version of the parameter.
6280: while (my ($symb,$param_hash) = each(%returnhash)) {
6281: # use a foreach because we are going to delete from the hash.
6282: foreach my $key (keys(%$param_hash)) {
6283: delete($param_hash->{$key}) if ($key =~ /^v\./);
6284: }
6285: }
6286: return \%returnhash;
1.12 www 6287: }
6288:
1.627 albertel 6289: # ------------------------------------------------------ critical inc interface
6290:
6291: sub cinc {
6292: return &inc(@_,'critical');
6293: }
6294:
1.449 matthew 6295: # --------------------------------------------------------------- inc interface
6296:
6297: sub inc {
1.627 albertel 6298: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6299: if (!$udomain) { $udomain=$env{'user.domain'}; }
6300: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6301: my $uhome=&homeserver($uname,$udomain);
6302: my $items='';
6303: if (! ref($store)) {
6304: # got a single value, so use that instead
6305: $items = &escape($store).'=&';
6306: } elsif (ref($store) eq 'SCALAR') {
6307: $items = &escape($$store).'=&';
6308: } elsif (ref($store) eq 'ARRAY') {
6309: $items = join('=&',map {&escape($_);} @{$store});
6310: } elsif (ref($store) eq 'HASH') {
6311: while (my($key,$value) = each(%{$store})) {
6312: $items.= &escape($key).'='.&escape($value).'&';
6313: }
6314: }
6315: $items=~s/\&$//;
1.627 albertel 6316: if ($critical) {
6317: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6318: } else {
6319: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6320: }
1.449 matthew 6321: }
6322:
1.12 www 6323: # --------------------------------------------------------------- put interface
6324:
6325: sub put {
1.134 albertel 6326: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6327: if (!$udomain) { $udomain=$env{'user.domain'}; }
6328: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6329: my $uhome=&homeserver($uname,$udomain);
1.12 www 6330: my $items='';
1.800 albertel 6331: foreach my $item (keys(%$storehash)) {
6332: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6333: }
1.12 www 6334: $items=~s/\&$//;
1.134 albertel 6335: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6336: }
6337:
1.631 albertel 6338: # ------------------------------------------------------------ newput interface
6339:
6340: sub newput {
6341: my ($namespace,$storehash,$udomain,$uname)=@_;
6342: if (!$udomain) { $udomain=$env{'user.domain'}; }
6343: if (!$uname) { $uname=$env{'user.name'}; }
6344: my $uhome=&homeserver($uname,$udomain);
6345: my $items='';
6346: foreach my $key (keys(%$storehash)) {
6347: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6348: }
6349: $items=~s/\&$//;
6350: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6351: }
6352:
6353: # --------------------------------------------------------- putstore interface
6354:
1.524 raeburn 6355: sub putstore {
1.1172.2.59 raeburn 6356: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6357: if (!$udomain) { $udomain=$env{'user.domain'}; }
6358: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6359: my $uhome=&homeserver($uname,$udomain);
6360: my $items='';
1.715 albertel 6361: foreach my $key (keys(%$storehash)) {
6362: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6363: }
1.715 albertel 6364: $items=~s/\&$//;
1.716 albertel 6365: my $esc_symb=&escape($symb);
6366: my $esc_v=&escape($version);
1.715 albertel 6367: my $reply =
1.716 albertel 6368: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6369: $uhome);
1.1172.2.59 raeburn 6370: if (($tolog) && ($reply eq 'ok')) {
6371: my $namevalue='';
6372: foreach my $key (keys(%{$storehash})) {
6373: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6374: }
6375: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6376: '&host='.&escape($perlvar{'lonHostID'}).
6377: '&version='.$esc_v.
6378: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6379: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6380: }
1.715 albertel 6381: if ($reply eq 'unknown_cmd') {
1.716 albertel 6382: # gfall back to way things use to be done
1.715 albertel 6383: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6384: $uname);
1.524 raeburn 6385: }
1.715 albertel 6386: return $reply;
6387: }
6388:
6389: sub old_putstore {
1.716 albertel 6390: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6391: if (!$udomain) { $udomain=$env{'user.domain'}; }
6392: if (!$uname) { $uname=$env{'user.name'}; }
6393: my $uhome=&homeserver($uname,$udomain);
6394: my %newstorehash;
1.800 albertel 6395: foreach my $item (keys(%$storehash)) {
6396: my $key = $version.':'.&escape($symb).':'.$item;
6397: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6398: }
6399: my $items='';
6400: my %allitems = ();
1.800 albertel 6401: foreach my $item (keys(%newstorehash)) {
6402: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6403: my $key = $1.':keys:'.$2;
6404: $allitems{$key} .= $3.':';
6405: }
1.800 albertel 6406: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6407: }
1.800 albertel 6408: foreach my $item (keys(%allitems)) {
6409: $allitems{$item} =~ s/\:$//;
6410: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6411: }
6412: $items=~s/\&$//;
6413: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6414: }
6415:
1.47 www 6416: # ------------------------------------------------------ critical put interface
6417:
6418: sub cput {
1.134 albertel 6419: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6420: if (!$udomain) { $udomain=$env{'user.domain'}; }
6421: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6422: my $uhome=&homeserver($uname,$udomain);
1.47 www 6423: my $items='';
1.800 albertel 6424: foreach my $item (keys(%$storehash)) {
6425: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6426: }
1.47 www 6427: $items=~s/\&$//;
1.134 albertel 6428: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6429: }
6430:
6431: # -------------------------------------------------------------- eget interface
6432:
6433: sub eget {
1.133 albertel 6434: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6435: my $items='';
1.800 albertel 6436: foreach my $item (@$storearr) {
6437: $items.=&escape($item).'&';
1.191 harris41 6438: }
1.12 www 6439: $items=~s/\&$//;
1.620 albertel 6440: if (!$udomain) { $udomain=$env{'user.domain'}; }
6441: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6442: my $uhome=&homeserver($uname,$udomain);
6443: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6444: my @pairs=split(/\&/,$rep);
6445: my %returnhash=();
1.42 www 6446: my $i=0;
1.800 albertel 6447: foreach my $item (@$storearr) {
6448: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6449: $i++;
1.191 harris41 6450: }
1.12 www 6451: return %returnhash;
6452: }
6453:
1.667 albertel 6454: # ------------------------------------------------------------ tmpput interface
6455: sub tmpput {
1.802 raeburn 6456: my ($storehash,$server,$context)=@_;
1.667 albertel 6457: my $items='';
1.800 albertel 6458: foreach my $item (keys(%$storehash)) {
6459: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6460: }
6461: $items=~s/\&$//;
1.802 raeburn 6462: if (defined($context)) {
6463: $items .= ':'.&escape($context);
6464: }
1.667 albertel 6465: return &reply("tmpput:$items",$server);
6466: }
6467:
6468: # ------------------------------------------------------------ tmpget interface
6469: sub tmpget {
1.688 albertel 6470: my ($token,$server)=@_;
6471: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6472: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6473: my %returnhash;
1.1172.2.85 raeburn 6474: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6475: return %returnhash;
6476: }
1.667 albertel 6477: foreach my $item (split(/\&/,$rep)) {
6478: my ($key,$value)=split(/=/,$item);
6479: $returnhash{&unescape($key)}=&thaw_unescape($value);
6480: }
6481: return %returnhash;
6482: }
6483:
1.1113 raeburn 6484: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6485: sub tmpdel {
6486: my ($token,$server)=@_;
6487: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6488: return &reply("tmpdel:$token",$server);
6489: }
6490:
1.1172.2.13 raeburn 6491: # ------------------------------------------------------------ get_timebased_id
6492:
6493: sub get_timebased_id {
6494: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6495: $maxtries) = @_;
6496: my ($newid,$error,$dellock);
6497: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6498: return ('','ok','invalid call to get suffix');
6499: }
6500:
6501: # set defaults for any optional args for which values were not supplied
6502: if ($who eq '') {
6503: $who = $env{'user.name'}.':'.$env{'user.domain'};
6504: }
6505: if (!$locktries) {
6506: $locktries = 3;
6507: }
6508: if (!$maxtries) {
6509: $maxtries = 10;
6510: }
6511:
6512: if (($cdom eq '') || ($cnum eq '')) {
6513: if ($env{'request.course.id'}) {
6514: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6515: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6516: }
6517: if (($cdom eq '') || ($cnum eq '')) {
6518: return ('','ok','call to get suffix not in course context');
6519: }
6520: }
6521:
6522: # construct locking item
6523: my $lockhash = {
6524: $prefix."\0".'locked_'.$keyid => $who,
6525: };
6526: my $tries = 0;
6527:
6528: # attempt to get lock on nohist_$namespace file
6529: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6530: while (($gotlock ne 'ok') && $tries <$locktries) {
6531: $tries ++;
6532: sleep 1;
6533: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6534: }
6535:
6536: # attempt to get unique identifier, based on current timestamp
6537: if ($gotlock eq 'ok') {
6538: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6539: my $id = time;
6540: $newid = $id;
1.1172.2.56 raeburn 6541: if ($idtype eq 'addcode') {
6542: $newid .= &sixnum_code();
6543: }
1.1172.2.13 raeburn 6544: my $idtries = 0;
6545: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6546: if ($idtype eq 'concat') {
6547: $newid = $id.$idtries;
1.1172.2.56 raeburn 6548: } elsif ($idtype eq 'addcode') {
6549: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6550: } else {
6551: $newid ++;
6552: }
6553: $idtries ++;
6554: }
6555: if (!exists($inuse{$prefix."\0".$newid})) {
6556: my %new_item = (
6557: $prefix."\0".$newid => $who,
6558: );
6559: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6560: $cdom,$cnum);
6561: if ($putresult ne 'ok') {
6562: undef($newid);
6563: $error = 'error saving new item: '.$putresult;
6564: }
6565: } else {
1.1172.2.56 raeburn 6566: undef($newid);
1.1172.2.13 raeburn 6567: $error = ('error: no unique suffix available for the new item ');
6568: }
6569: # remove lock
6570: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6571: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6572: } else {
6573: $error = "error: could not obtain lockfile\n";
6574: $dellock = 'ok';
1.1172.2.58 raeburn 6575: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6576: $dellock = 'nolock';
6577: }
1.1172.2.13 raeburn 6578: }
6579: return ($newid,$dellock,$error);
6580: }
6581:
1.1172.2.56 raeburn 6582: sub sixnum_code {
6583: my $code;
6584: for (0..6) {
6585: $code .= int( rand(9) );
6586: }
6587: return $code;
6588: }
6589:
1.765 albertel 6590: # -------------------------------------------------- portfolio access checking
6591:
6592: sub portfolio_access {
1.1172.2.77 raeburn 6593: my ($requrl,$clientip) = @_;
1.765 albertel 6594: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6595: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6596: if ($result) {
6597: my %setters;
6598: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6599: my ($startblock,$endblock) =
6600: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6601: if ($startblock && $endblock) {
6602: return 'B';
6603: }
6604: } else {
6605: my ($startblock,$endblock) =
6606: &Apache::loncommon::blockcheck(\%setters,'port');
6607: if ($startblock && $endblock) {
6608: return 'B';
6609: }
6610: }
6611: }
1.765 albertel 6612: if ($result eq 'ok') {
1.766 albertel 6613: return 'F';
1.765 albertel 6614: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6615: return 'A';
1.765 albertel 6616: }
1.766 albertel 6617: return '';
1.765 albertel 6618: }
6619:
6620: sub get_portfolio_access {
1.1172.2.77 raeburn 6621: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6622:
6623: if (!ref($access_hash)) {
6624: my $current_perms = &get_portfile_permissions($udom,$unum);
6625: my %access_controls = &get_access_controls($current_perms,$group,
6626: $file_name);
6627: $access_hash = $access_controls{$file_name};
6628: }
6629:
1.1172.2.77 raeburn 6630: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6631: my $now = time;
6632: if (ref($access_hash) eq 'HASH') {
6633: foreach my $key (keys(%{$access_hash})) {
6634: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6635: if ($start > $now) {
6636: next;
6637: }
6638: if ($end && $end<$now) {
6639: next;
6640: }
6641: if ($scope eq 'public') {
6642: $public = $key;
6643: last;
6644: } elsif ($scope eq 'guest') {
6645: $guest = $key;
6646: } elsif ($scope eq 'domains') {
6647: push(@domains,$key);
6648: } elsif ($scope eq 'users') {
6649: push(@users,$key);
6650: } elsif ($scope eq 'course') {
6651: push(@courses,$key);
6652: } elsif ($scope eq 'group') {
6653: push(@groups,$key);
1.1172.2.77 raeburn 6654: } elsif ($scope eq 'ip') {
6655: push(@ips,$key);
1.765 albertel 6656: }
6657: }
6658: if ($public) {
6659: return 'ok';
1.1172.2.77 raeburn 6660: } elsif (@ips > 0) {
6661: my $allowed;
6662: foreach my $ipkey (@ips) {
6663: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6664: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6665: $allowed = 1;
6666: last;
6667: }
6668: }
6669: }
6670: if ($allowed) {
6671: return 'ok';
6672: }
1.765 albertel 6673: }
6674: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6675: if ($guest) {
6676: return $guest;
6677: }
6678: } else {
6679: if (@domains > 0) {
6680: foreach my $domkey (@domains) {
6681: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6682: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6683: return 'ok';
6684: }
6685: }
6686: }
6687: }
6688: if (@users > 0) {
6689: foreach my $userkey (@users) {
1.865 raeburn 6690: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6691: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6692: if (ref($item) eq 'HASH') {
6693: if (($item->{'uname'} eq $env{'user.name'}) &&
6694: ($item->{'udom'} eq $env{'user.domain'})) {
6695: return 'ok';
6696: }
6697: }
6698: }
6699: }
1.765 albertel 6700: }
6701: }
6702: my %roleshash;
6703: my @courses_and_groups = @courses;
6704: push(@courses_and_groups,@groups);
6705: if (@courses_and_groups > 0) {
6706: my (%allgroups,%allroles);
6707: my ($start,$end,$role,$sec,$group);
6708: foreach my $envkey (%env) {
1.1060 raeburn 6709: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6710: my $cid = $2.'_'.$3;
6711: if ($1 eq 'gr') {
6712: $group = $4;
6713: $allgroups{$cid}{$group} = $env{$envkey};
6714: } else {
6715: if ($4 eq '') {
6716: $sec = 'none';
6717: } else {
6718: $sec = $4;
6719: }
6720: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6721: }
1.811 albertel 6722: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6723: my $cid = $2.'_'.$3;
6724: if ($4 eq '') {
6725: $sec = 'none';
6726: } else {
6727: $sec = $4;
6728: }
6729: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6730: }
6731: }
6732: if (keys(%allroles) == 0) {
6733: return;
6734: }
6735: foreach my $key (@courses_and_groups) {
6736: my %content = %{$$access_hash{$key}};
6737: my $cnum = $content{'number'};
6738: my $cdom = $content{'domain'};
6739: my $cid = $cdom.'_'.$cnum;
6740: if (!exists($allroles{$cid})) {
6741: next;
6742: }
6743: foreach my $role_id (keys(%{$content{'roles'}})) {
6744: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6745: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6746: my @status = @{$content{'roles'}{$role_id}{'access'}};
6747: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6748: foreach my $role (keys(%{$allroles{$cid}})) {
6749: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6750: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6751: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6752: if (grep/^all$/,@sections) {
6753: return 'ok';
6754: } else {
6755: if (grep/^$sec$/,@sections) {
6756: return 'ok';
6757: }
6758: }
6759: }
6760: }
6761: if (keys(%{$allgroups{$cid}}) == 0) {
6762: if (grep/^none$/,@groups) {
6763: return 'ok';
6764: }
6765: } else {
6766: if (grep/^all$/,@groups) {
6767: return 'ok';
6768: }
6769: foreach my $group (keys(%{$allgroups{$cid}})) {
6770: if (grep/^$group$/,@groups) {
6771: return 'ok';
6772: }
6773: }
6774: }
6775: }
6776: }
6777: }
6778: }
6779: }
6780: if ($guest) {
6781: return $guest;
6782: }
6783: }
6784: }
6785: return;
6786: }
6787:
6788: sub course_group_datechecker {
6789: my ($dates,$now,$status) = @_;
6790: my ($start,$end) = split(/\./,$dates);
6791: if (!$start && !$end) {
6792: return 'ok';
6793: }
6794: if (grep/^active$/,@{$status}) {
6795: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6796: return 'ok';
6797: }
6798: }
6799: if (grep/^previous$/,@{$status}) {
6800: if ($end > $now ) {
6801: return 'ok';
6802: }
6803: }
6804: if (grep/^future$/,@{$status}) {
6805: if ($start > $now) {
6806: return 'ok';
6807: }
6808: }
6809: return;
6810: }
6811:
6812: sub parse_portfolio_url {
6813: my ($url) = @_;
6814:
6815: my ($type,$udom,$unum,$group,$file_name);
6816:
1.823 albertel 6817: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6818: $type = 1;
6819: $udom = $1;
6820: $unum = $2;
6821: $file_name = $3;
1.823 albertel 6822: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6823: $type = 2;
6824: $udom = $1;
6825: $unum = $2;
6826: $group = $3;
6827: $file_name = $3.'/'.$4;
6828: }
6829: if (wantarray) {
6830: return ($type,$udom,$unum,$file_name,$group);
6831: }
6832: return $type;
6833: }
6834:
6835: sub is_portfolio_url {
6836: my ($url) = @_;
6837: return scalar(&parse_portfolio_url($url));
6838: }
6839:
1.798 raeburn 6840: sub is_portfolio_file {
6841: my ($file) = @_;
1.820 raeburn 6842: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6843: return 1;
6844: }
6845: return;
6846: }
6847:
1.976 raeburn 6848: sub usertools_access {
1.1084 raeburn 6849: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6850: my ($access,%tools);
6851: if ($context eq '') {
6852: $context = 'tools';
6853: }
6854: if ($context eq 'requestcourses') {
6855: %tools = (
6856: official => 1,
6857: unofficial => 1,
1.1006 raeburn 6858: community => 1,
1.1172.2.37 raeburn 6859: textbook => 1,
1.985 raeburn 6860: );
1.1172.2.9 raeburn 6861: } elsif ($context eq 'requestauthor') {
6862: %tools = (
6863: requestauthor => 1,
6864: );
1.985 raeburn 6865: } else {
6866: %tools = (
6867: aboutme => 1,
6868: blog => 1,
1.1172.2.6 raeburn 6869: webdav => 1,
1.985 raeburn 6870: portfolio => 1,
6871: );
6872: }
1.976 raeburn 6873: return if (!defined($tools{$tool}));
6874:
1.1172.2.35 raeburn 6875: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6876: $udom = $env{'user.domain'};
6877: $uname = $env{'user.name'};
6878: }
6879:
1.978 raeburn 6880: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6881: if ($action ne 'reload') {
1.985 raeburn 6882: if ($context eq 'requestcourses') {
6883: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6884: } elsif ($context eq 'requestauthor') {
6885: return $env{'environment.canrequest.author'};
1.985 raeburn 6886: } else {
6887: return $env{'environment.availabletools.'.$tool};
6888: }
6889: }
1.976 raeburn 6890: }
6891:
1.1172.2.9 raeburn 6892: my ($toolstatus,$inststatus,$envkey);
6893: if ($context eq 'requestauthor') {
6894: $envkey = $context;
6895: } else {
6896: $envkey = $context.'.'.$tool;
6897: }
1.976 raeburn 6898:
1.985 raeburn 6899: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6900: ($action ne 'reload')) {
1.1172.2.9 raeburn 6901: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6902: $inststatus = $env{'environment.inststatus'};
6903: } else {
1.1084 raeburn 6904: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6905: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6906: $inststatus = $userenvref->{'inststatus'};
6907: } else {
1.1172.2.9 raeburn 6908: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6909: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6910: $inststatus = $userenv{'inststatus'};
6911: }
1.976 raeburn 6912: }
6913:
6914: if ($toolstatus ne '') {
6915: if ($toolstatus) {
6916: $access = 1;
6917: } else {
6918: $access = 0;
6919: }
6920: return $access;
6921: }
6922:
1.1084 raeburn 6923: my ($is_adv,%domdef);
6924: if (ref($is_advref) eq 'HASH') {
6925: $is_adv = $is_advref->{'is_adv'};
6926: } else {
6927: $is_adv = &is_advanced_user($udom,$uname);
6928: }
6929: if (ref($domdefref) eq 'HASH') {
6930: %domdef = %{$domdefref};
6931: } else {
6932: %domdef = &get_domain_defaults($udom);
6933: }
1.976 raeburn 6934: if (ref($domdef{$tool}) eq 'HASH') {
6935: if ($is_adv) {
6936: if ($domdef{$tool}{'_LC_adv'} ne '') {
6937: if ($domdef{$tool}{'_LC_adv'}) {
6938: $access = 1;
6939: } else {
6940: $access = 0;
6941: }
6942: return $access;
6943: }
6944: }
6945: if ($inststatus ne '') {
6946: my ($hasaccess,$hasnoaccess);
6947: foreach my $affiliation (split(/:/,$inststatus)) {
6948: if ($domdef{$tool}{$affiliation} ne '') {
6949: if ($domdef{$tool}{$affiliation}) {
6950: $hasaccess = 1;
6951: } else {
6952: $hasnoaccess = 1;
6953: }
6954: }
6955: }
6956: if ($hasaccess || $hasnoaccess) {
6957: if ($hasaccess) {
6958: $access = 1;
6959: } elsif ($hasnoaccess) {
6960: $access = 0;
6961: }
6962: return $access;
6963: }
6964: } else {
6965: if ($domdef{$tool}{'default'} ne '') {
6966: if ($domdef{$tool}{'default'}) {
6967: $access = 1;
6968: } elsif ($domdef{$tool}{'default'} == 0) {
6969: $access = 0;
6970: }
6971: return $access;
6972: }
6973: }
6974: } else {
1.1172.2.6 raeburn 6975: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6976: $access = 1;
6977: } else {
6978: $access = 0;
6979: }
1.976 raeburn 6980: return $access;
6981: }
6982: }
6983:
1.1050 raeburn 6984: sub is_course_owner {
6985: my ($cdom,$cnum,$udom,$uname) = @_;
6986: if (($udom eq '') || ($uname eq '')) {
6987: $udom = $env{'user.domain'};
6988: $uname = $env{'user.name'};
6989: }
6990: unless (($udom eq '') || ($uname eq '')) {
6991: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6992: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6993: return 1;
6994: } else {
6995: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6996: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6997: return 1;
6998: }
6999: }
7000: }
7001: }
7002: return;
7003: }
7004:
1.976 raeburn 7005: sub is_advanced_user {
7006: my ($udom,$uname) = @_;
1.1085 raeburn 7007: if ($udom ne '' && $uname ne '') {
7008: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7009: if (wantarray) {
7010: return ($env{'user.adv'},$env{'user.author'});
7011: } else {
7012: return $env{'user.adv'};
7013: }
1.1085 raeburn 7014: }
7015: }
1.976 raeburn 7016: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7017: my %allroles;
1.1128 raeburn 7018: my ($is_adv,$is_author);
1.976 raeburn 7019: foreach my $role (keys(%roleshash)) {
7020: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7021: my $area = '/'.$tdomain.'/'.$trest;
7022: if ($sec ne '') {
7023: $area .= '/'.$sec;
7024: }
7025: if (($area ne '') && ($trole ne '')) {
7026: my $spec=$trole.'.'.$area;
7027: if ($trole =~ /^cr\//) {
7028: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7029: } elsif ($trole ne 'gr') {
7030: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7031: }
1.1128 raeburn 7032: if ($trole eq 'au') {
7033: $is_author = 1;
7034: }
1.976 raeburn 7035: }
7036: }
7037: foreach my $role (keys(%allroles)) {
7038: last if ($is_adv);
7039: foreach my $item (split(/:/,$allroles{$role})) {
7040: if ($item ne '') {
7041: my ($privilege,$restrictions)=split(/&/,$item);
7042: if ($privilege eq 'adv') {
7043: $is_adv = 1;
7044: last;
7045: }
7046: }
7047: }
7048: }
1.1128 raeburn 7049: if (wantarray) {
7050: return ($is_adv,$is_author);
7051: }
1.976 raeburn 7052: return $is_adv;
7053: }
1.798 raeburn 7054:
1.1035 raeburn 7055: sub check_can_request {
1.1036 raeburn 7056: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7057: my $canreq = 0;
7058: my ($types,$typename) = &Apache::loncommon::course_types();
7059: my @options = ('approval','validate','autolimit');
7060: my $optregex = join('|',@options);
7061: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7062: foreach my $type (@{$types}) {
7063: if (&usertools_access($env{'user.name'},
7064: $env{'user.domain'},
7065: $type,undef,'requestcourses')) {
7066: $canreq ++;
1.1036 raeburn 7067: if (ref($request_domains) eq 'HASH') {
7068: push(@{$request_domains->{$type}},$env{'user.domain'});
7069: }
1.1035 raeburn 7070: if ($dom eq $env{'user.domain'}) {
7071: $can_request->{$type} = 1;
7072: }
7073: }
7074: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7075: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7076: if (@curr > 0) {
1.1036 raeburn 7077: foreach my $item (@curr) {
7078: if (ref($request_domains) eq 'HASH') {
7079: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7080: if ($otherdom ne '') {
7081: if (ref($request_domains->{$type}) eq 'ARRAY') {
7082: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7083: push(@{$request_domains->{$type}},$otherdom);
7084: }
7085: } else {
7086: push(@{$request_domains->{$type}},$otherdom);
7087: }
7088: }
7089: }
7090: }
7091: unless($dom eq $env{'user.domain'}) {
7092: $canreq ++;
1.1035 raeburn 7093: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7094: $can_request->{$type} = 1;
7095: }
7096: }
7097: }
7098: }
7099: }
7100: }
7101: return $canreq;
7102: }
7103:
1.341 www 7104: # ---------------------------------------------- Custom access rule evaluation
7105:
7106: sub customaccess {
7107: my ($priv,$uri)=@_;
1.807 albertel 7108: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7109: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7110: $udom = &LONCAPA::clean_domain($udom);
7111: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7112: my $access=0;
1.800 albertel 7113: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7114: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7115: if ($type eq 'user') {
7116: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7117: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7118: if ($tdom) {
7119: if ($tdom ne $env{'user.domain'}) { next; }
7120: }
1.896 albertel 7121: if ($tuname) {
7122: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7123: }
7124: $access=($effect eq 'allow');
7125: last;
7126: }
7127: } else {
7128: if ($role) {
7129: if ($role ne $urole) { next; }
7130: }
7131: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7132: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7133: if ($tdom) {
7134: if ($tdom ne $udom) { next; }
7135: }
7136: if ($tcrs) {
7137: if ($tcrs ne $ucrs) { next; }
7138: }
7139: if ($tsec) {
7140: if ($tsec ne $usec) { next; }
7141: }
7142: $access=($effect eq 'allow');
7143: last;
7144: }
7145: if ($realm eq '' && $role eq '') {
7146: $access=($effect eq 'allow');
7147: }
1.402 bowersj2 7148: }
1.341 www 7149: }
7150: return $access;
7151: }
7152:
1.103 harris41 7153: # ------------------------------------------------- Check for a user privilege
1.12 www 7154:
7155: sub allowed {
1.1172.2.65 raeburn 7156: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7157: my $ver_orguri=$uri;
1.439 www 7158: $uri=&deversion($uri);
1.152 www 7159: my $orguri=$uri;
1.52 www 7160: $uri=&declutter($uri);
1.809 raeburn 7161:
1.810 raeburn 7162: if ($priv eq 'evb') {
7163: # Evade communication block restrictions for specified role in a course
7164: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7165: return $1;
7166: } else {
7167: return;
7168: }
7169: }
7170:
1.620 albertel 7171: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7172: # Free bre access to adm and meta resources
1.1172.2.93.4 2(raebur 7173:7): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7174: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7175: && ($priv eq 'bre')) {
1.14 www 7176: return 'F';
1.159 www 7177: }
7178:
1.545 banghart 7179: # Free bre access to user's own portfolio contents
1.714 raeburn 7180: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7181: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7182: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7183: my %setters;
7184: my ($startblock,$endblock) =
7185: &Apache::loncommon::blockcheck(\%setters,'port');
7186: if ($startblock && $endblock) {
7187: return 'B';
7188: } else {
7189: return 'F';
7190: }
1.545 banghart 7191: }
7192:
1.762 raeburn 7193: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7194: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7195: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7196: if (exists($env{'request.course.id'})) {
7197: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7198: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7199: if (($domain eq $cdom) && ($name eq $cnum)) {
7200: my $courseprivid=$env{'request.course.id'};
7201: $courseprivid=~s/\_/\//;
7202: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7203: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7204: return $1;
1.762 raeburn 7205: } else {
7206: if ($env{'request.course.sec'}) {
7207: $courseprivid.='/'.$env{'request.course.sec'};
7208: }
7209: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7210: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7211: return $2;
7212: }
1.714 raeburn 7213: }
7214: }
7215: }
7216: }
7217:
1.159 www 7218: # Free bre to public access
7219:
7220: if ($priv eq 'bre') {
1.238 www 7221: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7222: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7223: return 'F';
7224: }
1.238 www 7225: if ($copyright eq 'priv') {
7226: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7227: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7228: return '';
7229: }
7230: }
7231: if ($copyright eq 'domain') {
7232: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7233: unless (($env{'user.domain'} eq $1) ||
7234: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7235: return '';
7236: }
1.262 matthew 7237: }
1.620 albertel 7238: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7239: # Library role, so allow browsing of resources in this domain.
7240: return 'F';
1.238 www 7241: }
1.341 www 7242: if ($copyright eq 'custom') {
7243: unless (&customaccess($priv,$uri)) { return ''; }
7244: }
1.14 www 7245: }
1.264 matthew 7246: # Domain coordinator is trying to create a course
1.620 albertel 7247: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7248: # uri is the requested domain in this case.
7249: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7250: # a role of dc for the domain in question.
1.620 albertel 7251: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7252: }
1.29 www 7253:
1.52 www 7254: my $thisallowed='';
7255: my $statecond=0;
7256: my $courseprivid='';
7257:
1.1039 raeburn 7258: my $ownaccess;
1.1043 raeburn 7259: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7260: if (($priv eq 'bro') && ($env{'user.author'})) {
7261: if ($uri eq '') {
7262: $ownaccess = 1;
7263: } else {
7264: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7265: my $udom = $env{'user.domain'};
7266: my $uname = $env{'user.name'};
7267: if ($uri =~ m{^\Q$udom\E/?$}) {
7268: $ownaccess = 1;
1.1040 raeburn 7269: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7270: unless ($uri =~ m{\.\./}) {
7271: $ownaccess = 1;
7272: }
7273: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7274: my $now = time;
7275: if ($uri =~ m{^([^/]+)/?$}) {
7276: my $adom = $1;
7277: foreach my $key (keys(%env)) {
1.1042 raeburn 7278: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7279: my ($start,$end) = split('.',$env{$key});
7280: if (($now >= $start) && (!$end || $end < $now)) {
7281: $ownaccess = 1;
7282: last;
7283: }
7284: }
7285: }
7286: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7287: my $adom = $1;
7288: my $aname = $2;
1.1042 raeburn 7289: foreach my $role ('ca','aa') {
7290: if ($env{"user.role.$role./$adom/$aname"}) {
7291: my ($start,$end) =
7292: split('.',$env{"user.role.$role./$adom/$aname"});
7293: if (($now >= $start) && (!$end || $end < $now)) {
7294: $ownaccess = 1;
7295: last;
7296: }
1.1039 raeburn 7297: }
7298: }
7299: }
7300: }
7301: }
7302: }
7303: }
7304:
1.52 www 7305: # Course
7306:
1.620 albertel 7307: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7308: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7309: $thisallowed.=$1;
7310: }
1.52 www 7311: }
1.29 www 7312:
1.52 www 7313: # Domain
7314:
1.620 albertel 7315: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7316: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7317: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7318: $thisallowed.=$1;
7319: }
1.12 www 7320: }
1.52 www 7321:
1.1141 raeburn 7322: # User who is not author or co-author might still be able to edit
7323: # resource of an author in the domain (e.g., if Domain Coordinator).
7324: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7325: (&allowed('mdc',$env{'request.course.id'}))) {
7326: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7327: $thisallowed.=$1;
7328: }
7329: }
7330:
1.52 www 7331: # Course: uri itself is a course
1.66 www 7332: my $courseuri=$uri;
7333: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7334: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7335:
1.620 albertel 7336: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7337: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7338: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7339: $thisallowed.=$1;
7340: }
1.12 www 7341: }
1.29 www 7342:
1.665 albertel 7343: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7344: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7345: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7346: $thisallowed='';
1.671 raeburn 7347: my ($match)=&is_on_map($uri);
7348: if ($match) {
7349: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7350: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7351: my $value = $1;
7352: if ($noblockcheck) {
7353: $thisallowed.=$value;
1.1162 raeburn 7354: } else {
1.1172.2.65 raeburn 7355: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7356: if (@blockers > 0) {
7357: $thisallowed = 'B';
7358: } else {
7359: $thisallowed.=$value;
7360: }
1.1162 raeburn 7361: }
1.671 raeburn 7362: }
7363: } else {
1.705 albertel 7364: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7365: if ($refuri) {
7366: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7367: $thisallowed='F';
1.671 raeburn 7368: } else {
7369: $refuri=&declutter($refuri);
7370: my ($match) = &is_on_map($refuri);
7371: if ($match) {
1.1172.2.65 raeburn 7372: if ($noblockcheck) {
1.1162 raeburn 7373: $thisallowed='F';
1.1172.2.65 raeburn 7374: } else {
7375: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7376: if (@blockers > 0) {
7377: $thisallowed = 'B';
7378: } else {
7379: $thisallowed='F';
7380: }
1.1162 raeburn 7381: }
1.671 raeburn 7382: }
1.669 raeburn 7383: }
1.671 raeburn 7384: }
7385: }
1.314 www 7386: }
1.492 albertel 7387:
1.766 albertel 7388: if ($priv eq 'bre'
7389: && $thisallowed ne 'F'
7390: && $thisallowed ne '2'
7391: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7392: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7393: }
7394:
1.52 www 7395: # Full access at system, domain or course-wide level? Exit.
1.29 www 7396: if ($thisallowed=~/F/) {
7397: return 'F';
7398: }
7399:
1.52 www 7400: # If this is generating or modifying users, exit with special codes
1.29 www 7401:
1.643 www 7402: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7403: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7404: my ($audom,$auname)=split('/',$uri);
1.643 www 7405: # no author name given, so this just checks on the general right to make a co-author in this domain
7406: unless ($auname) { return $thisallowed; }
7407: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7408: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7409: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7410: ($audom ne $env{'request.role.domain'}))) { return ''; }
7411: }
1.52 www 7412: return $thisallowed;
7413: }
7414: #
1.103 harris41 7415: # Gathered so far: system, domain and course wide privileges
1.52 www 7416: #
7417: # Course: See if uri or referer is an individual resource that is part of
7418: # the course
7419:
1.620 albertel 7420: if ($env{'request.course.id'}) {
1.232 www 7421:
1.620 albertel 7422: $courseprivid=$env{'request.course.id'};
7423: if ($env{'request.course.sec'}) {
7424: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7425: }
7426: $courseprivid=~s/\_/\//;
7427: my $checkreferer=1;
1.232 www 7428: my ($match,$cond)=&is_on_map($uri);
7429: if ($match) {
7430: $statecond=$cond;
1.620 albertel 7431: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7432: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7433: my $value = $1;
7434: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7435: if ($noblockcheck) {
1.1162 raeburn 7436: $thisallowed.=$value;
1.1172.2.65 raeburn 7437: } else {
7438: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7439: if (@blockers > 0) {
7440: $thisallowed = 'B';
7441: } else {
7442: $thisallowed.=$value;
7443: }
1.1162 raeburn 7444: }
7445: } else {
7446: $thisallowed.=$value;
7447: }
1.52 www 7448: $checkreferer=0;
7449: }
1.29 www 7450: }
1.83 www 7451:
1.148 www 7452: if ($checkreferer) {
1.620 albertel 7453: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7454: unless ($refuri) {
1.800 albertel 7455: foreach my $key (keys(%env)) {
7456: if ($key=~/^httpref\..*\*/) {
7457: my $pattern=$key;
1.156 www 7458: $pattern=~s/^httpref\.\/res\///;
1.148 www 7459: $pattern=~s/\*/\[\^\/\]\+/g;
7460: $pattern=~s/\//\\\//g;
1.152 www 7461: if ($orguri=~/$pattern/) {
1.800 albertel 7462: $refuri=$env{$key};
1.148 www 7463: }
7464: }
1.191 harris41 7465: }
1.148 www 7466: }
1.232 www 7467:
1.148 www 7468: if ($refuri) {
1.152 www 7469: $refuri=&declutter($refuri);
1.232 www 7470: my ($match,$cond)=&is_on_map($refuri);
7471: if ($match) {
7472: my $refstatecond=$cond;
1.620 albertel 7473: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7474: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7475: my $value = $1;
7476: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7477: if ($noblockcheck) {
1.1162 raeburn 7478: $thisallowed.=$value;
1.1172.2.65 raeburn 7479: } else {
7480: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7481: if (@blockers > 0) {
7482: $thisallowed = 'B';
7483: } else {
7484: $thisallowed.=$value;
7485: }
1.1162 raeburn 7486: }
7487: } else {
7488: $thisallowed.=$value;
7489: }
1.53 www 7490: $uri=$refuri;
7491: $statecond=$refstatecond;
1.52 www 7492: }
7493: }
1.148 www 7494: }
1.29 www 7495: }
1.52 www 7496: }
1.29 www 7497:
1.52 www 7498: #
1.103 harris41 7499: # Gathered now: all privileges that could apply, and condition number
1.52 www 7500: #
7501: #
7502: # Full or no access?
7503: #
1.29 www 7504:
1.52 www 7505: if ($thisallowed=~/F/) {
7506: return 'F';
7507: }
1.29 www 7508:
1.52 www 7509: unless ($thisallowed) {
7510: return '';
7511: }
1.29 www 7512:
1.52 www 7513: # Restrictions exist, deal with them
7514: #
7515: # C:according to course preferences
7516: # R:according to resource settings
7517: # L:unless locked
7518: # X:according to user session state
7519: #
7520:
7521: # Possibly locked functionality, check all courses
1.54 www 7522: # Locks might take effect only after 10 minutes cache expiration for other
7523: # courses, and 2 minutes for current course
1.52 www 7524:
7525: my $envkey;
7526: if ($thisallowed=~/L/) {
1.1000 raeburn 7527: foreach $envkey (keys(%env)) {
1.54 www 7528: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7529: my $courseid=$2;
7530: my $roleid=$1.'.'.$2;
1.92 www 7531: $courseid=~s/^\///;
1.54 www 7532: my $expiretime=600;
1.620 albertel 7533: if ($env{'request.role'} eq $roleid) {
1.54 www 7534: $expiretime=120;
7535: }
7536: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7537: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7538: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7539: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7540: }
1.620 albertel 7541: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7542: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7543: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7544: &log($env{'user.domain'},$env{'user.name'},
7545: $env{'user.home'},
1.57 www 7546: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7547: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7548: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7549: return '';
7550: }
7551: }
1.620 albertel 7552: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7553: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7554: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7555: &log($env{'user.domain'},$env{'user.name'},
7556: $env{'user.home'},
1.57 www 7557: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7558: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7559: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7560: return '';
7561: }
7562: }
7563: }
1.29 www 7564: }
1.52 www 7565: }
7566:
7567: #
7568: # Rest of the restrictions depend on selected course
7569: #
7570:
1.620 albertel 7571: unless ($env{'request.course.id'}) {
1.766 albertel 7572: if ($thisallowed eq 'A') {
7573: return 'A';
1.814 raeburn 7574: } elsif ($thisallowed eq 'B') {
7575: return 'B';
1.766 albertel 7576: } else {
7577: return '1';
7578: }
1.52 www 7579: }
1.29 www 7580:
1.52 www 7581: #
7582: # Now user is definitely in a course
7583: #
1.53 www 7584:
7585:
7586: # Course preferences
7587:
7588: if ($thisallowed=~/C/) {
1.620 albertel 7589: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7590: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7591: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7592: =~/\Q$rolecode\E/) {
1.1103 raeburn 7593: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7594: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7595: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7596: $env{'request.course.id'});
7597: }
1.237 www 7598: return '';
7599: }
7600:
1.620 albertel 7601: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7602: =~/\Q$unamedom\E/) {
1.1103 raeburn 7603: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7604: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7605: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7606: $env{'request.course.id'});
7607: }
1.54 www 7608: return '';
7609: }
1.53 www 7610: }
7611:
7612: # Resource preferences
7613:
7614: if ($thisallowed=~/R/) {
1.620 albertel 7615: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7616: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7617: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7618: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7619: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7620: }
7621: return '';
1.54 www 7622: }
1.53 www 7623: }
1.30 www 7624:
1.246 www 7625: # Restricted by state or randomout?
1.30 www 7626:
1.52 www 7627: if ($thisallowed=~/X/) {
1.620 albertel 7628: if ($env{'acc.randomout'}) {
1.579 albertel 7629: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7630: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7631: return '';
7632: }
1.247 www 7633: }
7634: if (&condval($statecond)) {
1.52 www 7635: return '2';
7636: } else {
7637: return '';
7638: }
7639: }
1.30 www 7640:
1.766 albertel 7641: if ($thisallowed eq 'A') {
7642: return 'A';
1.814 raeburn 7643: } elsif ($thisallowed eq 'B') {
7644: return 'B';
1.766 albertel 7645: }
1.52 www 7646: return 'F';
1.232 www 7647: }
1.1162 raeburn 7648:
1.1172.2.13 raeburn 7649: # ------------------------------------------- Check construction space access
7650:
7651: sub constructaccess {
7652: my ($url,$setpriv)=@_;
7653:
7654: # We do not allow editing of previous versions of files
7655: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7656:
7657: # Get username and domain from URL
7658: my ($ownername,$ownerdomain,$ownerhome);
7659:
7660: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7661: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7662:
7663: # The URL does not really point to any authorspace, forget it
7664: unless (($ownername) && ($ownerdomain)) { return ''; }
7665:
7666: # Now we need to see if the user has access to the authorspace of
7667: # $ownername at $ownerdomain
7668:
7669: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7670: # Real author for this?
7671: $ownerhome = $env{'user.home'};
7672: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7673: return ($ownername,$ownerdomain,$ownerhome);
7674: }
7675: } else {
7676: # Co-author for this?
7677: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7678: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7679: $ownerhome = &homeserver($ownername,$ownerdomain);
7680: return ($ownername,$ownerdomain,$ownerhome);
7681: }
7682: }
7683:
7684: # We don't have any access right now. If we are not possibly going to do anything about this,
7685: # we might as well leave
7686: unless ($setpriv) { return ''; }
7687:
7688: # Backdoor access?
7689: my $allowed=&allowed('eco',$ownerdomain);
7690: # Nope
7691: unless ($allowed) { return ''; }
7692: # Looks like we may have access, but could be locked by the owner of the construction space
7693: if ($allowed eq 'U') {
7694: my %blocked=&get('environment',['domcoord.author'],
7695: $ownerdomain,$ownername);
7696: # Is blocked by owner
7697: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7698: }
7699: if (($allowed eq 'F') || ($allowed eq 'U')) {
7700: # Grant temporary access
7701: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7702: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7703: if (!$update) { $update = $then; }
7704: my $refresh=$env{'user.refresh.time'};
7705: if (!$refresh) { $refresh = $update; }
7706: my $now = time;
7707: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7708: $now,'ca','constructaccess');
7709: $ownerhome = &homeserver($ownername,$ownerdomain);
7710: return($ownername,$ownerdomain,$ownerhome);
7711: }
7712: # No business here
7713: return '';
7714: }
7715:
1.1172.2.66 raeburn 7716: # ----------------------------------------------------------- Content Blocking
7717:
7718: {
7719: # Caches for faster Course Contents display where content blocking
7720: # is in operation (i.e., interval param set) for timed quiz.
7721: #
7722: # User for whom data are being temporarily cached.
7723: my $cacheduser='';
7724: # Cached blockers for this user (a hash of blocking items).
7725: my %cachedblockers=();
7726: # When the data were last cached.
7727: my $cachedlast='';
7728:
7729: sub load_all_blockers {
7730: my ($uname,$udom,$blocks)=@_;
7731: if (($uname ne '') && ($udom ne '')) {
7732: if (($cacheduser eq $uname.':'.$udom) &&
7733: (abs($cachedlast-time)<5)) {
7734: return;
7735: }
7736: }
7737: $cachedlast=time;
7738: $cacheduser=$uname.':'.$udom;
7739: %cachedblockers = &get_commblock_resources($blocks);
7740: }
7741:
1.1162 raeburn 7742: sub get_comm_blocks {
7743: my ($cdom,$cnum) = @_;
7744: if ($cdom eq '' || $cnum eq '') {
7745: return unless ($env{'request.course.id'});
7746: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7747: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7748: }
7749: my %commblocks;
7750: my $hashid=$cdom.'_'.$cnum;
7751: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7752: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7753: %commblocks = %{$blocksref};
7754: } else {
7755: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7756: my $cachetime = 600;
7757: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7758: }
7759: return %commblocks;
7760: }
7761:
1.1172.2.66 raeburn 7762: sub get_commblock_resources {
7763: my ($blocks) = @_;
7764: my %blockers = ();
7765: return %blockers unless ($env{'request.course.id'});
7766: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7767: my %commblocks;
7768: if (ref($blocks) eq 'HASH') {
7769: %commblocks = %{$blocks};
7770: } else {
7771: %commblocks = &get_comm_blocks();
7772: }
1.1172.2.66 raeburn 7773: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7774: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7775: return %blockers unless (ref($navmap));
7776: my $now = time;
1.1162 raeburn 7777: foreach my $block (keys(%commblocks)) {
7778: if ($block =~ /^(\d+)____(\d+)$/) {
7779: my ($start,$end) = ($1,$2);
7780: if ($start <= $now && $end >= $now) {
7781: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7782: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7783: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7784: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7785: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7786: }
7787: }
7788: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7789: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7790: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7791: }
7792: }
7793: }
7794: }
7795: }
7796: } elsif ($block =~ /^firstaccess____(.+)$/) {
7797: my $item = $1;
1.1163 raeburn 7798: my @to_test;
1.1162 raeburn 7799: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7800: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7801: my @interval;
7802: my $type = 'map';
7803: if ($item eq 'course') {
7804: $type = 'course';
7805: @interval=&EXT("resource.0.interval");
7806: } else {
7807: if ($item =~ /___\d+___/) {
7808: $type = 'resource';
7809: @interval=&EXT("resource.0.interval",$item);
7810: if (ref($navmap)) {
7811: my $res = $navmap->getBySymb($item);
7812: push(@to_test,$res);
7813: }
1.1162 raeburn 7814: } else {
1.1172.2.66 raeburn 7815: my $mapsymb = &symbread($item,1);
7816: if ($mapsymb) {
7817: if (ref($navmap)) {
7818: my $mapres = $navmap->getBySymb($mapsymb);
7819: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7820: foreach my $res (@to_test) {
7821: my $symb = $res->symb();
7822: next if ($symb eq $mapsymb);
7823: if ($symb ne '') {
7824: @interval=&EXT("resource.0.interval",$symb);
7825: if ($interval[1] eq 'map') {
7826: last;
1.1162 raeburn 7827: }
7828: }
7829: }
7830: }
7831: }
7832: }
1.1172.2.66 raeburn 7833: }
1.1172.2.93.4 1(raebur 7834:7): if ($interval[0] =~ /^(\d+)/) {
7835:7): my $timelimit = $1;
1.1172.2.66 raeburn 7836: my $first_access;
7837: if ($type eq 'resource') {
7838: $first_access=&get_first_access($interval[1],$item);
7839: } elsif ($type eq 'map') {
7840: $first_access=&get_first_access($interval[1],undef,$item);
7841: } else {
7842: $first_access=&get_first_access($interval[1]);
7843: }
7844: if ($first_access) {
1.1172.2.93.4 1(raebur 7845:7): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 7846: if ($timesup > $now) {
7847: my $activeblock;
7848: foreach my $res (@to_test) {
7849: if ($res->answerable()) {
7850: $activeblock = 1;
7851: last;
7852: }
7853: }
7854: if ($activeblock) {
7855: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7856: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7857: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7858: }
7859: }
7860: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7861: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7862: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7863: }
1.1162 raeburn 7864: }
7865: }
7866: }
7867: }
7868: }
7869: }
7870: }
7871: }
7872: }
1.1172.2.66 raeburn 7873: return %blockers;
1.1162 raeburn 7874: }
7875:
1.1172.2.66 raeburn 7876: sub has_comm_blocking {
7877: my ($priv,$symb,$uri,$blocks) = @_;
7878: my @blockers;
7879: return unless ($env{'request.course.id'});
7880: return unless ($priv eq 'bre');
7881: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7882: return if ($env{'request.state'} eq 'construct');
7883: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7884: return unless (keys(%cachedblockers) > 0);
7885: my (%possibles,@symbs);
7886: if (!$symb) {
7887: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7888: }
1.1172.2.66 raeburn 7889: if ($symb) {
7890: @symbs = ($symb);
7891: } elsif (keys(%possibles)) {
7892: @symbs = keys(%possibles);
7893: }
7894: my $noblock;
7895: foreach my $symb (@symbs) {
7896: last if ($noblock);
7897: my ($map,$resid,$resurl)=&decode_symb($symb);
7898: foreach my $block (keys(%cachedblockers)) {
7899: if ($block =~ /^firstaccess____(.+)$/) {
7900: my $item = $1;
7901: if (($item eq $map) || ($item eq $symb)) {
7902: $noblock = 1;
7903: last;
7904: }
1.1162 raeburn 7905: }
1.1172.2.66 raeburn 7906: if (ref($cachedblockers{$block}) eq 'HASH') {
7907: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7908: if ($cachedblockers{$block}{'resources'}{$symb}) {
7909: unless (grep(/^\Q$block\E$/,@blockers)) {
7910: push(@blockers,$block);
7911: }
7912: }
7913: }
7914: }
7915: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7916: if ($cachedblockers{$block}{'maps'}{$map}) {
7917: unless (grep(/^\Q$block\E$/,@blockers)) {
7918: push(@blockers,$block);
7919: }
7920: }
1.1162 raeburn 7921: }
7922: }
7923: }
1.1172.2.66 raeburn 7924: return if ($noblock);
7925: return @blockers;
7926: }
1.1162 raeburn 7927: }
7928:
1.1172.2.66 raeburn 7929: # -------------------------------- Deversion and split uri into path an filename
7930:
1.1133 foxr 7931: #
1.1172.2.66 raeburn 7932: # Removes the version from a URI and
1.1133 foxr 7933: # splits it in to its filename and path to the filename.
7934: # Seems like File::Basename could have done this more clearly.
7935: # Parameters:
7936: # $uri - input URI
7937: # Returns:
7938: # Two element list consisting of
7939: # $pathname - the URI up to and excluding the trailing /
7940: # $filename - The part of the URI following the last /
7941: # NOTE:
7942: # Another realization of this is simply:
7943: # use File::Basename;
7944: # ...
7945: # $uri = shift;
7946: # $filename = basename($uri);
7947: # $path = dirname($uri);
7948: # return ($filename, $path);
7949: #
7950: # The implementation below is probably faster however.
7951: #
1.710 albertel 7952: sub split_uri_for_cond {
7953: my $uri=&deversion(&declutter(shift));
7954: my @uriparts=split(/\//,$uri);
7955: my $filename=pop(@uriparts);
7956: my $pathname=join('/',@uriparts);
7957: return ($pathname,$filename);
7958: }
1.232 www 7959: # --------------------------------------------------- Is a resource on the map?
7960:
7961: sub is_on_map {
1.710 albertel 7962: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7963: #Trying to find the conditional for the file
1.620 albertel 7964: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7965: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7966: if ($match) {
1.289 bowersj2 7967: return (1,$1);
7968: } else {
1.434 www 7969: return (0,0);
1.289 bowersj2 7970: }
1.12 www 7971: }
7972:
1.427 www 7973: # --------------------------------------------------------- Get symb from alias
7974:
7975: sub get_symb_from_alias {
7976: my $symb=shift;
7977: my ($map,$resid,$url)=&decode_symb($symb);
7978: # Already is a symb
7979: if ($url) { return $symb; }
7980: # Must be an alias
7981: my $aliassymb='';
7982: my %bighash;
1.620 albertel 7983: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7984: &GDBM_READER(),0640)) {
7985: my $rid=$bighash{'mapalias_'.$symb};
7986: if ($rid) {
7987: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7988: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7989: $resid,$bighash{'src_'.$rid});
1.427 www 7990: }
7991: untie %bighash;
7992: }
7993: return $aliassymb;
7994: }
7995:
1.12 www 7996: # ----------------------------------------------------------------- Define Role
7997:
7998: sub definerole {
7999: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8000: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8001: foreach my $role (split(':',$sysrole)) {
8002: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8003: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8004: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8005: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8006: return "refused:s:$crole&$cqual";
8007: }
8008: }
1.191 harris41 8009: }
1.800 albertel 8010: foreach my $role (split(':',$domrole)) {
8011: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8012: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8013: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8014: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8015: return "refused:d:$crole&$cqual";
8016: }
8017: }
1.191 harris41 8018: }
1.800 albertel 8019: foreach my $role (split(':',$courole)) {
8020: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8021: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8022: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8023: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8024: return "refused:c:$crole&$cqual";
8025: }
8026: }
1.191 harris41 8027: }
1.1172.2.84 raeburn 8028: my $uhome;
8029: if (($uname ne '') && ($udom ne '')) {
8030: $uhome = &homeserver($uname,$udom);
8031: return $uhome if ($uhome eq 'no_host');
8032: } else {
8033: $uname = $env{'user.name'};
8034: $udom = $env{'user.domain'};
8035: $uhome = $env{'user.home'};
8036: }
1.620 albertel 8037: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8038: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8039: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8040: return reply($command,$uhome);
1.12 www 8041: } else {
8042: return 'refused';
8043: }
1.105 harris41 8044: }
8045:
8046: # ---------------- Make a metadata query against the network of library servers
8047:
8048: sub metadata_query {
1.1172.2.33 raeburn 8049: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8050: my %rhash;
1.845 albertel 8051: my %libserv = &all_library();
1.244 matthew 8052: my @server_list = (defined($server_array) ? @$server_array
8053: : keys(%libserv) );
8054: for my $server (@server_list) {
1.1172.2.33 raeburn 8055: my $domains = '';
8056: if (ref($domains_hash) eq 'HASH') {
8057: $domains = $domains_hash->{$server};
8058: }
1.118 harris41 8059: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8060: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8061: $rhash{$server}=$reply;
8062: }
8063: else {
8064: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8065: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8066: $server);
8067: $rhash{$server}=$reply;
8068: }
1.112 harris41 8069: }
1.118 harris41 8070: return \%rhash;
1.240 www 8071: }
8072:
8073: # ----------------------------------------- Send log queries and wait for reply
8074:
8075: sub log_query {
8076: my ($uname,$udom,$query,%filters)=@_;
8077: my $uhome=&homeserver($uname,$udom);
8078: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8079: my $uhost=&hostname($uhome);
1.800 albertel 8080: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8081: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8082: $uhome);
1.479 albertel 8083: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8084: return get_query_reply($queryid);
8085: }
8086:
1.818 raeburn 8087: # -------------------------- Update MySQL table for portfolio file
8088:
8089: sub update_portfolio_table {
1.821 raeburn 8090: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8091: if ($group ne '') {
8092: $file_name =~s /^\Q$group\E//;
8093: }
1.818 raeburn 8094: my $homeserver = &homeserver($uname,$udom);
8095: my $queryid=
1.821 raeburn 8096: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8097: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8098: my $reply = &get_query_reply($queryid);
8099: return $reply;
8100: }
8101:
1.899 raeburn 8102: # -------------------------- Update MySQL allusers table
8103:
8104: sub update_allusers_table {
8105: my ($uname,$udom,$names) = @_;
8106: my $homeserver = &homeserver($uname,$udom);
8107: my $queryid=
8108: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8109: 'lastname='.&escape($names->{'lastname'}).'%%'.
8110: 'firstname='.&escape($names->{'firstname'}).'%%'.
8111: 'middlename='.&escape($names->{'middlename'}).'%%'.
8112: 'generation='.&escape($names->{'generation'}).'%%'.
8113: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8114: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8115: return;
1.899 raeburn 8116: }
8117:
1.508 raeburn 8118: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8119:
8120: sub fetch_enrollment_query {
1.511 raeburn 8121: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8122: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8123: my $maxtries = 1;
1.508 raeburn 8124: if ($context eq 'automated') {
8125: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8126: $sleep = 2;
8127: $loopmax = 100;
1.547 raeburn 8128: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8129: } else {
8130: $homeserver = &homeserver($cnum,$dom);
8131: }
1.838 albertel 8132: my $host=&hostname($homeserver);
1.506 raeburn 8133: my $cmd = '';
1.1000 raeburn 8134: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8135: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8136: }
8137: $cmd =~ s/%%$//;
8138: $cmd = &escape($cmd);
8139: my $query = 'fetchenrollment';
1.620 albertel 8140: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8141: unless ($queryid=~/^\Q$host\E\_/) {
8142: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8143: return 'error: '.$queryid;
8144: }
1.1172.2.93 raeburn 8145: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8146: my $tries = 1;
8147: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8148: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8149: $tries ++;
8150: }
1.526 raeburn 8151: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8152: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8153: } else {
1.901 albertel 8154: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8155: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8156: foreach my $line (@responses) {
8157: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8158: $$replyref{$key} = $value;
8159: }
8160: } else {
1.1117 foxr 8161: my $pathname = LONCAPA::tempdir();
1.800 albertel 8162: foreach my $line (@responses) {
8163: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8164: $$replyref{$key} = $value;
8165: if ($value > 0) {
1.800 albertel 8166: foreach my $item (@{$$affiliatesref{$key}}) {
8167: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8168: my $destname = $pathname.'/'.$filename;
8169: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8170: if ($xml_classlist =~ /^error/) {
8171: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8172: } else {
1.506 raeburn 8173: if ( open(FILE,">$destname") ) {
8174: print FILE &unescape($xml_classlist);
8175: close(FILE);
1.526 raeburn 8176: } else {
8177: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8178: }
8179: }
8180: }
8181: }
8182: }
8183: }
8184: return 'ok';
8185: }
8186: return 'error';
8187: }
8188:
1.242 www 8189: sub get_query_reply {
1.1172.2.79 raeburn 8190: my ($queryid,$sleep,$loopmax) = @_;
8191: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8192: $sleep = 0.2;
8193: }
8194: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8195: $loopmax = 100;
8196: }
1.1117 foxr 8197: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8198: my $reply='';
1.1172.2.79 raeburn 8199: for (1..$loopmax) {
8200: sleep($sleep);
1.240 www 8201: if (-e $replyfile.'.end') {
1.448 albertel 8202: if (open(my $fh,$replyfile)) {
1.904 albertel 8203: $reply = join('',<$fh>);
8204: close($fh);
1.240 www 8205: } else { return 'error: reply_file_error'; }
1.242 www 8206: return &unescape($reply);
8207: }
1.240 www 8208: }
1.242 www 8209: return 'timeout:'.$queryid;
1.240 www 8210: }
8211:
8212: sub courselog_query {
1.241 www 8213: #
8214: # possible filters:
8215: # url: url or symb
8216: # username
8217: # domain
8218: # action: view, submit, grade
8219: # start: timestamp
8220: # end: timestamp
8221: #
1.240 www 8222: my (%filters)=@_;
1.620 albertel 8223: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8224: if ($filters{'url'}) {
8225: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8226: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8227: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8228: }
1.620 albertel 8229: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8230: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8231: return &log_query($cname,$cdom,'courselog',%filters);
8232: }
8233:
8234: sub userlog_query {
1.858 raeburn 8235: #
8236: # possible filters:
8237: # action: log check role
8238: # start: timestamp
8239: # end: timestamp
8240: #
1.240 www 8241: my ($uname,$udom,%filters)=@_;
8242: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8243: }
8244:
1.506 raeburn 8245: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8246:
8247: sub auto_run {
1.508 raeburn 8248: my ($cnum,$cdom) = @_;
1.876 raeburn 8249: my $response = 0;
8250: my $settings;
8251: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8252: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8253: $settings = $domconfig{'autoenroll'};
8254: if ($settings->{'run'} eq '1') {
8255: $response = 1;
8256: }
8257: } else {
1.934 raeburn 8258: my $homeserver;
8259: if (&is_course($cdom,$cnum)) {
8260: $homeserver = &homeserver($cnum,$cdom);
8261: } else {
8262: $homeserver = &domain($cdom,'primary');
8263: }
8264: if ($homeserver ne 'no_host') {
8265: $response = &reply('autorun:'.$cdom,$homeserver);
8266: }
1.876 raeburn 8267: }
1.506 raeburn 8268: return $response;
8269: }
1.776 albertel 8270:
1.506 raeburn 8271: sub auto_get_sections {
1.508 raeburn 8272: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8273: my $homeserver;
8274: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8275: $homeserver = &homeserver($cnum,$cdom);
8276: }
8277: if (!defined($homeserver)) {
8278: if ($cdom =~ /^$match_domain$/) {
8279: $homeserver = &domain($cdom,'primary');
8280: }
8281: }
8282: my @secs;
8283: if (defined($homeserver)) {
8284: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8285: unless ($response eq 'refused') {
8286: @secs = split(/:/,$response);
8287: }
1.506 raeburn 8288: }
8289: return @secs;
8290: }
1.776 albertel 8291:
1.506 raeburn 8292: sub auto_new_course {
1.1099 raeburn 8293: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8294: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8295: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8296: return $response;
8297: }
1.776 albertel 8298:
1.506 raeburn 8299: sub auto_validate_courseID {
1.508 raeburn 8300: my ($cnum,$cdom,$inst_course_id) = @_;
8301: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8302: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8303: return $response;
8304: }
1.776 albertel 8305:
1.1007 raeburn 8306: sub auto_validate_instcode {
1.1020 raeburn 8307: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8308: my ($homeserver,$response);
8309: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8310: $homeserver = &homeserver($cnum,$cdom);
8311: }
8312: if (!defined($homeserver)) {
8313: if ($cdom =~ /^$match_domain$/) {
8314: $homeserver = &domain($cdom,'primary');
8315: }
8316: }
1.1065 raeburn 8317: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8318: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8319: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8320: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8321: }
8322:
1.506 raeburn 8323: sub auto_create_password {
1.873 raeburn 8324: my ($cnum,$cdom,$authparam,$udom) = @_;
8325: my ($homeserver,$response);
1.506 raeburn 8326: my $create_passwd = 0;
8327: my $authchk = '';
1.873 raeburn 8328: if ($udom =~ /^$match_domain$/) {
8329: $homeserver = &domain($udom,'primary');
8330: }
8331: if ($homeserver eq '') {
8332: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8333: $homeserver = &homeserver($cnum,$cdom);
8334: }
8335: }
8336: if ($homeserver eq '') {
8337: $authchk = 'nodomain';
1.506 raeburn 8338: } else {
1.873 raeburn 8339: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8340: if ($response eq 'refused') {
8341: $authchk = 'refused';
8342: } else {
1.901 albertel 8343: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8344: }
1.506 raeburn 8345: }
8346: return ($authparam,$create_passwd,$authchk);
8347: }
8348:
1.706 raeburn 8349: sub auto_photo_permission {
8350: my ($cnum,$cdom,$students) = @_;
8351: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8352: my ($outcome,$perm_reqd,$conditions) =
8353: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8354: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8355: return (undef,undef);
8356: }
1.706 raeburn 8357: return ($outcome,$perm_reqd,$conditions);
8358: }
8359:
8360: sub auto_checkphotos {
8361: my ($uname,$udom,$pid) = @_;
8362: my $homeserver = &homeserver($uname,$udom);
8363: my ($result,$resulttype);
8364: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8365: &escape($uname).':'.&escape($pid),
8366: $homeserver));
1.709 albertel 8367: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8368: return (undef,undef);
8369: }
1.706 raeburn 8370: if ($outcome) {
8371: ($result,$resulttype) = split(/:/,$outcome);
8372: }
8373: return ($result,$resulttype);
8374: }
8375:
8376: sub auto_photochoice {
8377: my ($cnum,$cdom) = @_;
8378: my $homeserver = &homeserver($cnum,$cdom);
8379: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8380: &escape($cdom),
8381: $homeserver)));
1.709 albertel 8382: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8383: return (undef,undef);
8384: }
1.706 raeburn 8385: return ($update,$comment);
8386: }
8387:
8388: sub auto_photoupdate {
8389: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8390: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8391: my $host=&hostname($homeserver);
1.706 raeburn 8392: my $cmd = '';
8393: my $maxtries = 1;
1.800 albertel 8394: foreach my $affiliate (keys(%{$affiliatesref})) {
8395: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8396: }
8397: $cmd =~ s/%%$//;
8398: $cmd = &escape($cmd);
8399: my $query = 'institutionalphotos';
8400: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8401: unless ($queryid=~/^\Q$host\E\_/) {
8402: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8403: return 'error: '.$queryid;
8404: }
8405: my $reply = &get_query_reply($queryid);
8406: my $tries = 1;
8407: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8408: $reply = &get_query_reply($queryid);
8409: $tries ++;
8410: }
8411: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8412: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8413: } else {
8414: my @responses = split(/:/,$reply);
8415: my $outcome = shift(@responses);
8416: foreach my $item (@responses) {
8417: my ($key,$value) = split(/=/,$item);
8418: $$photo{$key} = $value;
8419: }
8420: return $outcome;
8421: }
8422: return 'error';
8423: }
8424:
1.521 raeburn 8425: sub auto_instcode_format {
1.793 albertel 8426: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8427: $cat_order) = @_;
1.521 raeburn 8428: my $courses = '';
1.772 raeburn 8429: my @homeservers;
1.521 raeburn 8430: if ($caller eq 'global') {
1.841 albertel 8431: my %servers = &get_servers($codedom,'library');
8432: foreach my $tryserver (keys(%servers)) {
8433: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8434: push(@homeservers,$tryserver);
8435: }
1.584 raeburn 8436: }
1.1022 raeburn 8437: } elsif ($caller eq 'requests') {
8438: if ($codedom =~ /^$match_domain$/) {
8439: my $chome = &domain($codedom,'primary');
8440: unless ($chome eq 'no_host') {
8441: push(@homeservers,$chome);
8442: }
8443: }
1.521 raeburn 8444: } else {
1.772 raeburn 8445: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8446: }
1.793 albertel 8447: foreach my $code (keys(%{$instcodes})) {
8448: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8449: }
8450: chop($courses);
1.772 raeburn 8451: my $ok_response = 0;
8452: my $response;
8453: while (@homeservers > 0 && $ok_response == 0) {
8454: my $server = shift(@homeservers);
8455: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8456: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8457: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8458: split(/:/,$response);
1.772 raeburn 8459: %{$codes} = (%{$codes},&str2hash($codes_str));
8460: push(@{$codetitles},&str2array($codetitles_str));
8461: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8462: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8463: $ok_response = 1;
8464: }
8465: }
8466: if ($ok_response) {
1.521 raeburn 8467: return 'ok';
1.772 raeburn 8468: } else {
8469: return $response;
1.521 raeburn 8470: }
8471: }
8472:
1.792 raeburn 8473: sub auto_instcode_defaults {
8474: my ($domain,$returnhash,$code_order) = @_;
8475: my @homeservers;
1.841 albertel 8476:
8477: my %servers = &get_servers($domain,'library');
8478: foreach my $tryserver (keys(%servers)) {
8479: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8480: push(@homeservers,$tryserver);
8481: }
1.792 raeburn 8482: }
1.841 albertel 8483:
1.792 raeburn 8484: my $response;
1.841 albertel 8485: foreach my $server (@homeservers) {
1.792 raeburn 8486: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8487: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8488:
8489: foreach my $pair (split(/\&/,$response)) {
8490: my ($name,$value)=split(/\=/,$pair);
8491: if ($name eq 'code_order') {
8492: @{$code_order} = split(/\&/,&unescape($value));
8493: } else {
8494: $returnhash->{&unescape($name)}=&unescape($value);
8495: }
8496: }
8497: return 'ok';
1.792 raeburn 8498: }
1.841 albertel 8499:
8500: return $response;
1.1003 raeburn 8501: }
8502:
8503: sub auto_possible_instcodes {
1.1007 raeburn 8504: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8505: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8506: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8507: return;
8508: }
1.1003 raeburn 8509: my (@homeservers,$uhome);
8510: if (defined(&domain($domain,'primary'))) {
8511: $uhome=&domain($domain,'primary');
8512: push(@homeservers,&domain($domain,'primary'));
8513: } else {
8514: my %servers = &get_servers($domain,'library');
8515: foreach my $tryserver (keys(%servers)) {
8516: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8517: push(@homeservers,$tryserver);
8518: }
8519: }
8520: }
8521: my $response;
8522: foreach my $server (@homeservers) {
8523: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8524: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8525: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8526: split(':',$response);
8527: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8528: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8529: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8530: my ($name,$value)=split('=',$item);
8531: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8532: }
8533: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8534: my ($name,$value)=split('=',$item);
8535: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8536: }
8537: return 'ok';
8538: }
8539: return $response;
8540: }
1.792 raeburn 8541:
1.1010 raeburn 8542: sub auto_courserequest_checks {
8543: my ($dom) = @_;
1.1020 raeburn 8544: my ($homeserver,%validations);
8545: if ($dom =~ /^$match_domain$/) {
8546: $homeserver = &domain($dom,'primary');
8547: }
8548: unless ($homeserver eq 'no_host') {
8549: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8550: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8551: my @items = split(/&/,$response);
8552: foreach my $item (@items) {
8553: my ($key,$value) = split('=',$item);
8554: $validations{&unescape($key)} = &thaw_unescape($value);
8555: }
8556: }
8557: }
1.1010 raeburn 8558: return %validations;
8559: }
8560:
1.1020 raeburn 8561: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8562: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8563: my ($homeserver,$response);
8564: if ($dom =~ /^$match_domain$/) {
8565: $homeserver = &domain($dom,'primary');
8566: }
1.1172.2.43 raeburn 8567: unless ($homeserver eq 'no_host') {
8568: my $customdata;
8569: if (ref($custominfo) eq 'HASH') {
8570: $customdata = &freeze_escape($custominfo);
8571: }
1.1020 raeburn 8572: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8573: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8574: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8575: $customdata,$homeserver));
1.1020 raeburn 8576: }
8577: return $response;
8578: }
8579:
1.777 albertel 8580: sub auto_validate_class_sec {
1.918 raeburn 8581: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8582: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8583: my $ownerlist;
8584: if (ref($owners) eq 'ARRAY') {
8585: $ownerlist = join(',',@{$owners});
8586: } else {
8587: $ownerlist = $owners;
8588: }
1.773 raeburn 8589: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8590: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8591: return $response;
8592: }
8593:
1.1172.2.38 raeburn 8594: sub auto_crsreq_update {
8595: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8596: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8597: my ($homeserver,%crsreqresponse);
8598: if ($cdom =~ /^$match_domain$/) {
8599: $homeserver = &domain($cdom,'primary');
8600: }
8601: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8602: my $info;
8603: if (ref($inbound) eq 'HASH') {
8604: $info = &freeze_escape($inbound);
8605: }
8606: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8607: ':'.&escape($action).':'.&escape($ownername).':'.
8608: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8609: &escape($title).':'.&escape($code).':'.
8610: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8611: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8612: my @items = split(/&/,$response);
8613: foreach my $item (@items) {
8614: my ($key,$value) = split('=',$item);
8615: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8616: }
8617: }
8618: }
8619: return \%crsreqresponse;
8620: }
8621:
1.1172.2.78 raeburn 8622: sub auto_export_grades {
8623: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8624: my ($homeserver,%exportresponse);
8625: if ($cdom =~ /^$match_domain$/) {
8626: $homeserver = &domain($cdom,'primary');
8627: }
8628: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8629: my $info;
8630: if (ref($inforef) eq 'HASH') {
8631: $info = &freeze_escape($inforef);
8632: }
8633: if (ref($gradesref) eq 'HASH') {
8634: my $grades = &freeze_escape($gradesref);
8635: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8636: $info.':'.$grades,$homeserver);
8637: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8638: my @items = split(/&/,$response);
8639: foreach my $item (@items) {
8640: my ($key,$value) = split('=',$item);
8641: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8642: }
8643: }
8644: }
8645: }
8646: return \%exportresponse;
8647: }
8648:
1.1172.2.68 raeburn 8649: sub check_instcode_cloning {
8650: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8651: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8652: return;
8653: }
8654: my $canclone;
8655: if (@{$code_order} > 0) {
8656: my $instcoderegexp ='^';
8657: my @clonecodes = split(/\&/,$cloner);
8658: foreach my $item (@{$code_order}) {
8659: if (grep(/^\Q$item\E=/,@clonecodes)) {
8660: foreach my $pair (@clonecodes) {
8661: my ($key,$val) = split(/\=/,$pair,2);
8662: $val = &unescape($val);
8663: if ($key eq $item) {
8664: $instcoderegexp .= '('.$val.')';
8665: last;
8666: }
8667: }
8668: } else {
8669: $instcoderegexp .= $codedefaults->{$item};
8670: }
8671: }
8672: $instcoderegexp .= '$';
8673: my (@from,@to);
8674: eval {
8675: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8676: (@to) = ($clonetocode =~ /$instcoderegexp/);
8677: };
8678: if ((@from > 0) && (@to > 0)) {
8679: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8680: if (!@diffs) {
8681: $canclone = 1;
8682: }
8683: }
8684: }
8685: return $canclone;
8686: }
8687:
8688: sub default_instcode_cloning {
8689: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8690: my (%codedefaults,@code_order,$canclone);
8691: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8692: %codedefaults = %{$codedefaultsref};
8693: @code_order = @{$codeorderref};
8694: } elsif ($clonedom) {
8695: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8696: }
8697: if (($domdefclone) && (@code_order)) {
8698: my @clonecodes = split(/\+/,$domdefclone);
8699: my $instcoderegexp ='^';
8700: foreach my $item (@code_order) {
8701: if (grep(/^\Q$item\E$/,@clonecodes)) {
8702: $instcoderegexp .= '('.$codedefaults{$item}.')';
8703: } else {
8704: $instcoderegexp .= $codedefaults{$item};
8705: }
8706: }
8707: $instcoderegexp .= '$';
8708: my (@from,@to);
8709: eval {
8710: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8711: (@to) = ($clonetocode =~ /$instcoderegexp/);
8712: };
8713: if ((@from > 0) && (@to > 0)) {
8714: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8715: if (!@diffs) {
8716: $canclone = 1;
8717: }
8718: }
8719: }
8720: return $canclone;
8721: }
8722:
1.679 raeburn 8723: # ------------------------------------------------------- Course Group routines
8724:
8725: sub get_coursegroups {
1.809 raeburn 8726: my ($cdom,$cnum,$group,$namespace) = @_;
8727: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8728: }
8729:
1.679 raeburn 8730: sub modify_coursegroup {
8731: my ($cdom,$cnum,$groupsettings) = @_;
8732: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8733: }
8734:
1.809 raeburn 8735: sub toggle_coursegroup_status {
8736: my ($cdom,$cnum,$group,$action) = @_;
8737: my ($from_namespace,$to_namespace);
8738: if ($action eq 'delete') {
8739: $from_namespace = 'coursegroups';
8740: $to_namespace = 'deleted_groups';
8741: } else {
8742: $from_namespace = 'deleted_groups';
8743: $to_namespace = 'coursegroups';
8744: }
8745: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8746: if (my $tmp = &error(%curr_group)) {
8747: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8748: return ('read error',$tmp);
8749: } else {
8750: my %savedsettings = %curr_group;
1.809 raeburn 8751: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8752: my $deloutcome;
8753: if ($result eq 'ok') {
1.809 raeburn 8754: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8755: } else {
8756: return ('write error',$result);
8757: }
8758: if ($deloutcome eq 'ok') {
8759: return 'ok';
8760: } else {
8761: return ('delete error',$deloutcome);
8762: }
8763: }
8764: }
8765:
1.679 raeburn 8766: sub modify_group_roles {
1.957 raeburn 8767: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8768: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8769: my $role = 'gr/'.&escape($userprivs);
8770: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8771: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8772: if ($result eq 'ok') {
8773: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8774: }
1.679 raeburn 8775: return $result;
8776: }
8777:
8778: sub modify_coursegroup_membership {
8779: my ($cdom,$cnum,$membership) = @_;
8780: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8781: return $result;
8782: }
8783:
1.682 raeburn 8784: sub get_active_groups {
8785: my ($udom,$uname,$cdom,$cnum) = @_;
8786: my $now = time;
8787: my %groups = ();
8788: foreach my $key (keys(%env)) {
1.811 albertel 8789: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8790: my ($start,$end) = split(/\./,$env{$key});
8791: if (($end!=0) && ($end<$now)) { next; }
8792: if (($start!=0) && ($start>$now)) { next; }
8793: if ($1 eq $cdom && $2 eq $cnum) {
8794: $groups{$3} = $env{$key} ;
8795: }
8796: }
8797: }
8798: return %groups;
8799: }
8800:
1.683 raeburn 8801: sub get_group_membership {
8802: my ($cdom,$cnum,$group) = @_;
8803: return(&dump('groupmembership',$cdom,$cnum,$group));
8804: }
8805:
8806: sub get_users_groups {
8807: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8808: my @usersgroups;
1.683 raeburn 8809: my $cachetime=1800;
8810:
8811: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8812: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8813: if (defined($cached)) {
1.734 albertel 8814: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8815: } else {
8816: $grouplist = '';
1.816 raeburn 8817: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8818: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8819: my $access_end = $env{'course.'.$courseid.
8820: '.default_enrollment_end_date'};
8821: my $now = time;
8822: foreach my $key (keys(%roleshash)) {
8823: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8824: my $group = $1;
8825: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8826: my $start = $2;
8827: my $end = $1;
8828: if ($start == -1) { next; } # deleted from group
8829: if (($start!=0) && ($start>$now)) { next; }
8830: if (($end!=0) && ($end<$now)) {
8831: if ($access_end && $access_end < $now) {
8832: if ($access_end - $end < 86400) {
8833: push(@usersgroups,$group);
1.733 raeburn 8834: }
8835: }
1.817 raeburn 8836: next;
1.733 raeburn 8837: }
1.817 raeburn 8838: push(@usersgroups,$group);
1.683 raeburn 8839: }
8840: }
8841: }
1.817 raeburn 8842: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8843: $grouplist = join(':',@usersgroups);
8844: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8845: }
1.733 raeburn 8846: return @usersgroups;
1.683 raeburn 8847: }
8848:
8849: sub devalidate_getgroups_cache {
8850: my ($udom,$uname,$cdom,$cnum)=@_;
8851: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8852:
1.683 raeburn 8853: my $hashid="$udom:$uname:$courseid";
8854: &devalidate_cache_new('getgroups',$hashid);
8855: }
8856:
1.12 www 8857: # ------------------------------------------------------------------ Plain Text
8858:
8859: sub plaintext {
1.988 raeburn 8860: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8861: if ($short =~ m{^cr/}) {
1.758 albertel 8862: return (split('/',$short))[-1];
8863: }
1.742 raeburn 8864: if (!defined($cid)) {
8865: $cid = $env{'request.course.id'};
8866: }
8867: my %rolenames = (
1.1008 raeburn 8868: Course => 'std',
8869: Community => 'alt1',
1.742 raeburn 8870: );
1.1037 raeburn 8871: if ($cid ne '') {
8872: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8873: unless ($forcedefault) {
8874: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8875: &Apache::lonlocal::mt_escape(\$roletext);
8876: return &Apache::lonlocal::mt($roletext);
8877: }
8878: }
8879: }
8880: if ((defined($type)) && (defined($rolenames{$type})) &&
8881: (defined($rolenames{$type})) &&
8882: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8883: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8884: } elsif ($cid ne '') {
8885: my $crstype = $env{'course.'.$cid.'.type'};
8886: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8887: (defined($prp{$short}{$rolenames{$crstype}}))) {
8888: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8889: }
1.742 raeburn 8890: }
1.1037 raeburn 8891: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8892: }
8893:
8894: # ----------------------------------------------------------------- Assign Role
8895:
8896: sub assignrole {
1.957 raeburn 8897: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8898: $context)=@_;
1.21 www 8899: my $mrole;
8900: if ($role =~ /^cr\//) {
1.393 www 8901: my $cwosec=$url;
1.811 albertel 8902: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8903: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8904: my $refused = 1;
8905: if ($context eq 'requestcourses') {
8906: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8907: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8908: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8909: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8910: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8911: if ($crsenv{'internal.courseowner'} eq
8912: $env{'user.name'}.':'.$env{'user.domain'}) {
8913: $refused = '';
8914: }
8915: }
8916: }
8917: }
8918: }
8919: if ($refused) {
8920: &logthis('Refused custom assignrole: '.
8921: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8922: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8923: return 'refused';
8924: }
1.104 www 8925: }
1.21 www 8926: $mrole='cr';
1.678 raeburn 8927: } elsif ($role =~ /^gr\//) {
8928: my $cwogrp=$url;
1.811 albertel 8929: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8930: unless (&allowed('mdg',$cwogrp)) {
8931: &logthis('Refused group assignrole: '.
8932: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8933: $env{'user.name'}.' at '.$env{'user.domain'});
8934: return 'refused';
8935: }
8936: $mrole='gr';
1.21 www 8937: } else {
1.82 www 8938: my $cwosec=$url;
1.811 albertel 8939: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8940: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8941: my $refused;
8942: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8943: if (!(&allowed('c'.$role,$url))) {
8944: $refused = 1;
8945: }
8946: } else {
8947: $refused = 1;
8948: }
1.947 raeburn 8949: if ($refused) {
1.1045 raeburn 8950: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8951: if (!$selfenroll && $context eq 'course') {
8952: my %crsenv;
8953: if ($role eq 'cc' || $role eq 'co') {
8954: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8955: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8956: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8957: if ($crsenv{'internal.courseowner'} eq
8958: $env{'user.name'}.':'.$env{'user.domain'}) {
8959: $refused = '';
8960: }
8961: }
8962: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8963: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8964: if ($crsenv{'internal.courseowner'} eq
8965: $env{'user.name'}.':'.$env{'user.domain'}) {
8966: $refused = '';
8967: }
8968: }
8969: }
8970: }
8971: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8972: $refused = '';
1.1017 raeburn 8973: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8974: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8975: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8976: my $wrongcc;
8977: if ($cnum =~ /^$match_community$/) {
8978: $wrongcc = 1 if ($role eq 'cc');
8979: } else {
8980: $wrongcc = 1 if ($role eq 'co');
8981: }
8982: unless ($wrongcc) {
8983: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8984: if ($crsenv{'internal.courseowner'} eq
8985: $env{'user.name'}.':'.$env{'user.domain'}) {
8986: $refused = '';
8987: }
1.1017 raeburn 8988: }
8989: }
1.1172.2.9 raeburn 8990: } elsif ($context eq 'requestauthor') {
8991: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8992: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8993: if ($env{'environment.requestauthor'} eq 'automatic') {
8994: $refused = '';
8995: } else {
8996: my %domdefaults = &get_domain_defaults($udom);
8997: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8998: my $checkbystatus;
8999: if ($env{'user.adv'}) {
9000: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9001: if ($disposition eq 'automatic') {
9002: $refused = '';
9003: } elsif ($disposition eq '') {
9004: $checkbystatus = 1;
9005: }
9006: } else {
9007: $checkbystatus = 1;
9008: }
9009: if ($checkbystatus) {
9010: if ($env{'environment.inststatus'}) {
9011: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9012: foreach my $type (@inststatuses) {
9013: if (($type ne '') &&
9014: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9015: $refused = '';
9016: }
9017: }
9018: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9019: $refused = '';
9020: }
9021: }
9022: }
9023: }
9024: }
1.1017 raeburn 9025: }
9026: if ($refused) {
1.947 raeburn 9027: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9028: ' '.$role.' '.$end.' '.$start.' by '.
9029: $env{'user.name'}.' at '.$env{'user.domain'});
9030: return 'refused';
9031: }
1.932 raeburn 9032: }
1.1131 raeburn 9033: } elsif ($role eq 'au') {
9034: if ($url ne '/'.$udom.'/') {
9035: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9036: ' to assign author role for '.$uname.':'.$udom.
9037: ' in domain: '.$url.' refused (wrong domain).');
9038: return 'refused';
9039: }
1.104 www 9040: }
1.21 www 9041: $mrole=$role;
9042: }
1.620 albertel 9043: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9044: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9045: if ($end) { $command.='_'.$end; }
1.21 www 9046: if ($start) {
9047: if ($end) {
1.81 www 9048: $command.='_'.$start;
1.21 www 9049: } else {
1.81 www 9050: $command.='_0_'.$start;
1.21 www 9051: }
9052: }
1.739 raeburn 9053: my $origstart = $start;
9054: my $origend = $end;
1.957 raeburn 9055: my $delflag;
1.357 www 9056: # actually delete
9057: if ($deleteflag) {
1.373 www 9058: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9059: # modify command to delete the role
1.620 albertel 9060: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9061: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9062: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9063: # set start and finish to negative values for userrolelog
9064: $start=-1;
9065: $end=-1;
1.957 raeburn 9066: $delflag = 1;
1.357 www 9067: }
9068: }
9069: # send command
1.349 www 9070: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9071: # log new user role if status is ok
1.349 www 9072: if ($answer eq 'ok') {
1.663 raeburn 9073: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9074: if (($role eq 'cc') || ($role eq 'in') ||
9075: ($role eq 'ep') || ($role eq 'ad') ||
9076: ($role eq 'ta') || ($role eq 'st') ||
9077: ($role=~/^cr/) || ($role eq 'gr') ||
9078: ($role eq 'co')) {
1.1172.2.13 raeburn 9079: # for course roles, perform group memberships changes triggered by role change.
9080: unless ($role =~ /^gr/) {
9081: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9082: $origstart,$selfenroll,$context);
9083: }
1.1172.2.9 raeburn 9084: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9085: $selfenroll,$context);
9086: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9087: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9088: ($role eq 'da')) {
1.1172.2.9 raeburn 9089: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9090: $context);
9091: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9092: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9093: $context);
9094: }
1.1053 raeburn 9095: if ($role eq 'cc') {
9096: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9097: }
1.349 www 9098: }
9099: return $answer;
1.169 harris41 9100: }
9101:
1.1053 raeburn 9102: sub autoupdate_coowners {
9103: my ($url,$end,$start,$uname,$udom) = @_;
9104: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9105: if (($cdom ne '') && ($cnum ne '')) {
9106: my $now = time;
9107: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9108: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9109: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9110: my $instcode = $coursehash{'internal.coursecode'};
9111: if ($instcode ne '') {
1.1056 raeburn 9112: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9113: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9114: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9115: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9116: if ($result eq 'valid') {
9117: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9118: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9119: push(@newcoowners,$coowner);
9120: }
9121: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9122: push(@newcoowners,$uname.':'.$udom);
9123: }
9124: @newcoowners = sort(@newcoowners);
9125: } else {
9126: push(@newcoowners,$uname.':'.$udom);
9127: }
9128: } else {
9129: if ($coursehash{'internal.co-owners'}) {
9130: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9131: unless ($coowner eq $uname.':'.$udom) {
9132: push(@newcoowners,$coowner);
9133: }
9134: }
9135: unless (@newcoowners > 0) {
9136: $delcoowners = 1;
9137: $coowners = '';
9138: }
9139: }
9140: }
9141: if (@newcoowners || $delcoowners) {
9142: &store_coowners($cdom,$cnum,$coursehash{'home'},
9143: $delcoowners,@newcoowners);
9144: }
9145: }
9146: }
9147: }
9148: }
9149: }
9150: }
9151:
9152: sub store_coowners {
9153: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9154: my $cid = $cdom.'_'.$cnum;
9155: my ($coowners,$delresult,$putresult);
9156: if (@newcoowners) {
9157: $coowners = join(',',@newcoowners);
9158: my %coownershash = (
9159: 'internal.co-owners' => $coowners,
9160: );
9161: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9162: if ($putresult eq 'ok') {
9163: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9164: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9165: }
9166: }
9167: }
9168: if ($delcoowners) {
9169: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9170: if ($delresult eq 'ok') {
9171: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9172: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9173: }
9174: }
9175: }
9176: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9177: my %crsinfo =
9178: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9179: if (ref($crsinfo{$cid}) eq 'HASH') {
9180: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9181: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9182: }
9183: }
9184: }
9185:
1.169 harris41 9186: # -------------------------------------------------- Modify user authentication
1.197 www 9187: # Overrides without validation
9188:
1.169 harris41 9189: sub modifyuserauth {
9190: my ($udom,$uname,$umode,$upass)=@_;
9191: my $uhome=&homeserver($uname,$udom);
1.197 www 9192: unless (&allowed('mau',$udom)) { return 'refused'; }
9193: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9194: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9195: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9196: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9197: &escape($upass),$uhome);
1.620 albertel 9198: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9199: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9200: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9201: &log($udom,,$uname,$uhome,
1.620 albertel 9202: 'Authentication changed by '.$env{'user.domain'}.', '.
9203: $env{'user.name'}.', '.$umode.
1.197 www 9204: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9205: unless ($reply eq 'ok') {
1.197 www 9206: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9207: return 'error: '.$reply;
9208: }
1.170 harris41 9209: return 'ok';
1.80 www 9210: }
9211:
1.81 www 9212: # --------------------------------------------------------------- Modify a user
1.80 www 9213:
1.81 www 9214: sub modifyuser {
1.206 matthew 9215: my ($udom, $uname, $uid,
9216: $umode, $upass, $first,
9217: $middle, $last, $gene,
1.1058 raeburn 9218: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9219: $udom= &LONCAPA::clean_domain($udom);
9220: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9221: my $showcandelete = 'none';
9222: if (ref($candelete) eq 'ARRAY') {
9223: if (@{$candelete} > 0) {
9224: $showcandelete = join(', ',@{$candelete});
9225: }
9226: }
1.81 www 9227: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9228: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9229: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9230: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9231: ' desiredhome not specified').
1.620 albertel 9232: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9233: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9234: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9235: my $newuser;
9236: if ($uhome eq 'no_host') {
9237: $newuser = 1;
9238: }
1.80 www 9239: # ----------------------------------------------------------------- Create User
1.406 albertel 9240: if (($uhome eq 'no_host') &&
9241: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9242: my $unhome='';
1.844 albertel 9243: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9244: $unhome = $desiredhome;
1.620 albertel 9245: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9246: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9247: } else { # load balancing routine for determining $unhome
1.81 www 9248: my $loadm=10000000;
1.841 albertel 9249: my %servers = &get_servers($udom,'library');
9250: foreach my $tryserver (keys(%servers)) {
9251: my $answer=reply('load',$tryserver);
9252: if (($answer=~/\d+/) && ($answer<$loadm)) {
9253: $loadm=$answer;
9254: $unhome=$tryserver;
9255: }
1.80 www 9256: }
9257: }
9258: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9259: return 'error: unable to find a home server for '.$uname.
9260: ' in domain '.$udom;
1.80 www 9261: }
9262: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9263: &escape($upass),$unhome);
9264: unless ($reply eq 'ok') {
9265: return 'error: '.$reply;
9266: }
1.230 stredwic 9267: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9268: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9269: return 'error: unable verify users home machine.';
1.80 www 9270: }
1.209 matthew 9271: } # End of creation of new user
1.80 www 9272: # ---------------------------------------------------------------------- Add ID
9273: if ($uid) {
9274: $uid=~tr/A-Z/a-z/;
9275: my %uidhash=&idrget($udom,$uname);
1.196 www 9276: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9277: && (!$forceid)) {
1.80 www 9278: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9279: return 'error: user id "'.$uid.'" does not match '.
9280: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9281: }
9282: } else {
9283: &idput($udom,($uname => $uid));
9284: }
9285: }
9286: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9287: my @tmp=&get('environment',
1.899 raeburn 9288: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9289: 'permanentemail','inststatus'],
1.134 albertel 9290: $udom,$uname);
1.1075 raeburn 9291: my (%names,%oldnames);
1.313 matthew 9292: if ($tmp[0] =~ m/^error:.*/) {
9293: %names=();
9294: } else {
9295: %names = @tmp;
1.1075 raeburn 9296: %oldnames = %names;
1.313 matthew 9297: }
1.388 www 9298: #
1.1058 raeburn 9299: # If name, email and/or uid are blank (e.g., because an uploaded file
9300: # of users did not contain them), do not overwrite existing values
9301: # unless field is in $candelete array ref.
9302: #
9303:
9304: my @fields = ('firstname','middlename','lastname','generation',
9305: 'permanentemail','id');
9306: my %newvalues;
9307: if (ref($candelete) eq 'ARRAY') {
9308: foreach my $field (@fields) {
9309: if (grep(/^\Q$field\E$/,@{$candelete})) {
9310: if ($field eq 'firstname') {
9311: $names{$field} = $first;
9312: } elsif ($field eq 'middlename') {
9313: $names{$field} = $middle;
9314: } elsif ($field eq 'lastname') {
9315: $names{$field} = $last;
9316: } elsif ($field eq 'generation') {
9317: $names{$field} = $gene;
9318: } elsif ($field eq 'permanentemail') {
9319: $names{$field} = $email;
9320: } elsif ($field eq 'id') {
9321: $names{$field} = $uid;
9322: }
9323: }
9324: }
9325: }
1.388 www 9326: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9327: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9328: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9329: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9330: if ($email) {
9331: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9332: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9333: }
1.899 raeburn 9334: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9335: if (defined($inststatus)) {
9336: $names{'inststatus'} = '';
9337: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9338: if (ref($usertypes) eq 'HASH') {
9339: my @okstatuses;
9340: foreach my $item (split(/:/,$inststatus)) {
9341: if (defined($usertypes->{$item})) {
9342: push(@okstatuses,$item);
9343: }
9344: }
9345: if (@okstatuses) {
9346: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9347: }
9348: }
9349: }
1.1075 raeburn 9350: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9351: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9352: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9353: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9354: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9355: } else {
9356: $logmsg .= ' during self creation';
9357: }
1.1075 raeburn 9358: my $changed;
9359: if ($newuser) {
9360: $changed = 1;
9361: } else {
9362: foreach my $field (@fields) {
9363: if ($names{$field} ne $oldnames{$field}) {
9364: $changed = 1;
9365: last;
9366: }
9367: }
9368: }
9369: unless ($changed) {
9370: $logmsg = 'No changes in user information needed for: '.$logmsg;
9371: &logthis($logmsg);
9372: return 'ok';
9373: }
9374: my $reply = &put('environment', \%names, $udom,$uname);
9375: if ($reply ne 'ok') {
9376: return 'error: '.$reply;
9377: }
1.1087 raeburn 9378: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9379: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9380: }
1.1075 raeburn 9381: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9382: &devalidate_cache_new('namescache',$uname.':'.$udom);
9383: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9384: &logthis($logmsg);
1.134 albertel 9385: return 'ok';
1.80 www 9386: }
9387:
1.81 www 9388: # -------------------------------------------------------------- Modify student
1.80 www 9389:
1.81 www 9390: sub modifystudent {
9391: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9392: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9393: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9394: if (!$cid) {
1.620 albertel 9395: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9396: return 'not_in_class';
9397: }
1.80 www 9398: }
9399: # --------------------------------------------------------------- Make the user
1.81 www 9400: my $reply=&modifyuser
1.209 matthew 9401: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9402: $desiredhome,$email,$inststatus);
1.80 www 9403: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9404: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9405: # student's environment
1.297 matthew 9406: $uid = undef if (!$forceid);
1.455 albertel 9407: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9408: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9409: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9410: return $reply;
9411: }
9412:
9413: sub modify_student_enrollment {
1.1172.2.23 raeburn 9414: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9415: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9416: my ($cdom,$cnum,$chome);
9417: if (!$cid) {
1.620 albertel 9418: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9419: return 'not_in_class';
9420: }
1.620 albertel 9421: $cdom=$env{'course.'.$cid.'.domain'};
9422: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9423: } else {
9424: ($cdom,$cnum)=split(/_/,$cid);
9425: }
1.620 albertel 9426: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9427: if (!$chome) {
1.457 raeburn 9428: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9429: }
1.455 albertel 9430: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9431: # Make sure the user exists
1.81 www 9432: my $uhome=&homeserver($uname,$udom);
9433: if (($uhome eq '') || ($uhome eq 'no_host')) {
9434: return 'error: no such user';
9435: }
1.297 matthew 9436: # Get student data if we were not given enough information
9437: if (!defined($first) || $first eq '' ||
9438: !defined($last) || $last eq '' ||
9439: !defined($uid) || $uid eq '' ||
9440: !defined($middle) || $middle eq '' ||
9441: !defined($gene) || $gene eq '') {
1.294 matthew 9442: # They did not supply us with enough data to enroll the student, so
9443: # we need to pick up more information.
1.297 matthew 9444: my %tmp = &get('environment',
1.294 matthew 9445: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9446: ,$udom,$uname);
9447:
1.800 albertel 9448: #foreach my $key (keys(%tmp)) {
9449: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9450: #}
1.294 matthew 9451: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9452: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9453: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9454: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9455: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9456: }
1.556 albertel 9457: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9458: my $user = "$uname:$udom";
9459: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9460: my $reply=cput('classlist',
1.1148 raeburn 9461: {$user =>
1.1172.2.76 raeburn 9462: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9463: $cdom,$cnum);
1.1148 raeburn 9464: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9465: &devalidate_getsection_cache($udom,$uname,$cid);
9466: } else {
1.81 www 9467: return 'error: '.$reply;
9468: }
1.297 matthew 9469: # Add student role to user
1.83 www 9470: my $uurl='/'.$cid;
1.81 www 9471: $uurl=~s/\_/\//g;
9472: if ($usec) {
9473: $uurl.='/'.$usec;
9474: }
1.1148 raeburn 9475: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9476: $selfenroll,$context);
9477: if ($result ne 'ok') {
9478: if ($old_entry{$user} ne '') {
9479: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9480: } else {
9481: $reply = &del('classlist',[$user],$cdom,$cnum);
9482: }
9483: }
9484: return $result;
1.21 www 9485: }
9486:
1.556 albertel 9487: sub format_name {
9488: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9489: my $name;
9490: if ($first ne 'lastname') {
9491: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9492: } else {
9493: if ($lastname=~/\S/) {
9494: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9495: $name=~s/\s+,/,/;
9496: } else {
9497: $name.= $firstname.' '.$middlename.' '.$generation;
9498: }
9499: }
9500: $name=~s/^\s+//;
9501: $name=~s/\s+$//;
9502: $name=~s/\s+/ /g;
9503: return $name;
9504: }
9505:
1.84 www 9506: # ------------------------------------------------- Write to course preferences
9507:
9508: sub writecoursepref {
9509: my ($courseid,%prefs)=@_;
9510: $courseid=~s/^\///;
9511: $courseid=~s/\_/\//g;
9512: my ($cdomain,$cnum)=split(/\//,$courseid);
9513: my $chome=homeserver($cnum,$cdomain);
9514: if (($chome eq '') || ($chome eq 'no_host')) {
9515: return 'error: no such course';
9516: }
9517: my $cstring='';
1.800 albertel 9518: foreach my $pref (keys(%prefs)) {
9519: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9520: }
1.84 www 9521: $cstring=~s/\&$//;
9522: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9523: }
9524:
9525: # ---------------------------------------------------------- Make/modify course
9526:
9527: sub createcourse {
1.741 raeburn 9528: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9529: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9530: $url=&declutter($url);
9531: my $cid='';
1.1028 raeburn 9532: if ($context eq 'requestcourses') {
9533: my $can_create = 0;
9534: my ($ownername,$ownerdom) = split(':',$course_owner);
9535: if ($udom eq $ownerdom) {
9536: if (&usertools_access($ownername,$ownerdom,$category,undef,
9537: $context)) {
9538: $can_create = 1;
9539: }
9540: } else {
9541: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9542: $category);
9543: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9544: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9545: if (@curr > 0) {
9546: my @options = qw(approval validate autolimit);
9547: my $optregex = join('|',@options);
9548: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9549: $can_create = 1;
9550: }
9551: }
9552: }
9553: }
9554: if ($can_create) {
9555: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9556: unless (&allowed('ccc',$udom)) {
9557: return 'refused';
9558: }
1.1017 raeburn 9559: }
9560: } else {
9561: return 'refused';
9562: }
1.1028 raeburn 9563: } elsif (!&allowed('ccc',$udom)) {
9564: return 'refused';
1.84 www 9565: }
1.1011 raeburn 9566: # --------------------------------------------------------------- Get Unique ID
9567: my $uname;
9568: if ($cnum =~ /^$match_courseid$/) {
9569: my $chome=&homeserver($cnum,$udom,'true');
9570: if (($chome eq '') || ($chome eq 'no_host')) {
9571: $uname = $cnum;
9572: } else {
1.1038 raeburn 9573: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9574: }
9575: } else {
1.1038 raeburn 9576: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9577: }
9578: return $uname if ($uname =~ /^error/);
9579: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9580: if (!defined($course_server)) {
9581: if (defined(&domain($udom,'primary'))) {
9582: $course_server = &domain($udom,'primary');
9583: } else {
9584: $course_server = $env{'user.home'};
9585: }
9586: }
9587: my %host_servers =
9588: &Apache::lonnet::get_servers($udom,'library');
9589: unless ($host_servers{$course_server}) {
9590: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9591: }
1.84 www 9592: # ------------------------------------------------------------- Make the course
9593: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9594: $course_server);
1.84 www 9595: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9596: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9597: if (($uhome eq '') || ($uhome eq 'no_host')) {
9598: return 'error: no such course';
9599: }
1.271 www 9600: # ----------------------------------------------------------------- Course made
1.516 raeburn 9601: # log existence
1.1029 raeburn 9602: my $now = time;
1.918 raeburn 9603: my $newcourse = {
9604: $udom.'_'.$uname => {
1.921 raeburn 9605: description => $description,
9606: inst_code => $inst_code,
9607: owner => $course_owner,
9608: type => $crstype,
1.1029 raeburn 9609: creator => $env{'user.name'}.':'.
9610: $env{'user.domain'},
9611: created => $now,
9612: context => $context,
1.918 raeburn 9613: },
9614: };
1.921 raeburn 9615: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9616: # set toplevel url
1.271 www 9617: my $topurl=$url;
9618: unless ($nonstandard) {
9619: # ------------------------------------------ For standard courses, make top url
9620: my $mapurl=&clutter($url);
1.278 www 9621: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9622: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9623: <map>
9624: <resource id="1" type="start"></resource>
9625: <resource id="2" src="$mapurl"></resource>
9626: <resource id="3" type="finish"></resource>
9627: <link index="1" from="1" to="2"></link>
9628: <link index="2" from="2" to="3"></link>
9629: </map>
9630: ENDINITMAP
9631: $topurl=&declutter(
1.638 albertel 9632: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9633: );
9634: }
9635: # ----------------------------------------------------------- Write preferences
1.84 www 9636: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9637: ('description' => $description,
9638: 'url' => $topurl,
9639: 'internal.creator' => $env{'user.name'}.':'.
9640: $env{'user.domain'},
9641: 'internal.created' => $now,
9642: 'internal.creationcontext' => $context)
9643: );
1.84 www 9644: return '/'.$udom.'/'.$uname;
9645: }
9646:
1.1011 raeburn 9647: # ------------------------------------------------------------------- Create ID
9648: sub generate_coursenum {
1.1038 raeburn 9649: my ($udom,$crstype) = @_;
1.1011 raeburn 9650: my $domdesc = &domain($udom);
9651: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9652: my $first;
9653: if ($crstype eq 'Community') {
9654: $first = '0';
9655: } else {
9656: $first = int(1+rand(9));
9657: }
9658: my $uname=$first.
1.1011 raeburn 9659: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9660: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9661: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9662: # ----------------------------------------------- Make sure that does not exist
9663: my $uhome=&homeserver($uname,$udom,'true');
9664: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9665: if ($crstype eq 'Community') {
9666: $first = '0';
9667: } else {
9668: $first = int(1+rand(9));
9669: }
9670: $uname=$first.
1.1011 raeburn 9671: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9672: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9673: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9674: $uhome=&homeserver($uname,$udom,'true');
9675: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9676: return 'error: unable to generate unique course-ID';
9677: }
9678: }
9679: return $uname;
9680: }
9681:
1.813 albertel 9682: sub is_course {
1.1167 droeschl 9683: my ($cdom, $cnum) = scalar(@_) == 1 ?
9684: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9685:
9686: return unless $cdom and $cnum;
9687:
9688: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9689: '.');
9690:
1.1172.2.23 raeburn 9691: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9692: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9693: }
9694:
1.1015 raeburn 9695: sub store_userdata {
9696: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9697: my $result;
1.1016 raeburn 9698: if ($datakey ne '') {
1.1013 raeburn 9699: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9700: if ($udom eq '' || $uname eq '') {
9701: $udom = $env{'user.domain'};
9702: $uname = $env{'user.name'};
9703: }
9704: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9705: if (($uhome eq '') || ($uhome eq 'no_host')) {
9706: $result = 'error: no_host';
9707: } else {
9708: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9709: $storehash->{'host'} = $perlvar{'lonHostID'};
9710:
9711: my $namevalue='';
9712: foreach my $key (keys(%{$storehash})) {
9713: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9714: }
9715: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9716: unless ($namespace eq 'courserequests') {
9717: $datakey = &escape($datakey);
9718: }
1.1105 raeburn 9719: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9720: $namevalue,$uhome);
1.1013 raeburn 9721: }
9722: } else {
9723: $result = 'error: data to store was not a hash reference';
9724: }
9725: } else {
9726: $result= 'error: invalid requestkey';
9727: }
9728: return $result;
9729: }
9730:
1.21 www 9731: # ---------------------------------------------------------- Assign Custom Role
9732:
9733: sub assigncustomrole {
1.957 raeburn 9734: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9735: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9736: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9737: }
9738:
9739: # ----------------------------------------------------------------- Revoke Role
9740:
9741: sub revokerole {
1.957 raeburn 9742: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9743: my $now=time;
1.965 raeburn 9744: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9745: }
9746:
9747: # ---------------------------------------------------------- Revoke Custom Role
9748:
9749: sub revokecustomrole {
1.957 raeburn 9750: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9751: my $now=time;
1.357 www 9752: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9753: $deleteflag,$selfenroll,$context);
1.17 www 9754: }
9755:
1.533 banghart 9756: # ------------------------------------------------------------ Disk usage
1.535 albertel 9757: sub diskusage {
1.955 raeburn 9758: my ($udom,$uname,$directorypath,$getpropath)=@_;
9759: $directorypath =~ s/\/$//;
9760: my $listing=&reply('du2:'.&escape($directorypath).':'
9761: .&escape($getpropath).':'.&escape($uname).':'
9762: .&escape($udom),homeserver($uname,$udom));
9763: if ($listing eq 'unknown_cmd') {
9764: if ($getpropath) {
9765: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9766: }
9767: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9768: }
1.514 albertel 9769: return $listing;
1.512 banghart 9770: }
9771:
1.566 banghart 9772: sub is_locked {
1.1096 raeburn 9773: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9774: my @check;
9775: my $is_locked;
1.1093 raeburn 9776: push (@check,$file_name);
1.613 albertel 9777: my %locked = &get('file_permissions',\@check,
1.620 albertel 9778: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9779: my ($tmp)=keys(%locked);
9780: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9781:
1.566 banghart 9782: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9783: $is_locked = 'false';
9784: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9785: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9786: $is_locked = 'true';
1.1096 raeburn 9787: if (ref($which) eq 'ARRAY') {
9788: push(@{$which},$entry);
9789: } else {
9790: last;
9791: }
1.745 raeburn 9792: }
9793: }
1.566 banghart 9794: } else {
9795: $is_locked = 'false';
9796: }
1.1093 raeburn 9797: return $is_locked;
1.566 banghart 9798: }
9799:
1.759 albertel 9800: sub declutter_portfile {
9801: my ($file) = @_;
1.833 albertel 9802: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9803: return $file;
9804: }
9805:
1.559 banghart 9806: # ------------------------------------------------------------- Mark as Read Only
9807:
9808: sub mark_as_readonly {
9809: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9810: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9811: my ($tmp)=keys(%current_permissions);
9812: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9813: foreach my $file (@{$files}) {
1.759 albertel 9814: $file = &declutter_portfile($file);
1.561 banghart 9815: push(@{$current_permissions{$file}},$what);
1.559 banghart 9816: }
1.613 albertel 9817: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9818: return;
9819: }
9820:
1.572 banghart 9821: # ------------------------------------------------------------Save Selected Files
9822:
9823: sub save_selected_files {
9824: my ($user, $path, @files) = @_;
9825: my $filename = $user."savedfiles";
1.573 banghart 9826: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9827: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9828: foreach my $file (@files) {
1.620 albertel 9829: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9830: }
9831: foreach my $file (@other_files) {
1.574 banghart 9832: print (OUT $file."\n");
1.572 banghart 9833: }
1.574 banghart 9834: close (OUT);
1.572 banghart 9835: return 'ok';
9836: }
9837:
1.574 banghart 9838: sub clear_selected_files {
9839: my ($user) = @_;
9840: my $filename = $user."savedfiles";
1.1117 foxr 9841: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9842: print (OUT undef);
9843: close (OUT);
9844: return ("ok");
9845: }
9846:
1.572 banghart 9847: sub files_in_path {
9848: my ($user, $path) = @_;
9849: my $filename = $user."savedfiles";
9850: my %return_files;
1.1117 foxr 9851: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9852: while (my $line_in = <IN>) {
1.574 banghart 9853: chomp ($line_in);
9854: my @paths_and_file = split (m!/!, $line_in);
9855: my $file_part = pop (@paths_and_file);
9856: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9857: $path_part.='/';
9858: my $path_and_file = $path_part.$file_part;
9859: if ($path_part eq $path) {
9860: $return_files{$file_part}= 'selected';
9861: }
9862: }
1.574 banghart 9863: close (IN);
9864: return (\%return_files);
1.572 banghart 9865: }
9866:
9867: # called in portfolio select mode, to show files selected NOT in current directory
9868: sub files_not_in_path {
9869: my ($user, $path) = @_;
9870: my $filename = $user."savedfiles";
9871: my @return_files;
9872: my $path_part;
1.1117 foxr 9873: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9874: while (my $line = <IN>) {
1.572 banghart 9875: #ok, I know it's clunky, but I want it to work
1.800 albertel 9876: my @paths_and_file = split(m|/|, $line);
9877: my $file_part = pop(@paths_and_file);
9878: chomp($file_part);
9879: my $path_part = join('/', @paths_and_file);
1.572 banghart 9880: $path_part .= '/';
9881: my $path_and_file = $path_part.$file_part;
9882: if ($path_part ne $path) {
1.800 albertel 9883: push(@return_files, ($path_and_file));
1.572 banghart 9884: }
9885: }
1.800 albertel 9886: close(OUT);
1.574 banghart 9887: return (@return_files);
1.572 banghart 9888: }
9889:
1.745 raeburn 9890: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9891:
1.745 raeburn 9892: sub get_portfile_permissions {
9893: my ($domain,$user) = @_;
1.613 albertel 9894: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9895: my ($tmp)=keys(%current_permissions);
9896: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9897: return \%current_permissions;
9898: }
9899:
9900: #---------------------------------------------Get portfolio file access controls
9901:
1.749 raeburn 9902: sub get_access_controls {
1.745 raeburn 9903: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9904: my %access;
9905: my $real_file = $file;
9906: $file =~ s/\.meta$//;
1.745 raeburn 9907: if (defined($file)) {
1.749 raeburn 9908: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9909: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9910: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9911: }
9912: }
1.745 raeburn 9913: } else {
1.749 raeburn 9914: foreach my $key (keys(%{$current_permissions})) {
9915: if ($key =~ /\0accesscontrol$/) {
9916: if (defined($group)) {
9917: if ($key !~ m-^\Q$group\E/-) {
9918: next;
9919: }
9920: }
9921: my ($fullpath) = split(/\0/,$key);
9922: if (ref($$current_permissions{$key}) eq 'HASH') {
9923: foreach my $control (keys(%{$$current_permissions{$key}})) {
9924: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9925: }
9926: }
9927: }
9928: }
9929: }
9930: return %access;
9931: }
9932:
9933: sub modify_access_controls {
9934: my ($file_name,$changes,$domain,$user)=@_;
9935: my ($outcome,$deloutcome);
9936: my %store_permissions;
9937: my %new_values;
9938: my %new_control;
9939: my %translation;
9940: my @deletions = ();
9941: my $now = time;
9942: if (exists($$changes{'activate'})) {
9943: if (ref($$changes{'activate'}) eq 'HASH') {
9944: my @newitems = sort(keys(%{$$changes{'activate'}}));
9945: my $numnew = scalar(@newitems);
9946: for (my $i=0; $i<$numnew; $i++) {
9947: my $newkey = $newitems[$i];
9948: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9949: if ($newkey =~ /^\d+:/) {
9950: $newkey =~ s/^(\d+)/$newid/;
9951: $translation{$1} = $newid;
9952: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9953: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9954: $translation{$1} = $newid;
9955: }
1.749 raeburn 9956: $new_values{$file_name."\0".$newkey} =
9957: $$changes{'activate'}{$newitems[$i]};
9958: $new_control{$newkey} = $now;
9959: }
9960: }
9961: }
9962: my %todelete;
9963: my %changed_items;
9964: foreach my $action ('delete','update') {
9965: if (exists($$changes{$action})) {
9966: if (ref($$changes{$action}) eq 'HASH') {
9967: foreach my $key (keys(%{$$changes{$action}})) {
9968: my ($itemnum) = ($key =~ /^([^:]+):/);
9969: if ($action eq 'delete') {
9970: $todelete{$itemnum} = 1;
9971: } else {
9972: $changed_items{$itemnum} = $key;
9973: }
9974: }
1.745 raeburn 9975: }
9976: }
1.749 raeburn 9977: }
9978: # get lock on access controls for file.
9979: my $lockhash = {
9980: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9981: ':'.$env{'user.domain'},
9982: };
9983: my $tries = 0;
9984: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9985:
1.1172.2.79 raeburn 9986: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9987: $tries ++;
1.1172.2.79 raeburn 9988: sleep(0.1);
1.749 raeburn 9989: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9990: }
9991: if ($gotlock eq 'ok') {
9992: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9993: my ($tmp)=keys(%curr_permissions);
9994: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9995: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9996: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9997: if (ref($curr_controls) eq 'HASH') {
9998: foreach my $control_item (keys(%{$curr_controls})) {
9999: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10000: if (defined($todelete{$itemnum})) {
10001: push(@deletions,$file_name."\0".$control_item);
10002: } else {
10003: if (defined($changed_items{$itemnum})) {
10004: $new_control{$changed_items{$itemnum}} = $now;
10005: push(@deletions,$file_name."\0".$control_item);
10006: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10007: } else {
10008: $new_control{$control_item} = $$curr_controls{$control_item};
10009: }
10010: }
1.745 raeburn 10011: }
10012: }
10013: }
1.970 raeburn 10014: my ($group);
10015: if (&is_course($domain,$user)) {
10016: ($group,my $file) = split(/\//,$file_name,2);
10017: }
1.749 raeburn 10018: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10019: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10020: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10021: # remove lock
10022: my @del_lock = ($file_name."\0".'locked_access_records');
10023: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10024: my $sqlresult =
1.970 raeburn 10025: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10026: $group);
1.749 raeburn 10027: } else {
10028: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10029: }
1.749 raeburn 10030: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10031: }
10032:
1.827 raeburn 10033: sub make_public_indefinitely {
10034: my ($requrl) = @_;
10035: my $now = time;
10036: my $action = 'activate';
10037: my $aclnum = 0;
10038: if (&is_portfolio_url($requrl)) {
10039: my (undef,$udom,$unum,$file_name,$group) =
10040: &parse_portfolio_url($requrl);
10041: my $current_perms = &get_portfile_permissions($udom,$unum);
10042: my %access_controls = &get_access_controls($current_perms,
10043: $group,$file_name);
10044: foreach my $key (keys(%{$access_controls{$file_name}})) {
10045: my ($num,$scope,$end,$start) =
10046: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10047: if ($scope eq 'public') {
10048: if ($start <= $now && $end == 0) {
10049: $action = 'none';
10050: } else {
10051: $action = 'update';
10052: $aclnum = $num;
10053: }
10054: last;
10055: }
10056: }
10057: if ($action eq 'none') {
10058: return 'ok';
10059: } else {
10060: my %changes;
10061: my $newend = 0;
10062: my $newstart = $now;
10063: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10064: $changes{$action}{$newkey} = {
10065: type => 'public',
10066: time => {
10067: start => $newstart,
10068: end => $newend,
10069: },
10070: };
10071: my ($outcome,$deloutcome,$new_values,$translation) =
10072: &modify_access_controls($file_name,\%changes,$udom,$unum);
10073: return $outcome;
10074: }
10075: } else {
10076: return 'invalid';
10077: }
10078: }
10079:
1.745 raeburn 10080: #------------------------------------------------------Get Marked as Read Only
10081:
10082: sub get_marked_as_readonly {
10083: my ($domain,$user,$what,$group) = @_;
10084: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10085: my @readonly_files;
1.629 banghart 10086: my $cmp1=$what;
10087: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10088: while (my ($file_name,$value) = each(%{$current_permissions})) {
10089: if (defined($group)) {
10090: if ($file_name !~ m-^\Q$group\E/-) {
10091: next;
10092: }
10093: }
1.561 banghart 10094: if (ref($value) eq "ARRAY"){
10095: foreach my $stored_what (@{$value}) {
1.629 banghart 10096: my $cmp2=$stored_what;
1.759 albertel 10097: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10098: $cmp2=join('',@{$stored_what});
1.745 raeburn 10099: }
1.629 banghart 10100: if ($cmp1 eq $cmp2) {
1.561 banghart 10101: push(@readonly_files, $file_name);
1.745 raeburn 10102: last;
1.563 banghart 10103: } elsif (!defined($what)) {
10104: push(@readonly_files, $file_name);
1.745 raeburn 10105: last;
1.561 banghart 10106: }
10107: }
1.745 raeburn 10108: }
1.561 banghart 10109: }
10110: return @readonly_files;
10111: }
1.577 banghart 10112: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10113:
1.577 banghart 10114: sub get_marked_as_readonly_hash {
1.745 raeburn 10115: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10116: my %readonly_files;
1.745 raeburn 10117: while (my ($file_name,$value) = each(%{$current_permissions})) {
10118: if (defined($group)) {
10119: if ($file_name !~ m-^\Q$group\E/-) {
10120: next;
10121: }
10122: }
1.577 banghart 10123: if (ref($value) eq "ARRAY"){
10124: foreach my $stored_what (@{$value}) {
1.745 raeburn 10125: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10126: foreach my $lock_descriptor(@{$stored_what}) {
10127: if ($lock_descriptor eq 'graded') {
10128: $readonly_files{$file_name} = 'graded';
10129: } elsif ($lock_descriptor eq 'handback') {
10130: $readonly_files{$file_name} = 'handback';
10131: } else {
10132: if (!exists($readonly_files{$file_name})) {
10133: $readonly_files{$file_name} = 'locked';
10134: }
10135: }
1.745 raeburn 10136: }
1.750 banghart 10137: }
1.577 banghart 10138: }
10139: }
10140: }
10141: return %readonly_files;
10142: }
1.559 banghart 10143: # ------------------------------------------------------------ Unmark as Read Only
10144:
10145: sub unmark_as_readonly {
1.629 banghart 10146: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10147: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10148: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10149: $file_name = &declutter_portfile($file_name);
1.634 albertel 10150: my $symb_crs = $what;
10151: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10152: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10153: my ($tmp)=keys(%current_permissions);
10154: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10155: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10156: foreach my $file (@readonly_files) {
1.759 albertel 10157: my $clean_file = &declutter_portfile($file);
10158: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10159: my $current_locks = $current_permissions{$file};
1.563 banghart 10160: my @new_locks;
10161: my @del_keys;
10162: if (ref($current_locks) eq "ARRAY"){
10163: foreach my $locker (@{$current_locks}) {
1.632 albertel 10164: my $compare=$locker;
1.749 raeburn 10165: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10166: $compare=join('',@{$locker});
1.746 raeburn 10167: if ($compare ne $symb_crs) {
10168: push(@new_locks, $locker);
10169: }
1.563 banghart 10170: }
10171: }
1.650 albertel 10172: if (scalar(@new_locks) > 0) {
1.563 banghart 10173: $current_permissions{$file} = \@new_locks;
10174: } else {
10175: push(@del_keys, $file);
1.613 albertel 10176: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10177: delete($current_permissions{$file});
1.563 banghart 10178: }
10179: }
1.561 banghart 10180: }
1.613 albertel 10181: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10182: return;
10183: }
1.512 banghart 10184:
1.17 www 10185: # ------------------------------------------------------------ Directory lister
10186:
10187: sub dirlist {
1.955 raeburn 10188: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10189: $uri=~s/^\///;
10190: $uri=~s/\/$//;
1.253 stredwic 10191: my ($udom, $uname);
1.955 raeburn 10192: if ($getuserdir) {
1.253 stredwic 10193: $udom = $userdomain;
10194: $uname = $username;
1.955 raeburn 10195: } else {
10196: (undef,$udom,$uname)=split(/\//,$uri);
10197: if(defined($userdomain)) {
10198: $udom = $userdomain;
10199: }
10200: if(defined($username)) {
10201: $uname = $username;
10202: }
1.253 stredwic 10203: }
1.955 raeburn 10204: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10205:
1.955 raeburn 10206: $dirRoot = $perlvar{'lonDocRoot'};
10207: if (defined($getpropath)) {
10208: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10209: $dirRoot =~ s/\/$//;
1.955 raeburn 10210: } elsif (defined($getuserdir)) {
10211: my $subdir=$uname.'__';
10212: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10213: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10214: ."/$udom/$subdir/$uname";
10215: } elsif (defined($alternateRoot)) {
10216: $dirRoot = $alternateRoot;
1.751 banghart 10217: }
1.253 stredwic 10218:
10219: if($udom) {
10220: if($uname) {
1.1135 raeburn 10221: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10222: if ($uhome eq 'no_host') {
10223: return ([],'no_host');
10224: }
1.955 raeburn 10225: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10226: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10227: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10228: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10229: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10230: } else {
10231: @listing_results = map { &unescape($_); } split(/:/,$listing);
10232: }
1.605 matthew 10233: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10234: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10235: @listing_results = split(/:/,$listing);
10236: } else {
10237: @listing_results = map { &unescape($_); } split(/:/,$listing);
10238: }
1.1135 raeburn 10239: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10240: ($listing eq 'rejected') || ($listing eq 'refused') ||
10241: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10242: return ([],$listing);
10243: } else {
10244: return (\@listing_results);
1.1135 raeburn 10245: }
1.955 raeburn 10246: } elsif(!$alternateRoot) {
1.1136 raeburn 10247: my (%allusers,%listerror);
1.841 albertel 10248: my %servers = &get_servers($udom,'library');
1.955 raeburn 10249: foreach my $tryserver (keys(%servers)) {
10250: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10251: &escape($udom),$tryserver);
10252: if ($listing eq 'unknown_cmd') {
10253: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10254: $udom, $tryserver);
10255: } else {
10256: @listing_results = map { &unescape($_); } split(/:/,$listing);
10257: }
1.841 albertel 10258: if ($listing eq 'unknown_cmd') {
10259: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10260: $udom, $tryserver);
10261: @listing_results = split(/:/,$listing);
10262: } else {
10263: @listing_results =
10264: map { &unescape($_); } split(/:/,$listing);
10265: }
1.1136 raeburn 10266: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10267: ($listing eq 'rejected') || ($listing eq 'refused') ||
10268: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10269: $listerror{$tryserver} = $listing;
10270: } else {
1.841 albertel 10271: foreach my $line (@listing_results) {
10272: my ($entry) = split(/&/,$line,2);
10273: $allusers{$entry} = 1;
10274: }
10275: }
1.253 stredwic 10276: }
1.1136 raeburn 10277: my @alluserslist=();
1.800 albertel 10278: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10279: push(@alluserslist,$user.'&user');
1.253 stredwic 10280: }
1.1172.2.80 raeburn 10281: if (!%listerror) {
10282: # no errors
10283: return (\@alluserslist);
10284: } elsif (scalar(keys(%servers)) == 1) {
10285: # one library server, one error
10286: my ($key) = keys(%listerror);
10287: return (\@alluserslist, $listerror{$key});
10288: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10289: # con_lost indicates that we might miss data from at least one
10290: # library server
10291: return (\@alluserslist, 'con_lost');
10292: } else {
10293: # multiple library servers and no con_lost -> data should be
10294: # complete.
10295: return (\@alluserslist);
10296: }
10297:
1.253 stredwic 10298: } else {
1.1136 raeburn 10299: return ([],'missing username');
1.253 stredwic 10300: }
1.955 raeburn 10301: } elsif(!defined($getpropath)) {
1.1136 raeburn 10302: my $path = $perlvar{'lonDocRoot'}.'/res/';
10303: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10304: return (\@all_domains);
1.955 raeburn 10305: } else {
1.1136 raeburn 10306: return ([],'missing domain');
1.275 stredwic 10307: }
10308: }
10309:
10310: # --------------------------------------------- GetFileTimestamp
10311: # This function utilizes dirlist and returns the date stamp for
10312: # when it was last modified. It will also return an error of -1
10313: # if an error occurs
10314:
10315: sub GetFileTimestamp {
1.955 raeburn 10316: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10317: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10318: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10319: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10320: undef,$getuserdir);
10321: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10322: return -1;
10323: }
10324: if (ref($fileref) eq 'ARRAY') {
10325: my @stats = split('&',$fileref->[0]);
1.375 matthew 10326: # @stats contains first the filename, then the stat output
10327: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10328: } else {
10329: return -1;
1.253 stredwic 10330: }
1.26 www 10331: }
10332:
1.712 albertel 10333: sub stat_file {
10334: my ($uri) = @_;
1.787 albertel 10335: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10336:
1.955 raeburn 10337: my ($udom,$uname,$file);
1.712 albertel 10338: if ($uri =~ m-^/(uploaded|editupload)/-) {
10339: ($udom,$uname,$file) =
1.811 albertel 10340: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10341: $file = 'userfiles/'.$file;
10342: }
10343: if ($uri =~ m-^/res/-) {
10344: ($udom,$uname) =
1.807 albertel 10345: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10346: $file = $uri;
10347: }
10348:
10349: if (!$udom || !$uname || !$file) {
10350: # unable to handle the uri
10351: return ();
10352: }
1.956 raeburn 10353: my $getpropath;
10354: if ($file =~ /^userfiles\//) {
10355: $getpropath = 1;
10356: }
1.1136 raeburn 10357: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10358: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10359: return ();
10360: } else {
10361: if (ref($listref) eq 'ARRAY') {
10362: my @stats = split('&',$listref->[0]);
10363: shift(@stats); #filename is first
10364: return @stats;
10365: }
1.712 albertel 10366: }
10367: return ();
10368: }
10369:
1.26 www 10370: # -------------------------------------------------------- Value of a Condition
10371:
1.713 albertel 10372: # gets the value of a specific preevaluated condition
10373: # stored in the string $env{user.state.<cid>}
10374: # or looks up a condition reference in the bighash and if if hasn't
10375: # already been evaluated recurses into docondval to get the value of
10376: # the condition, then memoizing it to
10377: # $env{user.state.<cid>.<condition>}
1.40 www 10378: sub directcondval {
10379: my $number=shift;
1.620 albertel 10380: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10381: &Apache::lonuserstate::evalstate();
10382: }
1.713 albertel 10383: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10384: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10385: } elsif ($number =~ /^_/) {
10386: my $sub_condition;
10387: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10388: &GDBM_READER(),0640)) {
10389: $sub_condition=$bighash{'conditions'.$number};
10390: untie(%bighash);
10391: }
10392: my $value = &docondval($sub_condition);
1.949 raeburn 10393: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10394: return $value;
10395: }
1.620 albertel 10396: if ($env{'user.state.'.$env{'request.course.id'}}) {
10397: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10398: } else {
10399: return 2;
10400: }
10401: }
10402:
1.713 albertel 10403: # get the collection of conditions for this resource
1.26 www 10404: sub condval {
10405: my $condidx=shift;
1.54 www 10406: my $allpathcond='';
1.713 albertel 10407: foreach my $cond (split(/\|/,$condidx)) {
10408: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10409: $allpathcond.=
10410: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10411: }
1.191 harris41 10412: }
1.54 www 10413: $allpathcond=~s/\|$//;
1.713 albertel 10414: return &docondval($allpathcond);
10415: }
10416:
10417: #evaluates an expression of conditions
10418: sub docondval {
10419: my ($allpathcond) = @_;
10420: my $result=0;
10421: if ($env{'request.course.id'}
10422: && defined($allpathcond)) {
10423: my $operand='|';
10424: my @stack;
10425: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10426: if ($chunk eq '(') {
10427: push @stack,($operand,$result);
10428: } elsif ($chunk eq ')') {
10429: my $before=pop @stack;
10430: if (pop @stack eq '&') {
10431: $result=$result>$before?$before:$result;
10432: } else {
10433: $result=$result>$before?$result:$before;
10434: }
10435: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10436: $operand=$chunk;
10437: } else {
10438: my $new=directcondval($chunk);
10439: if ($operand eq '&') {
10440: $result=$result>$new?$new:$result;
10441: } else {
10442: $result=$result>$new?$result:$new;
10443: }
10444: }
10445: }
1.26 www 10446: }
10447: return $result;
1.421 albertel 10448: }
10449:
10450: # ---------------------------------------------------- Devalidate courseresdata
10451:
10452: sub devalidatecourseresdata {
10453: my ($coursenum,$coursedomain)=@_;
10454: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10455: &devalidate_cache_new('courseres',$hashid);
1.28 www 10456: }
10457:
1.763 www 10458:
1.200 www 10459: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10460: #
10461: # Parameters:
10462: # $coursenum - Number of the course.
10463: # $coursedomain - Domain at which the course was created.
10464: # Returns:
10465: # A hash of the course parameters along (I think) with timestamps
10466: # and version info.
1.877 foxr 10467:
1.624 albertel 10468: sub get_courseresdata {
10469: my ($coursenum,$coursedomain)=@_;
1.200 www 10470: my $coursehom=&homeserver($coursenum,$coursedomain);
10471: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10472: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10473: my %dumpreply;
1.417 albertel 10474: unless (defined($cached)) {
1.624 albertel 10475: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10476: $result=\%dumpreply;
1.251 albertel 10477: my ($tmp) = keys(%dumpreply);
10478: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10479: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10480: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10481: return $tmp;
1.416 albertel 10482: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10483: $result=undef;
1.599 albertel 10484: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10485: }
10486: }
1.624 albertel 10487: return $result;
10488: }
10489:
1.633 albertel 10490: sub devalidateuserresdata {
10491: my ($uname,$udom)=@_;
10492: my $hashid="$udom:$uname";
10493: &devalidate_cache_new('userres',$hashid);
10494: }
10495:
1.624 albertel 10496: sub get_userresdata {
10497: my ($uname,$udom)=@_;
10498: #most student don\'t have any data set, check if there is some data
10499: if (&EXT_cache_status($udom,$uname)) { return undef; }
10500:
10501: my $hashid="$udom:$uname";
10502: my ($result,$cached)=&is_cached_new('userres',$hashid);
10503: if (!defined($cached)) {
10504: my %resourcedata=&dump('resourcedata',$udom,$uname);
10505: $result=\%resourcedata;
10506: &do_cache_new('userres',$hashid,$result,600);
10507: }
10508: my ($tmp)=keys(%$result);
10509: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10510: return $result;
10511: }
10512: #error 2 occurs when the .db doesn't exist
10513: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10514: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10515: &logthis("<font color=\"blue\">WARNING:".
10516: " Trying to get resource data for ".
10517: $uname." at ".$udom.": ".
10518: $tmp."</font>");
10519: }
1.624 albertel 10520: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10521: #&EXT_cache_set($udom,$uname);
10522: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10523: undef($tmp); # not really an error so don't send it back
1.624 albertel 10524: }
10525: return $tmp;
10526: }
1.879 foxr 10527: #----------------------------------------------- resdata - return resource data
10528: # Purpose:
10529: # Return resource data for either users or for a course.
10530: # Parameters:
10531: # $name - Course/user name.
10532: # $domain - Name of the domain the user/course is registered on.
1.1172.2.93.4 1(raebur 10533:7): # $type - Type of thing $name is (must be 'course' or 'user')
1.879 foxr 10534: # @which - Array of names of resources desired.
10535: # Returns:
10536: # The value of the first reasource in @which that is found in the
10537: # resource hash.
10538: # Exceptional Conditions:
10539: # If the $type passed in is not valid (not the string 'course' or
10540: # 'user', an undefined reference is returned.
10541: # If none of the resources are found, an undef is returned
1.624 albertel 10542: sub resdata {
10543: my ($name,$domain,$type,@which)=@_;
10544: my $result;
10545: if ($type eq 'course') {
10546: $result=&get_courseresdata($name,$domain);
10547: } elsif ($type eq 'user') {
10548: $result=&get_userresdata($name,$domain);
10549: }
10550: if (!ref($result)) { return $result; }
1.251 albertel 10551: foreach my $item (@which) {
1.1172.2.93.4 1(raebur 10552:7): if (ref($item) eq 'ARRAY') {
10553:7): if (defined($result->{$item->[0]})) {
10554:7): return [$result->{$item->[0]},$item->[1]];
10555:7): }
10556:7): }
1.250 albertel 10557: }
1.291 albertel 10558: return undef;
1.200 www 10559: }
10560:
1.1172.2.93.4 2(raebur 10561:7): sub get_domain_ltitools {
10562:7): my ($cdom) = @_;
10563:7): my %ltitools;
10564:7): my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10565:7): if (defined($cached)) {
10566:7): if (ref($result) eq 'HASH') {
10567:7): %ltitools = %{$result};
10568:7): }
10569:7): } else {
10570:7): my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10571:7): if (ref($domconfig{'ltitools'}) eq 'HASH') {
10572:7): %ltitools = %{$domconfig{'ltitools'}};
10573:7): my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
10574:7): if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
10575:7): foreach my $id (keys(%ltitools)) {
10576:7): if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
10577:7): foreach my $item ('key','secret') {
10578:7): $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
10579:7): }
10580:7): }
10581:7): }
10582:7): }
10583:7): }
10584:7): my $cachetime = 24*60*60;
10585:7): &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10586:7): }
10587:7): return %ltitools;
10588:7): }
10589:7):
1.1172.2.31 raeburn 10590: sub get_numsuppfiles {
10591: my ($cnum,$cdom,$ignorecache)=@_;
10592: my $hashid=$cnum.':'.$cdom;
10593: my ($suppcount,$cached);
10594: unless ($ignorecache) {
10595: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10596: }
10597: unless (defined($cached)) {
10598: my $chome=&homeserver($cnum,$cdom);
10599: unless ($chome eq 'no_host') {
10600: ($suppcount,my $errors) = (0,0);
10601: my $suppmap = 'supplemental.sequence';
10602: ($suppcount,$errors) =
10603: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10604: }
10605: &do_cache_new('suppcount',$hashid,$suppcount,600);
10606: }
10607: return $suppcount;
10608: }
10609:
1.379 matthew 10610: #
10611: # EXT resource caching routines
10612: #
10613:
10614: sub clear_EXT_cache_status {
1.383 albertel 10615: &delenv('cache.EXT.');
1.379 matthew 10616: }
10617:
10618: sub EXT_cache_status {
10619: my ($target_domain,$target_user) = @_;
1.383 albertel 10620: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10621: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10622: # We know already the user has no data
10623: return 1;
10624: } else {
10625: return 0;
10626: }
10627: }
10628:
10629: sub EXT_cache_set {
10630: my ($target_domain,$target_user) = @_;
1.383 albertel 10631: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10632: #&appenv({$cachename => time});
1.379 matthew 10633: }
10634:
1.28 www 10635: # --------------------------------------------------------- Value of a Variable
1.58 www 10636: sub EXT {
1.715 albertel 10637:
1.1172.2.28 raeburn 10638: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10639: unless ($varname) { return ''; }
1.218 albertel 10640: #get real user name/domain, courseid and symb
10641: my $courseid;
1.359 albertel 10642: my $publicuser;
1.427 www 10643: if ($symbparm) {
10644: $symbparm=&get_symb_from_alias($symbparm);
10645: }
1.218 albertel 10646: if (!($uname && $udom)) {
1.790 albertel 10647: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10648: if (!$symbparm) { $symbparm=$cursymb; }
10649: } else {
1.620 albertel 10650: $courseid=$env{'request.course.id'};
1.218 albertel 10651: }
1.48 www 10652: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10653: my $rest;
1.320 albertel 10654: if (defined($therest[0])) {
1.48 www 10655: $rest=join('.',@therest);
10656: } else {
10657: $rest='';
10658: }
1.320 albertel 10659:
1.57 www 10660: my $qualifierrest=$qualifier;
10661: if ($rest) { $qualifierrest.='.'.$rest; }
10662: my $spacequalifierrest=$space;
10663: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10664: if ($realm eq 'user') {
1.48 www 10665: # --------------------------------------------------------------- user.resource
10666: if ($space eq 'resource') {
1.651 albertel 10667: if ( (defined($Apache::lonhomework::parsing_a_problem)
10668: || defined($Apache::lonhomework::parsing_a_task))
10669: &&
1.744 albertel 10670: ($symbparm eq &symbread()) ) {
10671: # if we are in the middle of processing the resource the
10672: # get the value we are planning on committing
10673: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10674: return $Apache::lonhomework::results{$qualifierrest};
10675: } else {
10676: return $Apache::lonhomework::history{$qualifierrest};
10677: }
1.335 albertel 10678: } else {
1.359 albertel 10679: my %restored;
1.620 albertel 10680: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10681: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10682: } else {
10683: %restored=&restore($symbparm,$courseid,$udom,$uname);
10684: }
1.335 albertel 10685: return $restored{$qualifierrest};
10686: }
1.48 www 10687: # ----------------------------------------------------------------- user.access
10688: } elsif ($space eq 'access') {
1.218 albertel 10689: # FIXME - not supporting calls for a specific user
1.48 www 10690: return &allowed($qualifier,$rest);
10691: # ------------------------------------------ user.preferences, user.environment
10692: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10693: if (($uname eq $env{'user.name'}) &&
10694: ($udom eq $env{'user.domain'})) {
10695: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10696: } else {
1.359 albertel 10697: my %returnhash;
10698: if (!$publicuser) {
10699: %returnhash=&userenvironment($udom,$uname,
10700: $qualifierrest);
10701: }
1.218 albertel 10702: return $returnhash{$qualifierrest};
10703: }
1.48 www 10704: # ----------------------------------------------------------------- user.course
10705: } elsif ($space eq 'course') {
1.218 albertel 10706: # FIXME - not supporting calls for a specific user
1.620 albertel 10707: return $env{join('.',('request.course',$qualifier))};
1.48 www 10708: # ------------------------------------------------------------------- user.role
10709: } elsif ($space eq 'role') {
1.218 albertel 10710: # FIXME - not supporting calls for a specific user
1.620 albertel 10711: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10712: if ($qualifier eq 'value') {
10713: return $role;
10714: } elsif ($qualifier eq 'extent') {
10715: return $where;
10716: }
10717: # ----------------------------------------------------------------- user.domain
10718: } elsif ($space eq 'domain') {
1.218 albertel 10719: return $udom;
1.48 www 10720: # ------------------------------------------------------------------- user.name
10721: } elsif ($space eq 'name') {
1.218 albertel 10722: return $uname;
1.48 www 10723: # ---------------------------------------------------- Any other user namespace
1.29 www 10724: } else {
1.359 albertel 10725: my %reply;
10726: if (!$publicuser) {
10727: %reply=&get($space,[$qualifierrest],$udom,$uname);
10728: }
10729: return $reply{$qualifierrest};
1.48 www 10730: }
1.236 www 10731: } elsif ($realm eq 'query') {
10732: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10733: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10734: [$spacequalifierrest]);
1.620 albertel 10735: return $env{'form.'.$spacequalifierrest};
1.236 www 10736: } elsif ($realm eq 'request') {
1.48 www 10737: # ------------------------------------------------------------- request.browser
10738: if ($space eq 'browser') {
1.1145 bisitz 10739: return $env{'browser.'.$qualifier};
1.57 www 10740: # ------------------------------------------------------------ request.filename
10741: } else {
1.620 albertel 10742: return $env{'request.'.$spacequalifierrest};
1.29 www 10743: }
1.28 www 10744: } elsif ($realm eq 'course') {
1.48 www 10745: # ---------------------------------------------------------- course.description
1.620 albertel 10746: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10747: } elsif ($realm eq 'resource') {
1.165 www 10748:
1.620 albertel 10749: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10750: if (!$symbparm) { $symbparm=&symbread(); }
10751: }
1.693 albertel 10752:
1.1172.2.30 raeburn 10753: if ($qualifier eq '') {
10754: if ($space eq 'title') {
10755: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10756: return &gettitle($symbparm);
10757: }
1.693 albertel 10758:
1.1172.2.30 raeburn 10759: if ($space eq 'map') {
10760: my ($map) = &decode_symb($symbparm);
10761: return &symbread($map);
10762: }
10763: if ($space eq 'maptitle') {
10764: my ($map) = &decode_symb($symbparm);
10765: return &gettitle($map);
10766: }
10767: if ($space eq 'filename') {
10768: if ($symbparm) {
10769: return &clutter((&decode_symb($symbparm))[2]);
10770: }
10771: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10772: }
1.1172.2.30 raeburn 10773:
10774: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10775: if ($space eq 'visibleparts') {
10776: my $navmap = Apache::lonnavmaps::navmap->new();
10777: my $item;
10778: if (ref($navmap)) {
10779: my $res = $navmap->getBySymb($symbparm);
10780: my $parts = $res->parts();
10781: if (ref($parts) eq 'ARRAY') {
10782: $item = join(',',@{$parts});
10783: }
10784: undef($navmap);
10785: }
10786: return $item;
10787: }
10788: }
10789: }
1.693 albertel 10790:
10791: my ($section, $group, @groups);
1.593 albertel 10792: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10793: if (($courseid eq '') && ($cid)) {
10794: $courseid = $cid;
10795: }
10796: if (($symbparm && $courseid) &&
10797: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10798:
1.218 albertel 10799: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10800:
1.60 www 10801: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10802: my $symbp=$symbparm;
1.735 albertel 10803: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10804:
10805: my $symbparm=$symbp.'.'.$spacequalifierrest;
10806: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10807:
1.620 albertel 10808: if (($env{'user.name'} eq $uname) &&
10809: ($env{'user.domain'} eq $udom)) {
10810: $section=$env{'request.course.sec'};
1.733 raeburn 10811: @groups = split(/:/,$env{'request.course.groups'});
10812: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10813: } else {
1.539 albertel 10814: if (! defined($usection)) {
1.551 albertel 10815: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10816: } else {
10817: $section = $usection;
10818: }
1.733 raeburn 10819: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10820: }
10821:
10822: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10823: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10824: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10825:
1.593 albertel 10826: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10827: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10828: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10829:
1.60 www 10830: # ----------------------------------------------------------- first, check user
1.624 albertel 10831:
10832: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10833: ([$courselevelr,'resource'],
10834: [$courselevelm,'map' ],
10835: [$courselevel, 'course' ]));
1.931 albertel 10836: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10837:
1.594 albertel 10838: # ------------------------------------------------ second, check some of course
1.684 raeburn 10839: my $coursereply;
1.691 raeburn 10840: if (@groups > 0) {
10841: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10842: $mapparm,$spacequalifierrest);
1.927 albertel 10843: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10844: }
1.96 www 10845:
1.684 raeburn 10846: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10847: $env{'course.'.$courseid.'.domain'},
10848: 'course',
10849: ([$seclevelr, 'resource'],
10850: [$seclevelm, 'map' ],
10851: [$seclevel, 'course' ],
10852: [$courselevelr,'resource']));
10853: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10854:
1.60 www 10855: # ------------------------------------------------------ third, check map parms
1.218 albertel 10856: my %parmhash=();
10857: my $thisparm='';
10858: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10859: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10860: &GDBM_READER(),0640)) {
1.218 albertel 10861: $thisparm=$parmhash{$symbparm};
10862: untie(%parmhash);
10863: }
1.927 albertel 10864: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10865: }
1.594 albertel 10866: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10867:
1.218 albertel 10868: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10869: my $filename;
10870: if (!$symbparm) { $symbparm=&symbread(); }
10871: if ($symbparm) {
1.409 www 10872: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10873: } else {
1.620 albertel 10874: $filename=$env{'request.filename'};
1.282 albertel 10875: }
10876: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10877: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10878: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10879: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10880:
1.927 albertel 10881: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10882: if ($symbparm && defined($courseid) &&
1.620 albertel 10883: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10884: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10885: $env{'course.'.$courseid.'.domain'},
10886: 'course',
1.927 albertel 10887: ([$courselevelm,'map' ],
10888: [$courselevel, 'course']));
10889: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10890: }
1.145 www 10891: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10892: unless ($space eq '0') {
1.336 albertel 10893: my @parts=split(/_/,$space);
10894: my $id=pop(@parts);
10895: my $part=join('_',@parts);
10896: if ($part eq '') { $part='0'; }
1.927 albertel 10897: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10898: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10899: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10900: }
1.395 albertel 10901: if ($recurse) { return undef; }
10902: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10903: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10904: # ---------------------------------------------------- Any other user namespace
10905: } elsif ($realm eq 'environment') {
10906: # ----------------------------------------------------------------- environment
1.620 albertel 10907: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10908: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10909: } else {
1.770 albertel 10910: if ($uname eq 'anonymous' && $udom eq '') {
10911: return '';
10912: }
1.219 albertel 10913: my %returnhash=&userenvironment($udom,$uname,
10914: $spacequalifierrest);
10915: return $returnhash{$spacequalifierrest};
10916: }
1.28 www 10917: } elsif ($realm eq 'system') {
1.48 www 10918: # ----------------------------------------------------------------- system.time
10919: if ($space eq 'time') {
10920: return time;
10921: }
1.696 albertel 10922: } elsif ($realm eq 'server') {
10923: # ----------------------------------------------------------------- system.time
10924: if ($space eq 'name') {
10925: return $ENV{'SERVER_NAME'};
10926: }
1.28 www 10927: }
1.48 www 10928: return '';
1.61 www 10929: }
10930:
1.927 albertel 10931: sub get_reply {
10932: my ($reply_value) = @_;
1.940 raeburn 10933: if (ref($reply_value) eq 'ARRAY') {
10934: if (wantarray) {
10935: return @$reply_value;
10936: }
10937: return $reply_value->[0];
10938: } else {
10939: return $reply_value;
1.927 albertel 10940: }
10941: }
10942:
1.691 raeburn 10943: sub check_group_parms {
10944: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10945: my @groupitems = ();
10946: my $resultitem;
1.927 albertel 10947: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10948: foreach my $group (@{$groups}) {
10949: foreach my $level (@levels) {
1.927 albertel 10950: my $item = $courseid.'.['.$group.'].'.$level->[0];
10951: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10952: }
10953: }
10954: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10955: $env{'course.'.$courseid.'.domain'},
10956: 'course',@groupitems);
10957: return $coursereply;
10958: }
10959:
10960: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10961: my ($courseid,@groups) = @_;
10962: @groups = sort(@groups);
1.691 raeburn 10963: return @groups;
10964: }
10965:
1.395 albertel 10966: sub packages_tab_default {
10967: my ($uri,$varname)=@_;
10968: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10969:
10970: my (@extension,@specifics,$do_default);
10971: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10972: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10973: if ($pack_type eq 'default') {
10974: $do_default=1;
10975: } elsif ($pack_type eq 'extension') {
10976: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10977: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10978: # only look at packages defaults for packages that this id is
1.738 albertel 10979: push(@specifics,[$package,$pack_type,$pack_part]);
10980: }
10981: }
10982: # first look for a package that matches the requested part id
10983: foreach my $package (@specifics) {
10984: my (undef,$pack_type,$pack_part)=@{$package};
10985: next if ($pack_part ne $part);
10986: if (defined($packagetab{"$pack_type&$name&default"})) {
10987: return $packagetab{"$pack_type&$name&default"};
10988: }
10989: }
10990: # look for any possible matching non extension_ package
10991: foreach my $package (@specifics) {
10992: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10993: if (defined($packagetab{"$pack_type&$name&default"})) {
10994: return $packagetab{"$pack_type&$name&default"};
10995: }
1.585 albertel 10996: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10997: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10998: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10999: }
11000: }
1.738 albertel 11001: # look for any posible extension_ match
11002: foreach my $package (@extension) {
11003: my ($package,$pack_type)=@{$package};
11004: if (defined($packagetab{"$pack_type&$name&default"})) {
11005: return $packagetab{"$pack_type&$name&default"};
11006: }
11007: if (defined($packagetab{$package."&$name&default"})) {
11008: return $packagetab{$package."&$name&default"};
11009: }
11010: }
11011: # look for a global default setting
11012: if ($do_default && defined($packagetab{"default&$name&default"})) {
11013: return $packagetab{"default&$name&default"};
11014: }
1.395 albertel 11015: return undef;
11016: }
11017:
1.334 albertel 11018: sub add_prefix_and_part {
11019: my ($prefix,$part)=@_;
11020: my $keyroot;
11021: if (defined($prefix) && $prefix !~ /^__/) {
11022: # prefix that has a part already
11023: $keyroot=$prefix;
11024: } elsif (defined($prefix)) {
11025: # prefix that is missing a part
11026: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11027: } else {
11028: # no prefix at all
11029: if (defined($part)) { $keyroot='_'.$part; }
11030: }
11031: return $keyroot;
11032: }
11033:
1.71 www 11034: # ---------------------------------------------------------------- Get metadata
11035:
1.599 albertel 11036: my %metaentry;
1.1070 www 11037: my %importedpartids;
1.71 www 11038: sub metadata {
1.176 www 11039: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11040: $uri=&declutter($uri);
1.288 albertel 11041: # if it is a non metadata possible uri return quickly
1.529 albertel 11042: if (($uri eq '') ||
11043: (($uri =~ m|^/*adm/|) &&
1.1172.2.93.4 2(raebur 11044:7): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11045: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11046: return undef;
11047: }
1.1172.2.49 raeburn 11048: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11049: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11050: return undef;
1.288 albertel 11051: }
1.73 www 11052: my $filename=$uri;
11053: $uri=~s/\.meta$//;
1.172 www 11054: #
11055: # Is the metadata already cached?
1.177 www 11056: # Look at timestamp of caching
1.172 www 11057: # Everything is cached by the main uri, libraries are never directly cached
11058: #
1.428 albertel 11059: if (!defined($liburi)) {
1.599 albertel 11060: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11061: if (defined($cached)) { return $result->{':'.$what}; }
11062: }
11063: {
1.1069 www 11064: # Imported parts would go here
1.1070 www 11065: my %importedids=();
11066: my @origfileimportpartids=();
1.1069 www 11067: my $importedparts=0;
1.172 www 11068: #
11069: # Is this a recursive call for a library?
11070: #
1.599 albertel 11071: # if (! exists($metacache{$uri})) {
11072: # $metacache{$uri}={};
11073: # }
1.924 albertel 11074: my $cachetime = 60*60;
1.171 www 11075: if ($liburi) {
11076: $liburi=&declutter($liburi);
11077: $filename=$liburi;
1.401 bowersj2 11078: } else {
1.599 albertel 11079: &devalidate_cache_new('meta',$uri);
11080: undef(%metaentry);
1.401 bowersj2 11081: }
1.140 www 11082: my %metathesekeys=();
1.73 www 11083: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11084: my $metastring;
1.1140 www 11085: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11086: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11087: $metastring =
1.929 albertel 11088: &Apache::lonnet::ssi_body($which,
1.924 albertel 11089: ('grade_target' => 'meta'));
11090: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11091: } elsif (($uri !~ m -^(editupload)/-) &&
11092: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11093: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11094: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11095: $metastring=&getfile($file);
1.489 albertel 11096: }
1.208 albertel 11097: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11098: my $token;
1.140 www 11099: undef %metathesekeys;
1.71 www 11100: while ($token=$parser->get_token) {
1.339 albertel 11101: if ($token->[0] eq 'S') {
11102: if (defined($token->[2]->{'package'})) {
1.172 www 11103: #
11104: # This is a package - get package info
11105: #
1.339 albertel 11106: my $package=$token->[2]->{'package'};
11107: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11108: if (defined($token->[2]->{'id'})) {
11109: $keyroot.='_'.$token->[2]->{'id'};
11110: }
1.599 albertel 11111: if ($metaentry{':packages'}) {
11112: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11113: } else {
1.599 albertel 11114: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11115: }
1.736 albertel 11116: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11117: my $part=$keyroot;
11118: $part=~s/^\_//;
1.736 albertel 11119: if ($pack_entry=~/^\Q$package\E\&/ ||
11120: $pack_entry=~/^\Q$package\E_0\&/) {
11121: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11122: # ignore package.tab specified default values
11123: # here &package_tab_default() will fetch those
11124: if ($subp eq 'default') { next; }
1.736 albertel 11125: my $value=$packagetab{$pack_entry};
1.432 albertel 11126: my $unikey;
11127: if ($pack =~ /_0$/) {
11128: $unikey='parameter_0_'.$name;
11129: $part=0;
11130: } else {
11131: $unikey='parameter'.$keyroot.'_'.$name;
11132: }
1.339 albertel 11133: if ($subp eq 'display') {
11134: $value.=' [Part: '.$part.']';
11135: }
1.599 albertel 11136: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11137: $metathesekeys{$unikey}=1;
1.599 albertel 11138: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11139: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11140: }
1.599 albertel 11141: if (defined($metaentry{':'.$unikey.'.default'})) {
11142: $metaentry{':'.$unikey}=
11143: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11144: }
1.339 albertel 11145: }
11146: }
11147: } else {
1.172 www 11148: #
11149: # This is not a package - some other kind of start tag
1.339 albertel 11150: #
11151: my $entry=$token->[1];
1.1068 www 11152: my $unikey='';
1.175 www 11153:
1.339 albertel 11154: if ($entry eq 'import') {
1.175 www 11155: #
11156: # Importing a library here
1.339 albertel 11157: #
1.1067 www 11158: my $location=$parser->get_text('/import');
11159: my $dir=$filename;
11160: $dir=~s|[^/]*$||;
11161: $location=&filelocation($dir,$location);
1.1069 www 11162:
1.1068 www 11163: my $importmode=$token->[2]->{'importmode'};
11164: if ($importmode eq 'problem') {
1.1069 www 11165: # Import as problem/response
1.1068 www 11166: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11167: } elsif ($importmode eq 'part') {
11168: # Import as part(s)
1.1069 www 11169: $importedparts=1;
11170: # We need to get the original file and the imported file to get the part order correct
11171: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11172: # Load and inspect original file
1.1070 www 11173: if ($#origfileimportpartids<0) {
11174: undef(%importedpartids);
11175: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11176: my $origfile=&getfile($origfilelocation);
11177: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11178: }
11179:
1.1069 www 11180: # Load and inspect imported file
11181: my $impfile=&getfile($location);
11182: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11183: if ($#impfilepartids>=0) {
11184: # This problem had parts
1.1070 www 11185: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11186: } else {
11187: # Importing by turning a single problem into a problem part
11188: # It gets the import-tags ID as part-ID
11189: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11190: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11191: }
1.1068 www 11192: } else {
11193: # Normal import
11194: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11195: if (defined($token->[2]->{'id'})) {
11196: $unikey.='_'.$token->[2]->{'id'};
11197: }
1.1067 www 11198: }
11199:
1.339 albertel 11200: if ($depthcount<20) {
1.736 albertel 11201: my $metadata =
11202: &metadata($uri,'keys', $location,$unikey,
11203: $depthcount+1);
11204: foreach my $meta (split(',',$metadata)) {
11205: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11206: $metathesekeys{$meta}=1;
1.339 albertel 11207: }
1.1068 www 11208:
11209: }
1.1067 www 11210: } else {
11211: #
11212: # Not importing, some other kind of non-package, non-library start tag
11213: #
11214: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11215: if (defined($token->[2]->{'id'})) {
11216: $unikey.='_'.$token->[2]->{'id'};
11217: }
1.339 albertel 11218: if (defined($token->[2]->{'name'})) {
11219: $unikey.='_'.$token->[2]->{'name'};
11220: }
11221: $metathesekeys{$unikey}=1;
1.736 albertel 11222: foreach my $param (@{$token->[3]}) {
11223: $metaentry{':'.$unikey.'.'.$param} =
11224: $token->[2]->{$param};
1.339 albertel 11225: }
11226: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11227: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11228: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11229: # only ws inside the tag, and not in default, so use default
11230: # as value
1.599 albertel 11231: $metaentry{':'.$unikey}=$default;
1.908 albertel 11232: } elsif ( $internaltext =~ /\S/ ) {
11233: # something interesting inside the tag
11234: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11235: } else {
1.908 albertel 11236: # no interesting values, don't set a default
1.339 albertel 11237: }
1.172 www 11238: # end of not-a-package not-a-library import
1.339 albertel 11239: }
1.172 www 11240: # end of not-a-package start tag
1.339 albertel 11241: }
1.172 www 11242: # the next is the end of "start tag"
1.339 albertel 11243: }
11244: }
1.483 albertel 11245: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11246: $extension = lc($extension);
11247: if ($extension eq 'htm') { $extension='html'; }
11248:
1.737 albertel 11249: foreach my $key (keys(%packagetab)) {
1.483 albertel 11250: #no specific packages #how's our extension
11251: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11252: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11253: \%metathesekeys);
11254: }
1.883 albertel 11255:
11256: if (!exists($metaentry{':packages'})
11257: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11258: foreach my $key (keys(%packagetab)) {
1.483 albertel 11259: #no specific packages well let's get default then
11260: if ($key!~/^default&/) { next; }
1.488 albertel 11261: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11262: \%metathesekeys);
11263: }
11264: }
1.338 www 11265: # are there custom rights to evaluate
1.599 albertel 11266: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11267:
1.338 www 11268: #
11269: # Importing a rights file here
1.339 albertel 11270: #
11271: unless ($depthcount) {
1.599 albertel 11272: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11273: my $dir=$filename;
11274: $dir=~s|[^/]*$||;
11275: $location=&filelocation($dir,$location);
1.736 albertel 11276: my $rights_metadata =
11277: &metadata($uri,'keys',$location,'_rights',
11278: $depthcount+1);
11279: foreach my $rights (split(',',$rights_metadata)) {
11280: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11281: $metathesekeys{$rights}=1;
1.339 albertel 11282: }
11283: }
11284: }
1.737 albertel 11285: # uniqifiy package listing
11286: my %seen;
11287: my @uniq_packages =
11288: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11289: $metaentry{':packages'} = join(',',@uniq_packages);
11290:
1.1070 www 11291: if ($importedparts) {
11292: # We had imported parts and need to rebuild partorder
11293: $metaentry{':partorder'}='';
11294: $metathesekeys{'partorder'}=1;
11295: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11296: if ($origfileimportpartids[$index] eq 'part') {
11297: # original part, part of the problem
11298: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11299: } else {
11300: # we have imported parts at this position
11301: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11302: }
11303: }
11304: $metaentry{':partorder'}=~s/^\,//;
11305: }
11306:
1.737 albertel 11307: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11308: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11309: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11310: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11311: # this is the end of "was not already recently cached
1.71 www 11312: }
1.599 albertel 11313: return $metaentry{':'.$what};
1.261 albertel 11314: }
11315:
1.488 albertel 11316: sub metadata_create_package_def {
1.483 albertel 11317: my ($uri,$key,$package,$metathesekeys)=@_;
11318: my ($pack,$name,$subp)=split(/\&/,$key);
11319: if ($subp eq 'default') { next; }
11320:
1.599 albertel 11321: if (defined($metaentry{':packages'})) {
11322: $metaentry{':packages'}.=','.$package;
1.483 albertel 11323: } else {
1.599 albertel 11324: $metaentry{':packages'}=$package;
1.483 albertel 11325: }
11326: my $value=$packagetab{$key};
11327: my $unikey;
11328: $unikey='parameter_0_'.$name;
1.599 albertel 11329: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11330: $$metathesekeys{$unikey}=1;
1.599 albertel 11331: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11332: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11333: }
1.599 albertel 11334: if (defined($metaentry{':'.$unikey.'.default'})) {
11335: $metaentry{':'.$unikey}=
11336: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11337: }
11338: }
11339:
1.261 albertel 11340: sub metadata_generate_part0 {
11341: my ($metadata,$metacache,$uri) = @_;
11342: my %allnames;
1.737 albertel 11343: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11344: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11345: my $part=$$metacache{':'.$metakey.'.part'};
11346: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11347: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11348: $allnames{$name}=$part;
11349: }
11350: }
11351: }
11352: foreach my $name (keys(%allnames)) {
11353: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11354: my $key=":parameter_0_$name";
1.261 albertel 11355: $$metacache{"$key.part"}='0';
11356: $$metacache{"$key.name"}=$name;
1.428 albertel 11357: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11358: $allnames{$name}.'_'.$name.
11359: '.type'};
1.428 albertel 11360: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11361: '.display'};
1.644 www 11362: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11363: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11364: $$metacache{"$key.display"}=$olddis;
11365: }
1.71 www 11366: }
11367:
1.764 albertel 11368: # ------------------------------------------------------ Devalidate title cache
11369:
11370: sub devalidate_title_cache {
11371: my ($url)=@_;
11372: if (!$env{'request.course.id'}) { return; }
11373: my $symb=&symbread($url);
11374: if (!$symb) { return; }
11375: my $key=$env{'request.course.id'}."\0".$symb;
11376: &devalidate_cache_new('title',$key);
11377: }
11378:
1.1014 droeschl 11379: # ------------------------------------------------- Get the title of a course
11380:
11381: sub current_course_title {
11382: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11383: }
1.301 www 11384: # ------------------------------------------------- Get the title of a resource
11385:
11386: sub gettitle {
11387: my $urlsymb=shift;
11388: my $symb=&symbread($urlsymb);
1.534 albertel 11389: if ($symb) {
1.620 albertel 11390: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11391: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11392: if (defined($cached)) {
11393: return $result;
11394: }
1.534 albertel 11395: my ($map,$resid,$url)=&decode_symb($symb);
11396: my $title='';
1.907 albertel 11397: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11398: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11399: } else {
11400: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11401: &GDBM_READER(),0640)) {
11402: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11403: $title=$bighash{'title_'.$mapid.'.'.$resid};
11404: untie(%bighash);
11405: }
1.534 albertel 11406: }
11407: $title=~s/\&colon\;/\:/gs;
11408: if ($title) {
1.1159 www 11409: # Remember both $symb and $title for dynamic metadata
11410: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11411: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11412: # Cache this title and then return it
1.599 albertel 11413: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11414: }
11415: $urlsymb=$url;
11416: }
11417: my $title=&metadata($urlsymb,'title');
11418: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11419: return $title;
1.301 www 11420: }
1.613 albertel 11421:
1.614 albertel 11422: sub get_slot {
11423: my ($which,$cnum,$cdom)=@_;
11424: if (!$cnum || !$cdom) {
1.790 albertel 11425: (undef,my $courseid)=&whichuser();
1.620 albertel 11426: $cdom=$env{'course.'.$courseid.'.domain'};
11427: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11428: }
1.703 albertel 11429: my $key=join("\0",'slots',$cdom,$cnum,$which);
11430: my %slotinfo;
11431: if (exists($remembered{$key})) {
11432: $slotinfo{$which} = $remembered{$key};
11433: } else {
11434: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11435: &Apache::lonhomework::showhash(%slotinfo);
11436: my ($tmp)=keys(%slotinfo);
11437: if ($tmp=~/^error:/) { return (); }
11438: $remembered{$key} = $slotinfo{$which};
11439: }
1.616 albertel 11440: if (ref($slotinfo{$which}) eq 'HASH') {
11441: return %{$slotinfo{$which}};
11442: }
11443: return $slotinfo{$which};
1.614 albertel 11444: }
1.1150 raeburn 11445:
11446: sub get_reservable_slots {
11447: my ($cnum,$cdom,$uname,$udom) = @_;
11448: my $now = time;
11449: my $reservable_info;
11450: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11451: if (exists($remembered{$key})) {
11452: $reservable_info = $remembered{$key};
11453: } else {
11454: my %resv;
11455: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11456: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11457: $reservable_info = \%resv;
11458: $remembered{$key} = $reservable_info;
11459: }
11460: return $reservable_info;
11461: }
11462:
11463: sub get_course_slots {
11464: my ($cnum,$cdom) = @_;
11465: my $hashid=$cnum.':'.$cdom;
11466: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11467: if (defined($cached)) {
11468: if (ref($result) eq 'HASH') {
11469: return %{$result};
11470: }
11471: } else {
11472: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11473: my ($tmp) = keys(%slots);
11474: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11475: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11476: return %slots;
11477: }
11478: }
11479: return;
11480: }
11481:
11482: sub devalidate_slots_cache {
11483: my ($cnum,$cdom)=@_;
11484: my $hashid=$cnum.':'.$cdom;
11485: &devalidate_cache_new('allslots',$hashid);
11486: }
11487:
1.1172.2.8 raeburn 11488: sub get_coursechange {
11489: my ($cdom,$cnum) = @_;
11490: if ($cdom eq '' || $cnum eq '') {
11491: return unless ($env{'request.course.id'});
11492: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11493: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11494: }
11495: my $hashid=$cdom.'_'.$cnum;
11496: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11497: if ((defined($cached)) && ($change ne '')) {
11498: return $change;
11499: } else {
11500: my %crshash;
11501: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11502: if ($crshash{'internal.contentchange'} eq '') {
11503: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11504: if ($change eq '') {
11505: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11506: $change = $crshash{'internal.created'};
11507: }
11508: } else {
11509: $change = $crshash{'internal.contentchange'};
11510: }
11511: my $cachetime = 600;
11512: &do_cache_new('crschange',$hashid,$change,$cachetime);
11513: }
11514: return $change;
11515: }
11516:
11517: sub devalidate_coursechange_cache {
11518: my ($cnum,$cdom)=@_;
11519: my $hashid=$cnum.':'.$cdom;
11520: &devalidate_cache_new('crschange',$hashid);
11521: }
11522:
1.31 www 11523: # ------------------------------------------------- Update symbolic store links
11524:
11525: sub symblist {
11526: my ($mapname,%newhash)=@_;
1.438 www 11527: $mapname=&deversion(&declutter($mapname));
1.31 www 11528: my %hash;
1.620 albertel 11529: if (($env{'request.course.fn'}) && (%newhash)) {
11530: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11531: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11532: foreach my $url (keys(%newhash)) {
1.711 albertel 11533: next if ($url eq 'last_known'
11534: && $env{'form.no_update_last_known'});
11535: $hash{declutter($url)}=&encode_symb($mapname,
11536: $newhash{$url}->[1],
11537: $newhash{$url}->[0]);
1.191 harris41 11538: }
1.31 www 11539: if (untie(%hash)) {
11540: return 'ok';
11541: }
11542: }
11543: }
11544: return 'error';
1.212 www 11545: }
11546:
11547: # --------------------------------------------------------------- Verify a symb
11548:
11549: sub symbverify {
1.1172.2.11 raeburn 11550: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11551: my $thisfn=$thisurl;
1.439 www 11552: $thisfn=&declutter($thisfn);
1.215 www 11553: # direct jump to resource in page or to a sequence - will construct own symbs
11554: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11555: # check URL part
1.409 www 11556: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11557:
1.431 www 11558: unless ($url eq $thisfn) { return 0; }
1.213 www 11559:
1.216 www 11560: $symb=&symbclean($symb);
1.510 www 11561: $thisurl=&deversion($thisurl);
1.439 www 11562: $thisfn=&deversion($thisfn);
1.213 www 11563:
11564: my %bighash;
11565: my $okay=0;
1.431 www 11566:
1.620 albertel 11567: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11568: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11569: my $noclutter;
1.1032 raeburn 11570: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11571: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11572: if ($map =~ m{^uploaded/.+\.page$}) {
11573: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11574: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11575: $noclutter = 1;
11576: }
11577: }
11578: my $ids;
11579: if ($noclutter) {
11580: $ids=$bighash{'ids_'.$thisurl};
11581: } else {
11582: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11583: }
1.1102 raeburn 11584: unless ($ids) {
1.1172.2.13 raeburn 11585: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11586: $ids=$bighash{$idkey};
1.216 www 11587: }
11588: if ($ids) {
11589: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11590: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11591: $symb =~ s/\?.+$//;
11592: }
1.800 albertel 11593: foreach my $id (split(/\,/,$ids)) {
11594: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11595: if (
11596: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11597: eq $symb) {
1.1172.2.11 raeburn 11598: if (ref($encstate)) {
11599: $$encstate = $bighash{'encrypted_'.$id};
11600: }
1.1172.2.13 raeburn 11601: if (($env{'request.role.adv'}) ||
11602: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11603: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11604: $okay=1;
11605: last;
11606: }
11607: }
11608: }
1.216 www 11609: }
1.213 www 11610: untie(%bighash);
11611: }
11612: return $okay;
1.31 www 11613: }
11614:
1.210 www 11615: # --------------------------------------------------------------- Clean-up symb
11616:
11617: sub symbclean {
11618: my $symb=shift;
1.568 albertel 11619: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11620: # remove version from map
11621: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11622:
1.210 www 11623: # remove version from URL
11624: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11625:
1.507 www 11626: # remove wrapper
11627:
1.510 www 11628: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11629: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11630: return $symb;
1.409 www 11631: }
11632:
11633: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11634:
11635: sub encode_symb {
11636: my ($map,$resid,$url)=@_;
11637: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11638: }
1.409 www 11639:
11640: sub decode_symb {
1.568 albertel 11641: my $symb=shift;
11642: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11643: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11644: return (&fixversion($map),$resid,&fixversion($url));
11645: }
11646:
11647: sub fixversion {
11648: my $fn=shift;
1.609 banghart 11649: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11650: my %bighash;
11651: my $uri=&clutter($fn);
1.620 albertel 11652: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11653: # is this cached?
1.599 albertel 11654: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11655: if (defined($cached)) { return $result; }
11656: # unfortunately not cached, or expired
1.620 albertel 11657: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11658: &GDBM_READER(),0640)) {
11659: if ($bighash{'version_'.$uri}) {
11660: my $version=$bighash{'version_'.$uri};
1.444 www 11661: unless (($version eq 'mostrecent') ||
11662: ($version==&getversion($uri))) {
1.440 www 11663: $uri=~s/\.(\w+)$/\.$version\.$1/;
11664: }
11665: }
11666: untie %bighash;
1.413 www 11667: }
1.599 albertel 11668: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11669: }
11670:
11671: sub deversion {
11672: my $url=shift;
11673: $url=~s/\.\d+\.(\w+)$/\.$1/;
11674: return $url;
1.210 www 11675: }
11676:
1.31 www 11677: # ------------------------------------------------------ Return symb list entry
11678:
11679: sub symbread {
1.1172.2.66 raeburn 11680: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11681: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11682: if (defined($env{$cache_str})) {
11683: if ($ignorecachednull) {
11684: return $env{$cache_str} unless ($env{$cache_str} eq '');
11685: } else {
11686: return $env{$cache_str};
11687: }
11688: }
1.242 www 11689: # no filename provided? try from environment
1.1172.2.54 raeburn 11690: unless ($thisfn) {
1.620 albertel 11691: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11692: return $env{$cache_str}=&symbclean($env{'request.symb'});
11693: }
11694: $thisfn=$env{'request.filename'};
1.44 www 11695: }
1.569 albertel 11696: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11697: # is that filename actually a symb? Verify, clean, and return
11698: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11699: if (&symbverify($thisfn,$1)) {
1.620 albertel 11700: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11701: }
1.242 www 11702: }
1.44 www 11703: $thisfn=declutter($thisfn);
1.31 www 11704: my %hash;
1.37 www 11705: my %bighash;
11706: my $syval='';
1.620 albertel 11707: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11708: my $targetfn = $thisfn;
1.609 banghart 11709: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11710: $targetfn = 'adm/wrapper/'.$thisfn;
11711: }
1.687 albertel 11712: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11713: $targetfn=$1;
11714: }
1.620 albertel 11715: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11716: &GDBM_READER(),0640)) {
1.481 raeburn 11717: $syval=$hash{$targetfn};
1.37 www 11718: untie(%hash);
11719: }
11720: # ---------------------------------------------------------- There was an entry
11721: if ($syval) {
1.601 albertel 11722: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11723: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11724: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11725: #return $env{$cache_str}='';
1.601 albertel 11726: #}
11727: #$syval.=$1;
11728: #}
1.37 www 11729: } else {
11730: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11731: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11732: &GDBM_READER(),0640)) {
1.37 www 11733: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11734: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11735: unless ($ids) {
11736: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11737: }
11738: unless ($ids) {
11739: # alias?
11740: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11741: }
1.37 www 11742: if ($ids) {
11743: # ------------------------------------------------------------------- Has ID(s)
11744: my @possibilities=split(/\,/,$ids);
1.39 www 11745: if ($#possibilities==0) {
11746: # ----------------------------------------------- There is only one possibility
1.37 www 11747: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11748: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11749: $resid,$thisfn);
1.1172.2.66 raeburn 11750: if (ref($possibles) eq 'HASH') {
11751: $possibles->{$syval} = 1;
11752: }
11753: if ($checkforblock) {
11754: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11755: if (@blockers) {
11756: $syval = '';
11757: return;
11758: }
11759: }
11760: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11761: # ------------------------------------------ There is more than one possibility
11762: my $realpossible=0;
1.800 albertel 11763: foreach my $id (@possibilities) {
11764: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11765: my $canaccess;
11766: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11767: $canaccess = 1;
11768: } else {
11769: $canaccess = &allowed('bre',$file);
11770: }
11771: if ($canaccess) {
11772: my ($mapid,$resid)=split(/\./,$id);
11773: if ($bighash{'map_type_'.$mapid} ne 'page') {
11774: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11775: $resid,$thisfn);
11776: if (ref($possibles) eq 'HASH') {
11777: $possibles->{$syval} = 1;
11778: }
11779: if ($checkforblock) {
11780: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11781: unless (@blockers > 0) {
11782: $syval = $poss_syval;
11783: $realpossible++;
11784: }
11785: } else {
11786: $syval = $poss_syval;
11787: $realpossible++;
11788: }
11789: }
1.39 www 11790: }
1.191 harris41 11791: }
1.39 www 11792: if ($realpossible!=1) { $syval=''; }
1.249 www 11793: } else {
11794: $syval='';
1.37 www 11795: }
11796: }
1.1172.2.66 raeburn 11797: untie(%bighash);
1.481 raeburn 11798: }
1.31 www 11799: }
1.62 www 11800: if ($syval) {
1.620 albertel 11801: return $env{$cache_str}=$syval;
1.62 www 11802: }
1.31 www 11803: }
1.949 raeburn 11804: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11805: return $env{$cache_str}='';
1.31 www 11806: }
11807:
11808: # ---------------------------------------------------------- Return random seed
11809:
1.32 www 11810: sub numval {
11811: my $txt=shift;
11812: $txt=~tr/A-J/0-9/;
11813: $txt=~tr/a-j/0-9/;
11814: $txt=~tr/K-T/0-9/;
11815: $txt=~tr/k-t/0-9/;
11816: $txt=~tr/U-Z/0-5/;
11817: $txt=~tr/u-z/0-5/;
11818: $txt=~s/\D//g;
1.564 albertel 11819: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11820: return int($txt);
1.368 albertel 11821: }
11822:
1.484 albertel 11823: sub numval2 {
11824: my $txt=shift;
11825: $txt=~tr/A-J/0-9/;
11826: $txt=~tr/a-j/0-9/;
11827: $txt=~tr/K-T/0-9/;
11828: $txt=~tr/k-t/0-9/;
11829: $txt=~tr/U-Z/0-5/;
11830: $txt=~tr/u-z/0-5/;
11831: $txt=~s/\D//g;
11832: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11833: my $total;
11834: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11835: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11836: return int($total);
11837: }
11838:
1.575 albertel 11839: sub numval3 {
11840: use integer;
11841: my $txt=shift;
11842: $txt=~tr/A-J/0-9/;
11843: $txt=~tr/a-j/0-9/;
11844: $txt=~tr/K-T/0-9/;
11845: $txt=~tr/k-t/0-9/;
11846: $txt=~tr/U-Z/0-5/;
11847: $txt=~tr/u-z/0-5/;
11848: $txt=~s/\D//g;
11849: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11850: my $total;
11851: foreach my $val (@txts) { $total+=$val; }
11852: if ($_64bit) { $total=(($total<<32)>>32); }
11853: return $total;
11854: }
11855:
1.675 albertel 11856: sub digest {
11857: my ($data)=@_;
11858: my $digest=&Digest::MD5::md5($data);
11859: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11860: my ($e,$f);
11861: {
11862: use integer;
11863: $e=($a+$b);
11864: $f=($c+$d);
11865: if ($_64bit) {
11866: $e=(($e<<32)>>32);
11867: $f=(($f<<32)>>32);
11868: }
11869: }
11870: if (wantarray) {
11871: return ($e,$f);
11872: } else {
11873: my $g;
11874: {
11875: use integer;
11876: $g=($e+$f);
11877: if ($_64bit) {
11878: $g=(($g<<32)>>32);
11879: }
11880: }
11881: return $g;
11882: }
11883: }
11884:
1.368 albertel 11885: sub latest_rnd_algorithm_id {
1.675 albertel 11886: return '64bit5';
1.366 albertel 11887: }
1.32 www 11888:
1.503 albertel 11889: sub get_rand_alg {
11890: my ($courseid)=@_;
1.790 albertel 11891: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11892: if ($courseid) {
1.620 albertel 11893: return $env{"course.$courseid.rndseed"};
1.503 albertel 11894: }
11895: return &latest_rnd_algorithm_id();
11896: }
11897:
1.562 albertel 11898: sub validCODE {
11899: my ($CODE)=@_;
11900: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11901: return 0;
11902: }
11903:
1.491 albertel 11904: sub getCODE {
1.620 albertel 11905: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11906: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11907: defined($Apache::lonhomework::parsing_a_task) ) &&
11908: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11909: return $Apache::lonhomework::history{'resource.CODE'};
11910: }
11911: return undef;
11912: }
1.1133 foxr 11913: #
11914: # Determines the random seed for a specific context:
11915: #
11916: # parameters:
11917: # symb - in course context the symb for the seed.
11918: # course_id - The course id of the form domain_coursenum.
11919: # domain - Domain for the user.
11920: # course - Course for the user.
11921: # cenv - environment of the course.
11922: #
11923: # NOTE:
11924: # All parameters are picked out of the environment if missing
11925: # or not defined.
11926: # If a symb cannot be determined the current time is used instead.
11927: #
11928: # For a given well defined symb, courside, domain, username,
11929: # and course environment, the seed is reproducible.
11930: #
1.31 www 11931: sub rndseed {
1.1133 foxr 11932: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11933: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11934: if (!defined($symb)) {
1.366 albertel 11935: unless ($symb=$wsymb) { return time; }
11936: }
1.1146 foxr 11937: if (!defined $courseid) {
11938: $courseid=$wcourseid;
11939: }
11940: if (!defined $domain) { $domain=$wdomain; }
11941: if (!defined $username) { $username=$wusername }
1.1133 foxr 11942:
11943: my $which;
11944: if (defined($cenv->{'rndseed'})) {
11945: $which = $cenv->{'rndseed'};
11946: } else {
11947: $which =&get_rand_alg($courseid);
11948: }
1.491 albertel 11949: if (defined(&getCODE())) {
1.675 albertel 11950: if ($which eq '64bit5') {
11951: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11952: } elsif ($which eq '64bit4') {
1.575 albertel 11953: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11954: } else {
11955: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11956: }
1.675 albertel 11957: } elsif ($which eq '64bit5') {
11958: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11959: } elsif ($which eq '64bit4') {
11960: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11961: } elsif ($which eq '64bit3') {
11962: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11963: } elsif ($which eq '64bit2') {
11964: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11965: } elsif ($which eq '64bit') {
11966: return &rndseed_64bit($symb,$courseid,$domain,$username);
11967: }
11968: return &rndseed_32bit($symb,$courseid,$domain,$username);
11969: }
11970:
11971: sub rndseed_32bit {
11972: my ($symb,$courseid,$domain,$username)=@_;
11973: {
11974: use integer;
11975: my $symbchck=unpack("%32C*",$symb) << 27;
11976: my $symbseed=numval($symb) << 22;
11977: my $namechck=unpack("%32C*",$username) << 17;
11978: my $nameseed=numval($username) << 12;
11979: my $domainseed=unpack("%32C*",$domain) << 7;
11980: my $courseseed=unpack("%32C*",$courseid);
11981: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11982: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11983: #&logthis("rndseed :$num:$symb");
1.564 albertel 11984: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11985: return $num;
11986: }
11987: }
11988:
11989: sub rndseed_64bit {
11990: my ($symb,$courseid,$domain,$username)=@_;
11991: {
11992: use integer;
11993: my $symbchck=unpack("%32S*",$symb) << 21;
11994: my $symbseed=numval($symb) << 10;
11995: my $namechck=unpack("%32S*",$username);
11996:
11997: my $nameseed=numval($username) << 21;
11998: my $domainseed=unpack("%32S*",$domain) << 10;
11999: my $courseseed=unpack("%32S*",$courseid);
12000:
12001: my $num1=$symbchck+$symbseed+$namechck;
12002: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12003: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12004: #&logthis("rndseed :$num:$symb");
1.564 albertel 12005: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12006: return "$num1,$num2";
1.155 albertel 12007: }
1.366 albertel 12008: }
12009:
1.443 albertel 12010: sub rndseed_64bit2 {
12011: my ($symb,$courseid,$domain,$username)=@_;
12012: {
12013: use integer;
12014: # strings need to be an even # of cahracters long, it it is odd the
12015: # last characters gets thrown away
12016: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12017: my $symbseed=numval($symb) << 10;
12018: my $namechck=unpack("%32S*",$username.' ');
12019:
12020: my $nameseed=numval($username) << 21;
1.501 albertel 12021: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12022: my $courseseed=unpack("%32S*",$courseid.' ');
12023:
12024: my $num1=$symbchck+$symbseed+$namechck;
12025: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12026: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12027: #&logthis("rndseed :$num:$symb");
1.803 albertel 12028: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12029: return "$num1,$num2";
12030: }
12031: }
12032:
12033: sub rndseed_64bit3 {
12034: my ($symb,$courseid,$domain,$username)=@_;
12035: {
12036: use integer;
12037: # strings need to be an even # of cahracters long, it it is odd the
12038: # last characters gets thrown away
12039: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12040: my $symbseed=numval2($symb) << 10;
12041: my $namechck=unpack("%32S*",$username.' ');
12042:
12043: my $nameseed=numval2($username) << 21;
1.443 albertel 12044: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12045: my $courseseed=unpack("%32S*",$courseid.' ');
12046:
12047: my $num1=$symbchck+$symbseed+$namechck;
12048: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12049: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12050: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12051: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12052:
1.503 albertel 12053: return "$num1:$num2";
1.443 albertel 12054: }
12055: }
12056:
1.575 albertel 12057: sub rndseed_64bit4 {
12058: my ($symb,$courseid,$domain,$username)=@_;
12059: {
12060: use integer;
12061: # strings need to be an even # of cahracters long, it it is odd the
12062: # last characters gets thrown away
12063: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12064: my $symbseed=numval3($symb) << 10;
12065: my $namechck=unpack("%32S*",$username.' ');
12066:
12067: my $nameseed=numval3($username) << 21;
12068: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12069: my $courseseed=unpack("%32S*",$courseid.' ');
12070:
12071: my $num1=$symbchck+$symbseed+$namechck;
12072: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12073: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12074: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12075: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12076:
1.575 albertel 12077: return "$num1:$num2";
12078: }
12079: }
12080:
1.675 albertel 12081: sub rndseed_64bit5 {
12082: my ($symb,$courseid,$domain,$username)=@_;
12083: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12084: return "$num1:$num2";
12085: }
12086:
1.366 albertel 12087: sub rndseed_CODE_64bit {
12088: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12089: {
1.366 albertel 12090: use integer;
1.443 albertel 12091: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12092: my $symbseed=numval2($symb);
1.491 albertel 12093: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12094: my $CODEseed=numval(&getCODE());
1.443 albertel 12095: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12096: my $num1=$symbseed+$CODEchck;
12097: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12098: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12099: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12100: if ($_64bit) { $num1=(($num1<<32)>>32); }
12101: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12102: return "$num1:$num2";
1.366 albertel 12103: }
12104: }
12105:
1.575 albertel 12106: sub rndseed_CODE_64bit4 {
12107: my ($symb,$courseid,$domain,$username)=@_;
12108: {
12109: use integer;
12110: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12111: my $symbseed=numval3($symb);
12112: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12113: my $CODEseed=numval3(&getCODE());
12114: my $courseseed=unpack("%32S*",$courseid.' ');
12115: my $num1=$symbseed+$CODEchck;
12116: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12117: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12118: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12119: if ($_64bit) { $num1=(($num1<<32)>>32); }
12120: if ($_64bit) { $num2=(($num2<<32)>>32); }
12121: return "$num1:$num2";
12122: }
12123: }
12124:
1.675 albertel 12125: sub rndseed_CODE_64bit5 {
12126: my ($symb,$courseid,$domain,$username)=@_;
12127: my $code = &getCODE();
12128: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12129: return "$num1:$num2";
12130: }
12131:
1.366 albertel 12132: sub setup_random_from_rndseed {
12133: my ($rndseed)=@_;
1.503 albertel 12134: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12135: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12136: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12137: &Math::Random::random_set_seed_from_phrase($rndseed);
12138: } else {
12139: &Math::Random::random_set_seed($num1,$num2);
12140: }
1.366 albertel 12141: } else {
12142: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12143: }
1.36 albertel 12144: }
12145:
1.474 albertel 12146: sub latest_receipt_algorithm_id {
1.835 albertel 12147: return 'receipt3';
1.474 albertel 12148: }
12149:
1.480 www 12150: sub recunique {
12151: my $fucourseid=shift;
12152: my $unique;
1.835 albertel 12153: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12154: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12155: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12156: } else {
12157: $unique=$perlvar{'lonReceipt'};
12158: }
12159: return unpack("%32C*",$unique);
12160: }
12161:
12162: sub recprefix {
12163: my $fucourseid=shift;
12164: my $prefix;
1.835 albertel 12165: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12166: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12167: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12168: } else {
12169: $prefix=$perlvar{'lonHostID'};
12170: }
12171: return unpack("%32C*",$prefix);
12172: }
12173:
1.76 www 12174: sub ireceipt {
1.474 albertel 12175: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12176:
12177: my $return =&recprefix($fucourseid).'-';
12178:
12179: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12180: $env{'request.state'} eq 'construct') {
12181: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12182: return $return;
12183: }
12184:
1.76 www 12185: my $cuname=unpack("%32C*",$funame);
12186: my $cudom=unpack("%32C*",$fudom);
12187: my $cucourseid=unpack("%32C*",$fucourseid);
12188: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12189: my $cunique=&recunique($fucourseid);
1.474 albertel 12190: my $cpart=unpack("%32S*",$part);
1.835 albertel 12191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12192:
1.790 albertel 12193: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12194:
12195: $return.= ($cunique%$cuname+
12196: $cunique%$cudom+
12197: $cusymb%$cuname+
12198: $cusymb%$cudom+
12199: $cucourseid%$cuname+
12200: $cucourseid%$cudom+
12201: $cpart%$cuname+
12202: $cpart%$cudom);
12203: } else {
12204: $return.= ($cunique%$cuname+
12205: $cunique%$cudom+
12206: $cusymb%$cuname+
12207: $cusymb%$cudom+
12208: $cucourseid%$cuname+
12209: $cucourseid%$cudom);
12210: }
12211: return $return;
1.76 www 12212: }
12213:
12214: sub receipt {
1.474 albertel 12215: my ($part)=@_;
1.790 albertel 12216: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12217: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12218: }
1.260 ng 12219:
1.790 albertel 12220: sub whichuser {
12221: my ($passedsymb)=@_;
12222: my ($symb,$courseid,$domain,$name,$publicuser);
12223: if (defined($env{'form.grade_symb'})) {
12224: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12225: my $allowed=&allowed('vgr',$tmp_courseid);
12226: if (!$allowed &&
12227: exists($env{'request.course.sec'}) &&
12228: $env{'request.course.sec'} !~ /^\s*$/) {
12229: $allowed=&allowed('vgr',$tmp_courseid.
12230: '/'.$env{'request.course.sec'});
12231: }
12232: if ($allowed) {
12233: ($symb)=&get_env_multiple('form.grade_symb');
12234: $courseid=$tmp_courseid;
12235: ($domain)=&get_env_multiple('form.grade_domain');
12236: ($name)=&get_env_multiple('form.grade_username');
12237: return ($symb,$courseid,$domain,$name,$publicuser);
12238: }
12239: }
12240: if (!$passedsymb) {
12241: $symb=&symbread();
12242: } else {
12243: $symb=$passedsymb;
12244: }
12245: $courseid=$env{'request.course.id'};
12246: $domain=$env{'user.domain'};
12247: $name=$env{'user.name'};
12248: if ($name eq 'public' && $domain eq 'public') {
12249: if (!defined($env{'form.username'})) {
12250: $env{'form.username'}.=time.rand(10000000);
12251: }
12252: $name.=$env{'form.username'};
12253: }
12254: return ($symb,$courseid,$domain,$name,$publicuser);
12255:
12256: }
12257:
1.36 albertel 12258: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12259: # returns either the contents of the file or
12260: # -1 if the file doesn't exist
1.481 raeburn 12261: #
12262: # if the target is a file that was uploaded via DOCS,
12263: # a check will be made to see if a current copy exists on the local server,
12264: # if it does this will be served, otherwise a copy will be retrieved from
12265: # the home server for the course and stored in /home/httpd/html/userfiles on
12266: # the local server.
1.472 albertel 12267:
1.36 albertel 12268: sub getfile {
1.538 albertel 12269: my ($file) = @_;
1.609 banghart 12270: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12271: &repcopy($file);
12272: return &readfile($file);
12273: }
12274:
12275: sub repcopy_userfile {
12276: my ($file)=@_;
1.1142 raeburn 12277: my $londocroot = $perlvar{'lonDocRoot'};
12278: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12279: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12280: my ($cdom,$cnum,$filename) =
1.811 albertel 12281: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12282: my $uri="/uploaded/$cdom/$cnum/$filename";
12283: if (-e "$file") {
1.828 www 12284: # we already have a local copy, check it out
1.538 albertel 12285: my @fileinfo = stat($file);
1.828 www 12286: my $rtncode;
12287: my $info;
1.538 albertel 12288: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12289: if ($lwpresp ne 'ok') {
1.828 www 12290: # there is no such file anymore, even though we had a local copy
1.482 albertel 12291: if ($rtncode eq '404') {
1.538 albertel 12292: unlink($file);
1.482 albertel 12293: }
12294: return -1;
12295: }
12296: if ($info < $fileinfo[9]) {
1.828 www 12297: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12298: return 'ok';
1.828 www 12299: } else {
12300: # the file is outdated, get rid of it
12301: unlink($file);
1.482 albertel 12302: }
1.828 www 12303: }
12304: # one way or the other, at this point, we don't have the file
12305: # construct the correct path for the file
12306: my @parts = ($cdom,$cnum);
12307: if ($filename =~ m|^(.+)/[^/]+$|) {
12308: push @parts, split(/\//,$1);
12309: }
12310: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12311: foreach my $part (@parts) {
12312: $path .= '/'.$part;
12313: if (!-e $path) {
12314: mkdir($path,0770);
1.482 albertel 12315: }
12316: }
1.828 www 12317: # now the path exists for sure
12318: # get a user agent
12319: my $ua=new LWP::UserAgent;
12320: my $transferfile=$file.'.in.transfer';
12321: # FIXME: this should flock
12322: if (-e $transferfile) { return 'ok'; }
12323: my $request;
12324: $uri=~s/^\///;
1.980 raeburn 12325: my $homeserver = &homeserver($cnum,$cdom);
12326: my $protocol = $protocol{$homeserver};
12327: $protocol = 'http' if ($protocol ne 'https');
12328: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12329: my $response=$ua->request($request,$transferfile);
12330: # did it work?
12331: if ($response->is_error()) {
12332: unlink($transferfile);
12333: &logthis("Userfile repcopy failed for $uri");
12334: return -1;
12335: }
12336: # worked, rename the transfer file
12337: rename($transferfile,$file);
1.607 raeburn 12338: return 'ok';
1.481 raeburn 12339: }
12340:
1.517 albertel 12341: sub tokenwrapper {
12342: my $uri=shift;
1.980 raeburn 12343: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12344: $uri=~s|^/||;
1.620 albertel 12345: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12346: my $token=$1;
1.552 albertel 12347: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12348: if ($udom && $uname && $file) {
12349: $file=~s|(\?\.*)*$||;
1.949 raeburn 12350: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12351: my $homeserver = &homeserver($uname,$udom);
12352: my $protocol = $protocol{$homeserver};
12353: $protocol = 'http' if ($protocol ne 'https');
12354: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12355: (($uri=~/\?/)?'&':'?').'token='.$token.
12356: '&tokenissued='.$perlvar{'lonHostID'};
12357: } else {
12358: return '/adm/notfound.html';
12359: }
12360: }
12361:
1.828 www 12362: # call with reqtype HEAD: get last modification time
12363: # call with reqtype GET: get the file contents
12364: # Do not call this with reqtype GET for large files! It loads everything into memory
12365: #
1.481 raeburn 12366: sub getuploaded {
12367: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12368: $uri=~s/^\///;
1.980 raeburn 12369: my $homeserver = &homeserver($cnum,$cdom);
12370: my $protocol = $protocol{$homeserver};
12371: $protocol = 'http' if ($protocol ne 'https');
12372: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12373: my $ua=new LWP::UserAgent;
12374: my $request=new HTTP::Request($reqtype,$uri);
12375: my $response=$ua->request($request);
12376: $$rtncode = $response->code;
1.482 albertel 12377: if (! $response->is_success()) {
12378: return 'failed';
12379: }
12380: if ($reqtype eq 'HEAD') {
1.486 www 12381: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12382: } elsif ($reqtype eq 'GET') {
12383: $$info = $response->content;
1.472 albertel 12384: }
1.482 albertel 12385: return 'ok';
1.36 albertel 12386: }
12387:
1.481 raeburn 12388: sub readfile {
12389: my $file = shift;
12390: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12391: my $fh;
12392: open($fh,"<$file");
12393: my $a='';
1.800 albertel 12394: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12395: return $a;
12396: }
12397:
1.36 albertel 12398: sub filelocation {
1.590 banghart 12399: my ($dir,$file) = @_;
12400: my $location;
12401: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12402:
12403: if ($file =~ m-^/adm/-) {
12404: $file=~s-^/adm/wrapper/-/-;
12405: $file=~s-^/adm/coursedocs/showdoc/-/-;
12406: }
1.882 albertel 12407:
1.1139 www 12408: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12409: $location = $file;
1.609 banghart 12410: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12411: my ($udom,$uname,$filename)=
1.811 albertel 12412: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12413: my $home=&homeserver($uname,$udom);
12414: my $is_me=0;
12415: my @ids=¤t_machine_ids();
12416: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12417: if ($is_me) {
1.1117 foxr 12418: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12419: } else {
12420: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12421: $udom.'/'.$uname.'/'.$filename;
12422: }
1.882 albertel 12423: } elsif ($file =~ m-^/adm/-) {
12424: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12425: } else {
12426: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12427: $file=~s:^/(res|priv)/:/:;
12428: my $space=$1;
1.590 banghart 12429: if ( !( $file =~ m:^/:) ) {
12430: $location = $dir. '/'.$file;
12431: } else {
1.1142 raeburn 12432: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12433: }
1.59 albertel 12434: }
1.590 banghart 12435: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12436: while ($location=~m{/\.\./}) {
12437: if ($location =~ m{/[^/]+/\.\./}) {
12438: $location=~ s{/[^/]+/\.\./}{/}g;
12439: } else {
12440: $location=~ s{/\.\./}{/}g;
12441: }
12442: } #remove dir/..
1.590 banghart 12443: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12444: return $location;
1.46 www 12445: }
1.36 albertel 12446:
1.46 www 12447: sub hreflocation {
12448: my ($dir,$file)=@_;
1.980 raeburn 12449: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12450: $file=filelocation($dir,$file);
1.700 albertel 12451: } elsif ($file=~m-^/adm/-) {
12452: $file=~s-^/adm/wrapper/-/-;
12453: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12454: }
12455: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12456: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12457: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12458: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12459: {/uploaded/$1/$2/}x;
1.46 www 12460: }
1.913 albertel 12461: if ($file=~ m{^/userfiles/}) {
12462: $file =~ s{^/userfiles/}{/uploaded/};
12463: }
1.462 albertel 12464: return $file;
1.465 albertel 12465: }
12466:
1.1139 www 12467:
12468:
12469:
12470:
1.465 albertel 12471: sub current_machine_domains {
1.853 albertel 12472: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12473: }
12474:
12475: sub machine_domains {
12476: my ($hostname) = @_;
1.465 albertel 12477: my @domains;
1.838 albertel 12478: my %hostname = &all_hostnames();
1.465 albertel 12479: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12480: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12481: if ($hostname eq $name) {
1.844 albertel 12482: push(@domains,&host_domain($id));
1.465 albertel 12483: }
12484: }
12485: return @domains;
12486: }
12487:
12488: sub current_machine_ids {
1.853 albertel 12489: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12490: }
12491:
12492: sub machine_ids {
12493: my ($hostname) = @_;
12494: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12495: my @ids;
1.888 albertel 12496: my %name_to_host = &all_names();
1.889 albertel 12497: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12498: return @{ $name_to_host{$hostname} };
12499: }
12500: return;
1.31 www 12501: }
12502:
1.824 raeburn 12503: sub additional_machine_domains {
12504: my @domains;
12505: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12506: while( my $line = <$fh>) {
12507: $line =~ s/\s//g;
12508: push(@domains,$line);
12509: }
12510: return @domains;
12511: }
12512:
12513: sub default_login_domain {
12514: my $domain = $perlvar{'lonDefDomain'};
12515: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12516: foreach my $posdom (¤t_machine_domains(),
12517: &additional_machine_domains()) {
12518: if (lc($posdom) eq lc($testdomain)) {
12519: $domain=$posdom;
12520: last;
12521: }
12522: }
12523: return $domain;
12524: }
12525:
1.31 www 12526: # ------------------------------------------------------------- Declutters URLs
12527:
12528: sub declutter {
12529: my $thisfn=shift;
1.569 albertel 12530: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12531: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12532: $thisfn=~s{^/home/httpd/html}{};
12533: }
1.31 www 12534: $thisfn=~s/^\///;
1.697 albertel 12535: $thisfn=~s|^adm/wrapper/||;
12536: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12537: $thisfn=~s/^res\///;
1.1172 bisitz 12538: $thisfn=~s/^priv\///;
1.1032 raeburn 12539: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12540: $thisfn=~s/\?.+$//;
12541: }
1.268 www 12542: return $thisfn;
12543: }
12544:
12545: # ------------------------------------------------------------- Clutter up URLs
12546:
12547: sub clutter {
12548: my $thisfn='/'.&declutter(shift);
1.887 albertel 12549: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12550: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12551: $thisfn='/res'.$thisfn;
12552: }
1.1031 raeburn 12553: if ($thisfn !~m|^/adm|) {
12554: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12555: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12556: } else {
12557: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12558: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12559: if ($embstyle eq 'ssi'
12560: || ($embstyle eq 'hdn')
12561: || ($embstyle eq 'rat')
12562: || ($embstyle eq 'prv')
12563: || ($embstyle eq 'ign')) {
12564: #do nothing with these
12565: } elsif (($embstyle eq 'img')
1.695 albertel 12566: || ($embstyle eq 'emb')
12567: || ($embstyle eq 'wrp')) {
12568: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12569: } elsif ($embstyle eq 'unk'
12570: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12571: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12572: } else {
1.718 www 12573: # &logthis("Got a blank emb style");
1.695 albertel 12574: }
1.694 albertel 12575: }
1.1172.2.93.4 2(raebur 12576:7): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
12577:7): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12578: }
1.31 www 12579: return $thisfn;
1.12 www 12580: }
12581:
1.787 albertel 12582: sub clutter_with_no_wrapper {
12583: my $uri = &clutter(shift);
12584: if ($uri =~ m-^/adm/-) {
12585: $uri =~ s-^/adm/wrapper/-/-;
12586: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12587: }
12588: return $uri;
12589: }
12590:
1.557 albertel 12591: sub freeze_escape {
12592: my ($value)=@_;
12593: if (ref($value)) {
12594: $value=&nfreeze($value);
12595: return '__FROZEN__'.&escape($value);
12596: }
12597: return &escape($value);
12598: }
12599:
1.11 www 12600:
1.557 albertel 12601: sub thaw_unescape {
12602: my ($value)=@_;
12603: if ($value =~ /^__FROZEN__/) {
12604: substr($value,0,10,undef);
12605: $value=&unescape($value);
12606: return &thaw($value);
12607: }
12608: return &unescape($value);
12609: }
12610:
1.436 albertel 12611: sub correct_line_ends {
12612: my ($result)=@_;
12613: $$result =~s/\r\n/\n/mg;
12614: $$result =~s/\r/\n/mg;
1.415 albertel 12615: }
1.1 albertel 12616: # ================================================================ Main Program
12617:
1.184 www 12618: sub goodbye {
1.204 albertel 12619: &logthis("Starting Shut down");
1.443 albertel 12620: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12621: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12622: #converted
1.599 albertel 12623: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12624: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12625: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12626: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12627: #1.1 only
1.870 albertel 12628: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12629: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12630: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12631: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12632: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12633: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12634: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12635: &flushcourselogs();
12636: &logthis("Shutting down");
12637: }
12638:
1.852 albertel 12639: sub get_dns {
1.1172.2.17 raeburn 12640: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12641: if (!$ignore_cache) {
12642: my ($content,$cached)=
12643: &Apache::lonnet::is_cached_new('dns',$url);
12644: if ($cached) {
1.1172.2.17 raeburn 12645: &$func($content,$hashref);
1.869 albertel 12646: return;
12647: }
12648: }
12649:
12650: my %alldns;
1.852 albertel 12651: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12652: foreach my $dns (<$config>) {
12653: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12654: my $line = $1;
12655: my ($host,$protocol) = split(/:/,$line);
12656: if ($protocol ne 'https') {
12657: $protocol = 'http';
12658: }
12659: $alldns{$host} = $protocol;
1.869 albertel 12660: }
12661: while (%alldns) {
1.1172.2.52 raeburn 12662: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12663: my $ua=new LWP::UserAgent;
1.1134 raeburn 12664: $ua->timeout(30);
1.979 raeburn 12665: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12666: my $response=$ua->request($request);
1.979 raeburn 12667: delete($alldns{$dns});
1.852 albertel 12668: next if ($response->is_error());
12669: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12670: unless ($nocache) {
1.1172.2.23 raeburn 12671: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12672: }
12673: &$func(\@content,$hashref);
1.869 albertel 12674: return;
1.852 albertel 12675: }
12676: close($config);
1.871 albertel 12677: my $which = (split('/',$url))[3];
12678: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12679: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12680: my @content = <$config>;
1.1172.2.17 raeburn 12681: &$func(\@content,$hashref);
12682: return;
12683: }
12684:
12685: # ------------------------------------------------------Get DNS checksums file
12686: sub parse_dns_checksums_tab {
12687: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12688: my $lonhost = $perlvar{'lonHostID'};
12689: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12690: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12691: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12692: my $webconfdir = '/etc/httpd/conf';
12693: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12694: $webconfdir = '/etc/apache2';
12695: } elsif ($distro =~ /^sles(\d+)$/) {
12696: if ($1 >= 10) {
12697: $webconfdir = '/etc/apache2';
12698: }
12699: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12700: if ($1 >= 10.0) {
12701: $webconfdir = '/etc/apache2';
12702: }
12703: }
1.1172.2.17 raeburn 12704: my ($release,$timestamp) = split(/\-/,$loncaparev);
12705: my (%chksum,%revnum);
12706: if (ref($lines) eq 'ARRAY') {
12707: chomp(@{$lines});
1.1172.2.34 raeburn 12708: my $version = shift(@{$lines});
12709: if ($version eq $release) {
1.1172.2.17 raeburn 12710: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12711: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12712: if ($file =~ m{^/etc/httpd/conf}) {
12713: if ($webconfdir eq '/etc/apache2') {
12714: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12715: }
12716: }
1.1172.2.34 raeburn 12717: $chksum{$file} = $shasum;
12718: $revnum{$file} = $version;
1.1172.2.17 raeburn 12719: }
12720: if (ref($hashref) eq 'HASH') {
12721: %{$hashref} = (
12722: sums => \%chksum,
12723: versions => \%revnum,
12724: );
12725: }
12726: }
12727: }
1.869 albertel 12728: return;
1.852 albertel 12729: }
1.1172.2.17 raeburn 12730:
12731: sub fetch_dns_checksums {
12732: my %checksums;
1.1172.2.34 raeburn 12733: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12734: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12735: my ($release,$timestamp) = split(/\-/,$loncaparev);
12736: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12737: \%checksums);
12738: return \%checksums;
12739: }
12740:
1.327 albertel 12741: # ------------------------------------------------------------ Read domain file
12742: {
1.852 albertel 12743: my $loaded;
1.846 albertel 12744: my %domain;
12745:
1.852 albertel 12746: sub parse_domain_tab {
12747: my ($lines) = @_;
12748: foreach my $line (@$lines) {
12749: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12750:
1.846 albertel 12751: chomp($line);
1.852 albertel 12752: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12753: my %this_domain;
12754: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12755: 'lang_def', 'city', 'longi', 'lati',
12756: 'primary') {
12757: $this_domain{$field} = shift(@elements);
12758: }
12759: $domain{$name} = \%this_domain;
1.852 albertel 12760: }
12761: }
1.864 albertel 12762:
12763: sub reset_domain_info {
12764: undef($loaded);
12765: undef(%domain);
12766: }
12767:
1.852 albertel 12768: sub load_domain_tab {
1.1172.2.70 raeburn 12769: my ($ignore_cache,$nocache) = @_;
12770: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12771: my $fh;
12772: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12773: my @lines = <$fh>;
12774: &parse_domain_tab(\@lines);
1.448 albertel 12775: }
1.852 albertel 12776: close($fh);
12777: $loaded = 1;
1.327 albertel 12778: }
1.846 albertel 12779:
12780: sub domain {
1.852 albertel 12781: &load_domain_tab() if (!$loaded);
12782:
1.846 albertel 12783: my ($name,$what) = @_;
12784: return if ( !exists($domain{$name}) );
12785:
12786: if (!$what) {
12787: return $domain{$name}{'description'};
12788: }
12789: return $domain{$name}{$what};
12790: }
1.974 raeburn 12791:
12792: sub domain_info {
12793: &load_domain_tab() if (!$loaded);
12794: return %domain;
12795: }
12796:
1.327 albertel 12797: }
12798:
12799:
1.1 albertel 12800: # ------------------------------------------------------------- Read hosts file
12801: {
1.838 albertel 12802: my %hostname;
1.844 albertel 12803: my %hostdom;
1.845 albertel 12804: my %libserv;
1.852 albertel 12805: my $loaded;
1.888 albertel 12806: my %name_to_host;
1.1074 raeburn 12807: my %internetdom;
1.1107 raeburn 12808: my %LC_dns_serv;
1.852 albertel 12809:
12810: sub parse_hosts_tab {
12811: my ($file) = @_;
12812: foreach my $configline (@$file) {
12813: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12814: chomp($configline);
12815: if ($configline =~ /^\^/) {
12816: if ($configline =~ /^\^([\w.\-]+)/) {
12817: $LC_dns_serv{$1} = 1;
12818: }
12819: next;
12820: }
1.1074 raeburn 12821: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12822: $name=~s/\s//g;
12823: if ($id && $domain && $role && $name) {
1.1172.2.93.4 3(raebur 12824:7): if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
12825:7): my $curr = $hostname{$id};
12826:7): my $skip;
12827:7): if (ref($name_to_host{$curr}) eq 'ARRAY') {
12828:7): if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
12829:7): $skip = 1;
12830:7): } else {
12831:7): @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
12832:7): }
12833:7): }
12834:7): unless ($skip) {
12835:7): push(@{$name_to_host{$name}},$id);
12836:7): }
12837:7): } else {
12838:7): push(@{$name_to_host{$name}},$id);
12839:7): }
1.852 albertel 12840: $hostname{$id}=$name;
12841: $hostdom{$id}=$domain;
12842: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12843: if (defined($protocol)) {
12844: if ($protocol eq 'https') {
12845: $protocol{$id} = $protocol;
12846: } else {
12847: $protocol{$id} = 'http';
12848: }
1.968 raeburn 12849: } else {
1.969 raeburn 12850: $protocol{$id} = 'http';
1.968 raeburn 12851: }
1.1074 raeburn 12852: if (defined($intdom)) {
12853: $internetdom{$id} = $intdom;
12854: }
1.852 albertel 12855: }
12856: }
12857: }
1.864 albertel 12858:
12859: sub reset_hosts_info {
1.897 albertel 12860: &purge_remembered();
1.864 albertel 12861: &reset_domain_info();
12862: &reset_hosts_ip_info();
1.892 albertel 12863: undef(%name_to_host);
1.864 albertel 12864: undef(%hostname);
12865: undef(%hostdom);
12866: undef(%libserv);
12867: undef($loaded);
12868: }
1.1 albertel 12869:
1.852 albertel 12870: sub load_hosts_tab {
1.1172.2.70 raeburn 12871: my ($ignore_cache,$nocache) = @_;
12872: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12873: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12874: my @config = <$config>;
12875: &parse_hosts_tab(\@config);
12876: close($config);
12877: $loaded=1;
1.1 albertel 12878: }
1.852 albertel 12879:
1.838 albertel 12880: sub hostname {
1.852 albertel 12881: &load_hosts_tab() if (!$loaded);
12882:
1.838 albertel 12883: my ($lonid) = @_;
12884: return $hostname{$lonid};
12885: }
1.845 albertel 12886:
1.838 albertel 12887: sub all_hostnames {
1.852 albertel 12888: &load_hosts_tab() if (!$loaded);
12889:
1.838 albertel 12890: return %hostname;
12891: }
1.845 albertel 12892:
1.888 albertel 12893: sub all_names {
1.1172.2.70 raeburn 12894: my ($ignore_cache,$nocache) = @_;
12895: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12896:
12897: return %name_to_host;
12898: }
12899:
1.974 raeburn 12900: sub all_host_domain {
12901: &load_hosts_tab() if (!$loaded);
12902: return %hostdom;
12903: }
12904:
1.845 albertel 12905: sub is_library {
1.852 albertel 12906: &load_hosts_tab() if (!$loaded);
12907:
1.845 albertel 12908: return exists($libserv{$_[0]});
12909: }
12910:
12911: sub all_library {
1.852 albertel 12912: &load_hosts_tab() if (!$loaded);
12913:
1.845 albertel 12914: return %libserv;
12915: }
12916:
1.1062 droeschl 12917: sub unique_library {
12918: #2x reverse removes all hostnames that appear more than once
12919: my %unique = reverse &all_library();
12920: return reverse %unique;
12921: }
12922:
1.841 albertel 12923: sub get_servers {
1.852 albertel 12924: &load_hosts_tab() if (!$loaded);
12925:
1.841 albertel 12926: my ($domain,$type) = @_;
12927: my %possible_hosts = ($type eq 'library') ? %libserv
12928: : %hostname;
12929: my %result;
1.842 albertel 12930: if (ref($domain) eq 'ARRAY') {
12931: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12932: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12933: $result{$host} = $hostname;
12934: }
12935: }
12936: } else {
12937: while ( my ($host,$hostname) = each(%possible_hosts)) {
12938: if ($hostdom{$host} eq $domain) {
12939: $result{$host} = $hostname;
12940: }
1.841 albertel 12941: }
12942: }
12943: return %result;
12944: }
1.845 albertel 12945:
1.1062 droeschl 12946: sub get_unique_servers {
12947: my %unique = reverse &get_servers(@_);
12948: return reverse %unique;
12949: }
12950:
1.844 albertel 12951: sub host_domain {
1.852 albertel 12952: &load_hosts_tab() if (!$loaded);
12953:
1.844 albertel 12954: my ($lonid) = @_;
12955: return $hostdom{$lonid};
12956: }
12957:
1.841 albertel 12958: sub all_domains {
1.852 albertel 12959: &load_hosts_tab() if (!$loaded);
12960:
1.841 albertel 12961: my %seen;
12962: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12963: return @uniq;
12964: }
1.1074 raeburn 12965:
12966: sub internet_dom {
12967: &load_hosts_tab() if (!$loaded);
12968:
12969: my ($lonid) = @_;
12970: return $internetdom{$lonid};
12971: }
1.1107 raeburn 12972:
12973: sub is_LC_dns {
12974: &load_hosts_tab() if (!$loaded);
12975:
12976: my ($hostname) = @_;
12977: return exists($LC_dns_serv{$hostname});
12978: }
12979:
1.1 albertel 12980: }
12981:
1.847 albertel 12982: {
12983: my %iphost;
1.856 albertel 12984: my %name_to_ip;
12985: my %lonid_to_ip;
1.869 albertel 12986:
1.847 albertel 12987: sub get_hosts_from_ip {
12988: my ($ip) = @_;
12989: my %iphosts = &get_iphost();
12990: if (ref($iphosts{$ip})) {
12991: return @{$iphosts{$ip}};
12992: }
12993: return;
1.839 albertel 12994: }
1.864 albertel 12995:
12996: sub reset_hosts_ip_info {
12997: undef(%iphost);
12998: undef(%name_to_ip);
12999: undef(%lonid_to_ip);
13000: }
1.856 albertel 13001:
13002: sub get_host_ip {
13003: my ($lonid) = @_;
13004: if (exists($lonid_to_ip{$lonid})) {
13005: return $lonid_to_ip{$lonid};
13006: }
13007: my $name=&hostname($lonid);
13008: my $ip = gethostbyname($name);
13009: return if (!$ip || length($ip) ne 4);
13010: $ip=inet_ntoa($ip);
13011: $name_to_ip{$name} = $ip;
13012: $lonid_to_ip{$lonid} = $ip;
13013: return $ip;
13014: }
1.847 albertel 13015:
13016: sub get_iphost {
1.1172.2.70 raeburn 13017: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13018:
1.869 albertel 13019: if (!$ignore_cache) {
13020: if (%iphost) {
13021: return %iphost;
13022: }
13023: my ($ip_info,$cached)=
13024: &Apache::lonnet::is_cached_new('iphost','iphost');
13025: if ($cached) {
13026: %iphost = %{$ip_info->[0]};
13027: %name_to_ip = %{$ip_info->[1]};
13028: %lonid_to_ip = %{$ip_info->[2]};
13029: return %iphost;
13030: }
13031: }
1.894 albertel 13032:
13033: # get yesterday's info for fallback
13034: my %old_name_to_ip;
13035: my ($ip_info,$cached)=
13036: &Apache::lonnet::is_cached_new('iphost','iphost');
13037: if ($cached) {
13038: %old_name_to_ip = %{$ip_info->[1]};
13039: }
13040:
1.1172.2.70 raeburn 13041: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13042: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13043: my $ip;
13044: if (!exists($name_to_ip{$name})) {
13045: $ip = gethostbyname($name);
13046: if (!$ip || length($ip) ne 4) {
1.894 albertel 13047: if (defined($old_name_to_ip{$name})) {
13048: $ip = $old_name_to_ip{$name};
13049: &logthis("Can't find $name defaulting to old $ip");
13050: } else {
13051: &logthis("Name $name no IP found");
13052: next;
13053: }
13054: } else {
13055: $ip=inet_ntoa($ip);
1.847 albertel 13056: }
13057: $name_to_ip{$name} = $ip;
13058: } else {
13059: $ip = $name_to_ip{$name};
1.653 albertel 13060: }
1.888 albertel 13061: foreach my $id (@{ $name_to_host{$name} }) {
13062: $lonid_to_ip{$id} = $ip;
13063: }
13064: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13065: }
1.1172.2.70 raeburn 13066: unless ($nocache) {
13067: &do_cache_new('iphost','iphost',
13068: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13069: 48*60*60);
13070: }
1.869 albertel 13071:
1.847 albertel 13072: return %iphost;
1.598 albertel 13073: }
13074:
1.992 raeburn 13075: #
13076: # Given a DNS returns the loncapa host name for that DNS
13077: #
13078: sub host_from_dns {
13079: my ($dns) = @_;
13080: my @hosts;
13081: my $ip;
13082:
1.993 raeburn 13083: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13084: $ip = $name_to_ip{$dns};
13085: }
13086: if (!$ip) {
13087: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13088: if (length($ip) == 4) {
13089: $ip = &IO::Socket::inet_ntoa($ip);
13090: }
13091: }
13092: if ($ip) {
13093: @hosts = get_hosts_from_ip($ip);
13094: return $hosts[0];
13095: }
13096: return undef;
1.986 foxr 13097: }
1.992 raeburn 13098:
1.1074 raeburn 13099: sub get_internet_names {
13100: my ($lonid) = @_;
13101: return if ($lonid eq '');
13102: my ($idnref,$cached)=
13103: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13104: if ($cached) {
13105: return $idnref;
13106: }
13107: my $ip = &get_host_ip($lonid);
13108: my @hosts = &get_hosts_from_ip($ip);
13109: my %iphost = &get_iphost();
13110: my (@idns,%seen);
13111: foreach my $id (@hosts) {
13112: my $dom = &host_domain($id);
13113: my $prim_id = &domain($dom,'primary');
13114: my $prim_ip = &get_host_ip($prim_id);
13115: next if ($seen{$prim_ip});
13116: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13117: foreach my $id (@{$iphost{$prim_ip}}) {
13118: my $intdom = &internet_dom($id);
13119: unless (grep(/^\Q$intdom\E$/,@idns)) {
13120: push(@idns,$intdom);
13121: }
13122: }
13123: }
13124: $seen{$prim_ip} = 1;
13125: }
1.1172.2.23 raeburn 13126: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13127: }
13128:
1.986 foxr 13129: }
13130:
1.1079 raeburn 13131: sub all_loncaparevs {
1.1172.2.39 raeburn 13132: 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 13133: }
13134:
1.1172.2.27 raeburn 13135: # ------------------------------------------------------- Read loncaparev table
13136: {
13137: sub load_loncaparevs {
13138: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13139: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13140: while (my $configline=<$config>) {
13141: chomp($configline);
13142: my ($hostid,$loncaparev)=split(/:/,$configline);
13143: $loncaparevs{$hostid}=$loncaparev;
13144: }
13145: close($config);
13146: }
13147: }
13148: }
13149: }
13150:
13151: # ----------------------------------------------------- Read serverhostID table
13152: {
13153: sub load_serverhomeIDs {
13154: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13155: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13156: while (my $configline=<$config>) {
13157: chomp($configline);
13158: my ($name,$id)=split(/:/,$configline);
13159: $serverhomeIDs{$name}=$id;
13160: }
13161: close($config);
13162: }
13163: }
13164: }
13165: }
13166:
13167:
1.862 albertel 13168: BEGIN {
13169:
13170: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13171: unless ($readit) {
13172: {
13173: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13174: %perlvar = (%perlvar,%{$configvars});
13175: }
13176:
13177:
1.1 albertel 13178: # ------------------------------------------------------ Read spare server file
13179: {
1.448 albertel 13180: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13181:
13182: while (my $configline=<$config>) {
13183: chomp($configline);
1.284 matthew 13184: if ($configline) {
1.784 albertel 13185: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13186: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13187: push(@{ $spareid{$type} }, $host);
1.1 albertel 13188: }
13189: }
1.448 albertel 13190: close($config);
1.1 albertel 13191: }
1.11 www 13192: # ------------------------------------------------------------ Read permissions
13193: {
1.448 albertel 13194: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13195:
13196: while (my $configline=<$config>) {
1.448 albertel 13197: chomp($configline);
13198: if ($configline) {
13199: my ($role,$perm)=split(/ /,$configline);
13200: if ($perm ne '') { $pr{$role}=$perm; }
13201: }
1.11 www 13202: }
1.448 albertel 13203: close($config);
1.11 www 13204: }
13205:
13206: # -------------------------------------------- Read plain texts for permissions
13207: {
1.448 albertel 13208: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13209:
13210: while (my $configline=<$config>) {
1.448 albertel 13211: chomp($configline);
13212: if ($configline) {
1.742 raeburn 13213: my ($short,@plain)=split(/:/,$configline);
13214: %{$prp{$short}} = ();
13215: if (@plain > 0) {
13216: $prp{$short}{'std'} = $plain[0];
13217: for (my $i=1; $i<@plain; $i++) {
13218: $prp{$short}{'alt'.$i} = $plain[$i];
13219: }
13220: }
1.448 albertel 13221: }
1.135 www 13222: }
1.448 albertel 13223: close($config);
1.135 www 13224: }
13225:
13226: # ---------------------------------------------------------- Read package table
13227: {
1.448 albertel 13228: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13229:
13230: while (my $configline=<$config>) {
1.483 albertel 13231: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13232: chomp($configline);
13233: my ($short,$plain)=split(/:/,$configline);
13234: my ($pack,$name)=split(/\&/,$short);
13235: if ($plain ne '') {
13236: $packagetab{$pack.'&'.$name.'&name'}=$name;
13237: $packagetab{$short}=$plain;
13238: }
1.11 www 13239: }
1.448 albertel 13240: close($config);
1.329 matthew 13241: }
13242:
1.1172.2.27 raeburn 13243: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13244:
1.1172.2.27 raeburn 13245: &load_loncaparevs();
13246:
13247: # ------------------------------------------------------- Read serverhostID table
13248:
13249: &load_serverhomeIDs();
1.1074 raeburn 13250:
1.1172.2.27 raeburn 13251: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13252: {
13253: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13254: if (-e $file) {
13255: my $parser = HTML::LCParser->new($file);
13256: while (my $token = $parser->get_token()) {
13257: if ($token->[0] eq 'S') {
13258: my $item = $token->[1];
13259: my $name = $token->[2]{'name'};
13260: my $value = $token->[2]{'value'};
13261: if ($item ne '' && $name ne '' && $value ne '') {
13262: my $release = $parser->get_text();
13263: $release =~ s/(^\s*|\s*$ )//gx;
13264: $needsrelease{$item.':'.$name.':'.$value} = $release;
13265: }
13266: }
13267: }
13268: }
1.1073 raeburn 13269: }
13270:
1.1138 raeburn 13271: # ---------------------------------------------------------- Read managers table
13272: {
13273: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13274: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13275: while (my $configline=<$config>) {
13276: chomp($configline);
13277: next if ($configline =~ /^\#/);
13278: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13279: $managerstab{$configline} = 1;
13280: }
13281: }
13282: close($config);
13283: }
13284: }
13285: }
13286:
1.329 matthew 13287: # ------------- set up temporary directory
13288: {
1.1117 foxr 13289: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13290:
1.11 www 13291: }
13292:
1.794 albertel 13293: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13294: 'compress_threshold'=> 20_000,
13295: });
1.185 www 13296:
1.281 www 13297: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13298: $dumpcount=0;
1.958 www 13299: $locknum=0;
1.22 www 13300:
1.163 harris41 13301: &logtouch();
1.672 albertel 13302: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13303: $readit=1;
1.564 albertel 13304: {
13305: use integer;
13306: my $test=(2**32)+1;
1.568 albertel 13307: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13308: &logthis(" Detected 64bit platform ($_64bit)");
13309: }
1.195 www 13310: }
1.1 albertel 13311: }
1.179 www 13312:
1.1 albertel 13313: 1;
1.191 harris41 13314: __END__
13315:
1.243 albertel 13316: =pod
13317:
1.191 harris41 13318: =head1 NAME
13319:
1.243 albertel 13320: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13321:
13322: =head1 SYNOPSIS
13323:
1.243 albertel 13324: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13325:
13326: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13327:
1.243 albertel 13328: Common parameters:
13329:
13330: =over 4
13331:
13332: =item *
13333:
13334: $uname : an internal username (if $cname expecting a course Id specifically)
13335:
13336: =item *
13337:
13338: $udom : a domain (if $cdom expecting a course's domain specifically)
13339:
13340: =item *
13341:
13342: $symb : a resource instance identifier
13343:
13344: =item *
13345:
13346: $namespace : the name of a .db file that contains the data needed or
13347: being set.
13348:
13349: =back
13350:
1.394 bowersj2 13351: =head1 OVERVIEW
1.191 harris41 13352:
1.394 bowersj2 13353: lonnet provides subroutines which interact with the
13354: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13355: about classes, users, and resources.
1.243 albertel 13356:
13357: For many of these objects you can also use this to store data about
13358: them or modify them in various ways.
1.191 harris41 13359:
1.394 bowersj2 13360: =head2 Symbs
1.191 harris41 13361:
1.394 bowersj2 13362: To identify a specific instance of a resource, LON-CAPA uses symbols
13363: or "symbs"X<symb>. These identifiers are built from the URL of the
13364: map, the resource number of the resource in the map, and the URL of
13365: the resource itself. The latter is somewhat redundant, but might help
13366: if maps change.
13367:
13368: An example is
13369:
13370: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13371:
13372: The respective map entry is
13373:
13374: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13375: title="Problem 2">
13376: </resource>
13377:
13378: Symbs are used by the random number generator, as well as to store and
13379: restore data specific to a certain instance of for example a problem.
13380:
13381: =head2 Storing And Retrieving Data
13382:
13383: X<store()>X<cstore()>X<restore()>Three of the most important functions
13384: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13385: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13386: is is the non-critical message twin of cstore. These functions are for
13387: handlers to store a perl hash to a user's permanent data space in an
13388: easy manner, and to retrieve it again on another call. It is expected
13389: that a handler would use this once at the beginning to retrieve data,
13390: and then again once at the end to send only the new data back.
13391:
13392: The data is stored in the user's data directory on the user's
13393: homeserver under the ID of the course.
13394:
13395: The hash that is returned by restore will have all of the previous
13396: value for all of the elements of the hash.
13397:
13398: Example:
13399:
13400: #creating a hash
13401: my %hash;
13402: $hash{'foo'}='bar';
13403:
13404: #storing it
13405: &Apache::lonnet::cstore(\%hash);
13406:
13407: #changing a value
13408: $hash{'foo'}='notbar';
13409:
13410: #adding a new value
13411: $hash{'bar'}='foo';
13412: &Apache::lonnet::cstore(\%hash);
13413:
13414: #retrieving the hash
13415: my %history=&Apache::lonnet::restore();
13416:
13417: #print the hash
13418: foreach my $key (sort(keys(%history))) {
13419: print("\%history{$key} = $history{$key}");
13420: }
13421:
13422: Will print out:
1.191 harris41 13423:
1.394 bowersj2 13424: %history{1:foo} = bar
13425: %history{1:keys} = foo:timestamp
13426: %history{1:timestamp} = 990455579
13427: %history{2:bar} = foo
13428: %history{2:foo} = notbar
13429: %history{2:keys} = foo:bar:timestamp
13430: %history{2:timestamp} = 990455580
13431: %history{bar} = foo
13432: %history{foo} = notbar
13433: %history{timestamp} = 990455580
13434: %history{version} = 2
13435:
13436: Note that the special hash entries C<keys>, C<version> and
13437: C<timestamp> were added to the hash. C<version> will be equal to the
13438: total number of versions of the data that have been stored. The
13439: C<timestamp> attribute will be the UNIX time the hash was
13440: stored. C<keys> is available in every historical section to list which
13441: keys were added or changed at a specific historical revision of a
13442: hash.
13443:
13444: B<Warning>: do not store the hash that restore returns directly. This
13445: will cause a mess since it will restore the historical keys as if the
13446: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13447:
1.394 bowersj2 13448: Calling convention:
1.191 harris41 13449:
1.1172.2.27 raeburn 13450: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13451: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13452:
1.394 bowersj2 13453: For more detailed information, see lonnet specific documentation.
1.191 harris41 13454:
1.394 bowersj2 13455: =head1 RETURN MESSAGES
1.191 harris41 13456:
1.394 bowersj2 13457: =over 4
1.191 harris41 13458:
1.394 bowersj2 13459: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13460:
1.394 bowersj2 13461: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13462: when the connection is brought back up
1.191 harris41 13463:
1.394 bowersj2 13464: =item * B<con_failed>: unable to contact remote host and unable to save message
13465: for later delivery
1.191 harris41 13466:
1.967 bisitz 13467: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13468:
1.394 bowersj2 13469: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13470: that was requested
1.191 harris41 13471:
1.243 albertel 13472: =back
1.191 harris41 13473:
1.243 albertel 13474: =head1 PUBLIC SUBROUTINES
1.191 harris41 13475:
1.243 albertel 13476: =head2 Session Environment Functions
1.191 harris41 13477:
1.243 albertel 13478: =over 4
1.191 harris41 13479:
1.394 bowersj2 13480: =item *
13481: X<appenv()>
1.949 raeburn 13482: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13483: the user envirnoment file, and will be restored for each access this
1.620 albertel 13484: user makes during this session, also modifies the %env for the current
1.949 raeburn 13485: process. Optional rolesarrayref - if defined contains a reference to an array
13486: of roles which are exempt from the restriction on modifying user.role entries
13487: in the user's environment.db and in %env.
1.191 harris41 13488:
13489: =item *
1.394 bowersj2 13490: X<delenv()>
1.987 raeburn 13491: B<delenv($delthis,$regexp)>: removes all items from the session
13492: environment file that begin with $delthis. If the
13493: optional second arg - $regexp - is true, $delthis is treated as a
13494: regular expression, otherwise \Q$delthis\E is used.
13495: The values are also deleted from the current processes %env.
1.191 harris41 13496:
1.795 albertel 13497: =item * get_env_multiple($name)
13498:
13499: gets $name from the %env hash, it seemlessly handles the cases where multiple
13500: values may be defined and end up as an array ref.
13501:
13502: returns an array of values
13503:
1.243 albertel 13504: =back
13505:
13506: =head2 User Information
1.191 harris41 13507:
1.243 albertel 13508: =over 4
1.191 harris41 13509:
13510: =item *
1.394 bowersj2 13511: X<queryauthenticate()>
13512: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13513: authentication scheme
13514:
13515: =item *
1.394 bowersj2 13516: X<authenticate()>
1.1073 raeburn 13517: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13518: authenticate user from domain's lib servers (first use the current
13519: one). C<$upass> should be the users password.
1.1073 raeburn 13520: $checkdefauth is optional (value is 1 if a check should be made to
13521: authenticate user using default authentication method, and allow
13522: account creation if username does not have account in the domain).
13523: $clientcancheckhost is optional (value is 1 if checking whether the
13524: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13525:
13526: =item *
1.394 bowersj2 13527: X<homeserver()>
13528: B<homeserver($uname,$udom)>: find the server which has
13529: the user's directory and files (there must be only one), this caches
13530: the answer, and also caches if there is a borken connection.
1.191 harris41 13531:
13532: =item *
1.394 bowersj2 13533: X<idget()>
13534: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13535: (IDs are a unique resource in a domain, there must be only 1 ID per
13536: username, and only 1 username per ID in a specific domain) (returns
13537: hash: id=>name,id=>name)
1.191 harris41 13538:
13539: =item *
1.394 bowersj2 13540: X<idrget()>
13541: B<idrget($udom,@unames)>: find the IDs behind a list of
13542: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13543:
13544: =item *
1.394 bowersj2 13545: X<idput()>
13546: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13547:
13548: =item *
1.394 bowersj2 13549: X<rolesinit()>
1.1169 droeschl 13550: B<rolesinit($udom,$username)>: get user privileges.
13551: returns user role, first access and timer interval hashes
1.243 albertel 13552:
13553: =item *
1.1171 droeschl 13554: X<privileged()>
13555: B<privileged($username,$domain)>: returns a true if user has a
13556: privileged and active role (i.e. su or dc), false otherwise.
13557:
13558: =item *
1.551 albertel 13559: X<getsection()>
13560: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13561: course $cname, return section name/number or '' for "not in course"
13562: and '-1' for "no section"
13563:
13564: =item *
1.394 bowersj2 13565: X<userenvironment()>
13566: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13567: passed in @what from the requested user's environment, returns a hash
13568:
1.858 raeburn 13569: =item *
13570: X<userlog_query()>
1.859 albertel 13571: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13572: activity.log file. %filters defines filters applied when parsing the
13573: log file. These can be start or end timestamps, or the type of action
13574: - log to look for Login or Logout events, check for Checkin or
13575: Checkout, role for role selection. The response is in the form
13576: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13577: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13578:
1.243 albertel 13579: =back
13580:
13581: =head2 User Roles
13582:
13583: =over 4
13584:
13585: =item *
13586:
1.1172.2.65 raeburn 13587: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13588: returns codes for allowed actions.
13589:
13590: The first argument is required, all others are optional.
13591:
13592: $priv is the privilege being checked.
13593: $uri contains additional information about what is being checked for access (e.g.,
13594: URL, course ID etc.).
13595: $symb is the unique resource instance identifier in a course; if needed,
13596: but not provided, it will be retrieved via a call to &symbread().
13597: $role is the role for which a priv is being checked (only used if priv is evb).
13598: $clientip is the user's IP address (only used when checking for access to portfolio
13599: files).
13600: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13601: prevents recursive calls to &allowed.
13602:
1.243 albertel 13603: F: full access
13604: U,I,K: authentication modes (cxx only)
13605: '': forbidden
13606: 1: user needs to choose course
13607: 2: browse allowed
1.766 albertel 13608: A: passphrase authentication needed
1.1172.2.65 raeburn 13609: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13610:
13611: =item *
13612:
1.1172.2.13 raeburn 13613: constructaccess($url,$setpriv) : check for access to construction space URL
13614:
13615: See if the owner domain and name in the URL match those in the
13616: expected environment. If so, return three element list
13617: ($ownername,$ownerdomain,$ownerhome).
13618:
13619: Otherwise return the null string.
13620:
13621: If second argument 'setpriv' is true, it assigns the privileges,
13622: and returns the same three element list, unless the owner has
13623: blocked "ad hoc" Domain Coordinator access to the Author Space,
13624: in which case the null string is returned.
13625:
13626: =item *
13627:
1.1172.2.84 raeburn 13628: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13629: define a custom role rolename set privileges in format of lonTabs/roles.tab
13630: for system, domain, and course level. $uname and $udom are optional (current
13631: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13632:
13633: =item *
13634:
1.988 raeburn 13635: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13636: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13637: $type is Course (default) or Community.
1.988 raeburn 13638: If $forcedefault evaluates to true, text returned will be default
13639: text for $type. Otherwise, if this is a course, the text returned
13640: will be a custom name for the role (if defined in the course's
13641: environment). If no custom name is defined the default is returned.
13642:
1.832 raeburn 13643: =item *
13644:
1.1172.2.23 raeburn 13645: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13646: All arguments are optional. Returns a hash of a roles, either for
13647: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13648: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13649: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13650: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13651: For each key, value is set to colon-separated start and end times for
13652: the role. If no username and domain are specified, will default to
1.934 raeburn 13653: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13654: of role statuses (active, future or previous), roles
13655: (e.g., cc,in, st etc.) and domains of the roles which can be used
13656: to restrict the list of roles reported. If no array ref is
13657: provided for types, will default to return only active roles.
1.834 albertel 13658:
1.1172.2.13 raeburn 13659: =item *
13660:
13661: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13662: user: $uname:$udom has a role in the course: $cdom_$cnum.
13663:
13664: Additional optional arguments are: $type (if role checking is to be restricted
13665: to certain user status types -- previous (expired roles), active (currently
13666: available roles) or future (roles available in the future), and
13667: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13668: have active Domain Coordinator role in course's domain or in additional
13669: domains (specified in 'Domains to check for privileged users' in course
13670: environment -- set via: Course Settings -> Classlists and staff listing).
13671:
13672: =item *
13673:
13674: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13675: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13676: $possdomains and $possroles are optional array refs -- to domains to check and
13677: roles to check. If $possdomains is not specified, a dump will be done of the
13678: users' roles.db to check for a dc or su role in any domain. This can be
13679: time consuming if &privileged is called repeatedly (e.g., when displaying a
13680: classlist), so in such cases, supplying a $possdomains array is preferred, as
13681: this then allows &privileged_by_domain() to be used, which caches the identity
13682: of privileged users, eliminating the need for repeated calls to &dump().
13683:
13684: =item *
13685:
13686: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13687: where the outer hash keys are domains specified in the $possdomains array ref,
13688: next inner hash keys are privileged roles specified in the $roles array ref,
13689: and the innermost hash contains key = value pairs for username:domain = end:start
13690: for active or future "privileged" users with that role in that domain. To avoid
13691: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13692: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13693:
1.243 albertel 13694: =back
13695:
13696: =head2 User Modification
13697:
13698: =over 4
13699:
13700: =item *
13701:
1.957 raeburn 13702: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13703: user for the level given by URL. Optional start and end dates (leave empty
13704: string or zero for "no date")
1.191 harris41 13705:
13706: =item *
13707:
1.243 albertel 13708: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13709: change a users, password, possible return values are: ok,
13710: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13711: refused
1.191 harris41 13712:
13713: =item *
13714:
1.243 albertel 13715: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13716:
13717: =item *
13718:
1.1058 raeburn 13719: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13720: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13721:
13722: will update user information (firstname,middlename,lastname,generation,
13723: permanentemail), and if forceid is true, student/employee ID also.
13724: A user's institutional affiliation(s) can also be updated.
13725: User information fields will not be overwritten with empty entries
13726: unless the field is included in the $candelete array reference.
13727: This array is included when a single user is modified via "Manage Users",
13728: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13729:
13730: =item *
13731:
1.286 matthew 13732: modifystudent
13733:
1.957 raeburn 13734: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13735: The course id is resolved based on the current user's environment.
13736: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13737: associated with a course.
13738:
1.297 matthew 13739: This call is essentially a wrapper for lonnet::modifyuser and
13740: lonnet::modify_student_enrollment
1.286 matthew 13741:
13742: Inputs:
13743:
13744: =over 4
13745:
1.957 raeburn 13746: =item B<$udom> Student's loncapa domain
1.286 matthew 13747:
1.957 raeburn 13748: =item B<$uname> Student's loncapa login name
1.286 matthew 13749:
1.964 bisitz 13750: =item B<$uid> Student/Employee ID
1.286 matthew 13751:
1.957 raeburn 13752: =item B<$umode> Student's authentication mode
1.286 matthew 13753:
1.957 raeburn 13754: =item B<$upass> Student's password
1.286 matthew 13755:
1.957 raeburn 13756: =item B<$first> Student's first name
1.286 matthew 13757:
1.957 raeburn 13758: =item B<$middle> Student's middle name
1.286 matthew 13759:
1.957 raeburn 13760: =item B<$last> Student's last name
1.286 matthew 13761:
1.957 raeburn 13762: =item B<$gene> Student's generation
1.286 matthew 13763:
1.957 raeburn 13764: =item B<$usec> Student's section in course
1.286 matthew 13765:
13766: =item B<$end> Unix time of the roles expiration
13767:
13768: =item B<$start> Unix time of the roles start date
13769:
13770: =item B<$forceid> If defined, allow $uid to be changed
13771:
13772: =item B<$desiredhome> server to use as home server for student
13773:
1.957 raeburn 13774: =item B<$email> Student's permanent e-mail address
13775:
13776: =item B<$type> Type of enrollment (auto or manual)
13777:
1.963 raeburn 13778: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13779:
13780: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13781:
1.963 raeburn 13782: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13783:
1.963 raeburn 13784: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13785:
1.1172.2.19 raeburn 13786: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13787:
13788: =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 13789:
1.286 matthew 13790: =back
1.297 matthew 13791:
13792: =item *
13793:
13794: modify_student_enrollment
13795:
1.1172.2.31 raeburn 13796: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13797: 'role.request.course' must be defined for this function to proceed.
13798:
13799: Inputs:
13800:
13801: =over 4
13802:
1.1172.2.31 raeburn 13803: =item $udom, student's domain
1.297 matthew 13804:
1.1172.2.31 raeburn 13805: =item $uname, student's name
1.297 matthew 13806:
1.1172.2.31 raeburn 13807: =item $uid, student's user id
1.297 matthew 13808:
1.1172.2.31 raeburn 13809: =item $first, student's first name
1.297 matthew 13810:
13811: =item $middle
13812:
13813: =item $last
13814:
13815: =item $gene
13816:
13817: =item $usec
13818:
13819: =item $end
13820:
13821: =item $start
13822:
1.957 raeburn 13823: =item $type
13824:
13825: =item $locktype
13826:
13827: =item $cid
13828:
13829: =item $selfenroll
13830:
13831: =item $context
13832:
1.1172.2.19 raeburn 13833: =item $credits, number of credits student will earn from this class
13834:
1.1172.2.76 raeburn 13835: =item $instsec, institutional course section code for student
13836:
1.297 matthew 13837: =back
13838:
1.191 harris41 13839:
13840: =item *
13841:
1.243 albertel 13842: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13843: custom role; give a custom role to a user for the level given by URL. Specify
13844: name and domain of role author, and role name
1.191 harris41 13845:
13846: =item *
13847:
1.243 albertel 13848: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13849:
13850: =item *
13851:
1.243 albertel 13852: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13853:
13854: =back
13855:
13856: =head2 Course Infomation
13857:
13858: =over 4
1.191 harris41 13859:
13860: =item *
13861:
1.1118 foxr 13862: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13863: specified course id, including all environment settings for the
13864: course, the description of the course will be in the hash under the
13865: key 'description'
1.191 harris41 13866:
1.1118 foxr 13867: $options is an optional parameter that if supplied is a hash reference that controls
13868: what how this function works. It has the following key/values:
13869:
13870: =over 4
13871:
13872: =item freshen_cache
13873:
13874: If defined, and the environment cache for the course is valid, it is
13875: returned in the returned hash.
13876:
13877: =item one_time
13878:
13879: If defined, the last cache time is set to _now_
13880:
13881: =item user
13882:
13883: If defined, the supplied username is used instead of the current user.
13884:
13885:
13886: =back
13887:
1.191 harris41 13888: =item *
13889:
1.624 albertel 13890: resdata($name,$domain,$type,@which) : request for current parameter
13891: setting for a specific $type, where $type is either 'course' or 'user',
13892: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13893: answers for 10 minutes.
1.243 albertel 13894:
1.877 foxr 13895: =item *
13896:
13897: get_courseresdata($courseid, $domain) : dump the entire course resource
13898: data base, returning a hash that is keyed by the resource name and has
13899: values that are the resource value. I believe that the timestamps and
13900: versions are also returned.
13901:
1.1172.2.31 raeburn 13902: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13903: supplemental content area. This routine caches the number of files for
13904: 10 minutes.
13905:
1.243 albertel 13906: =back
13907:
13908: =head2 Course Modification
13909:
13910: =over 4
1.191 harris41 13911:
13912: =item *
13913:
1.243 albertel 13914: writecoursepref($courseid,%prefs) : write preferences (environment
13915: database) for a course
1.191 harris41 13916:
13917: =item *
13918:
1.1011 raeburn 13919: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13920:
13921: =item *
13922:
1.1038 raeburn 13923: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13924:
1.1167 droeschl 13925: =item *
13926:
13927: is_course($courseid), is_course($cdom, $cnum)
13928:
13929: Accepts either a combined $courseid (in the form of domain_courseid) or the
13930: two component version $cdom, $cnum. It checks if the specified course exists.
13931:
13932: Returns:
13933: undef if the course doesn't exist, otherwise
13934: in scalar context the combined courseid.
13935: in list context the two components of the course identifier, domain and
13936: courseid.
13937:
1.243 albertel 13938: =back
13939:
13940: =head2 Resource Subroutines
13941:
13942: =over 4
1.191 harris41 13943:
13944: =item *
13945:
1.243 albertel 13946: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13947:
13948: =item *
13949:
1.243 albertel 13950: repcopy($filename) : subscribes to the requested file, and attempts to
13951: replicate from the owning library server, Might return
1.607 raeburn 13952: 'unavailable', 'not_found', 'forbidden', 'ok', or
13953: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13954: resource. Expects the local filesystem pathname
13955: (/home/httpd/html/res/....)
13956:
13957: =back
13958:
13959: =head2 Resource Information
13960:
13961: =over 4
1.191 harris41 13962:
13963: =item *
13964:
1.1172.2.28 raeburn 13965: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13966: and returns the value of a variety of different possible values,
13967: $varname should be a request string, and the other parameters can be
13968: used to specify who and what one is asking about. Ordinarily, $cid
13969: does not need to be specified, as it is retrived from
13970: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13971: within lonuserstate::loadmap() when initializing a course, before
13972: $env{'request.course.id'} has been set, so it needs to be provided
13973: in that one case.
1.243 albertel 13974:
13975: Possible values for $varname are environment.lastname (or other item
13976: from the envirnment hash), user.name (or someother aspect about the
13977: user), resource.0.maxtries (or some other part and parameter of a
13978: resource)
1.204 albertel 13979:
13980: =item *
13981:
1.243 albertel 13982: directcondval($number) : get current value of a condition; reads from a state
13983: string
1.204 albertel 13984:
13985: =item *
13986:
1.243 albertel 13987: condval($condidx) : value of condition index based on state
1.204 albertel 13988:
13989: =item *
13990:
1.243 albertel 13991: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13992: resource's metadata, $what should be either a specific key, or either
13993: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13994: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13995:
13996: this function automatically caches all requests
1.191 harris41 13997:
13998: =item *
13999:
1.243 albertel 14000: metadata_query($query,$custom,$customshow) : make a metadata query against the
14001: network of library servers; returns file handle of where SQL and regex results
14002: will be stored for query
1.191 harris41 14003:
14004: =item *
14005:
1.1172.2.66 raeburn 14006: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14007: return symbolic list entry (all arguments optional).
14008:
14009: Args: filename is the filename (including path) for the file for which a symb
14010: is required; donotrecurse, if true will prevent calls to allowed() being made
14011: to check access status if more than one resource was found in the bighash
14012: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14013: a randompick); ignorecachednull, if true will prevent a symb of '' being
14014: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14015: cause possible symbs to be checked to determine if they are subject to content
14016: blocking, if so they will not be included as possible symbs; possibles is a
14017: ref to a hash, which, as a side effect, will be populated with all possible
14018: symbs (content blocking not tested).
14019:
1.243 albertel 14020: returns the data handle
1.191 harris41 14021:
14022: =item *
14023:
1.1172.2.17 raeburn 14024: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14025: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14026: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14027: on failure, user must be in a course, as it assumes the existence of
14028: the course initial hash, and uses $env('request.course.id'}. The third
14029: arg is an optional reference to a scalar. If this arg is passed in the
14030: call to symbverify, it will be set to 1 if the symb has been set to be
14031: encrypted; otherwise it will be null.
1.243 albertel 14032:
1.191 harris41 14033: =item *
14034:
1.243 albertel 14035: symbclean($symb) : removes versions numbers from a symb, returns the
14036: cleaned symb
1.191 harris41 14037:
14038: =item *
14039:
1.243 albertel 14040: is_on_map($uri) : checks if the $uri is somewhere on the current
14041: course map, user must be in a course for it to work.
1.191 harris41 14042:
14043: =item *
14044:
1.243 albertel 14045: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14046:
14047: =item *
14048:
1.243 albertel 14049: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14050: a random seed, all arguments are optional, if they aren't sent it uses the
14051: environment to derive them. Note: if symb isn't sent and it can't get one
14052: from &symbread it will use the current time as its return value
1.191 harris41 14053:
14054: =item *
14055:
1.243 albertel 14056: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14057: unfakeable, receipt
1.191 harris41 14058:
14059: =item *
14060:
1.620 albertel 14061: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14062:
14063: =item *
14064:
1.243 albertel 14065: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14066:
14067: =item *
14068:
1.243 albertel 14069: 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 14070:
14071: =item *
14072:
1.243 albertel 14073: 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 14074:
14075: =item *
14076:
1.243 albertel 14077: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14078:
14079: =item *
14080:
1.243 albertel 14081: devalidate($symb) : devalidate temporary spreadsheet calculations,
14082: forcing spreadsheet to reevaluate the resource scores next time.
14083:
1.1172.2.13 raeburn 14084: =item *
14085:
14086: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14087: when viewing in course context.
14088:
14089: input: six args -- filename (decluttered), course number, course domain,
14090: url, symb (if registered) and group (if this is a
14091: group item -- e.g., bulletin board, group page etc.).
14092:
14093: output: array of five scalars --
14094: $cfile -- url for file editing if editable on current server
14095: $home -- homeserver of resource (i.e., for author if published,
14096: or course if uploaded.).
14097: $switchserver -- 1 if server switch will be needed.
14098: $forceedit -- 1 if icon/link should be to go to edit mode
14099: $forceview -- 1 if icon/link should be to go to view mode
14100:
14101: =item *
14102:
14103: is_course_upload($file,$cnum,$cdom)
14104:
14105: Used in course context to determine if current file was uploaded to
14106: the course (i.e., would be found in /userfiles/docs on the course's
14107: homeserver.
14108:
14109: input: 3 args -- filename (decluttered), course number and course domain.
14110: output: boolean -- 1 if file was uploaded.
14111:
1.243 albertel 14112: =back
14113:
14114: =head2 Storing/Retreiving Data
14115:
14116: =over 4
1.191 harris41 14117:
14118: =item *
14119:
1.1172.2.64 raeburn 14120: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14121: permanently for this url; hashref needs to be given and should be a \%hashname;
14122: the remaining args aren't required and if they aren't passed or are '' they will
14123: be derived from the env (with the exception of $laststore, which is an
14124: optional arg used when a user's submission is stored in grading).
14125: $laststore is $version=$timestamp, where $version is the most recent version
14126: number retrieved for the corresponding $symb in the $namespace db file, and
14127: $timestamp is the timestamp for that transaction (UNIX time).
14128: $laststore is currently only passed when cstore() is called by
14129: structuretags::finalize_storage().
1.191 harris41 14130:
14131: =item *
14132:
1.1172.2.64 raeburn 14133: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14134: but uses critical subroutine
1.191 harris41 14135:
14136: =item *
14137:
1.243 albertel 14138: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14139: all args are optional
1.191 harris41 14140:
14141: =item *
14142:
1.717 albertel 14143: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14144: dumps the complete (or key matching regexp) namespace into a hash
14145: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14146: normally &store()ed into
14147:
14148: $range should be either an integer '100' (give me the first 100
14149: matching records)
14150: or be two integers sperated by a - with no spaces
14151: '30-50' (give me the 30th through the 50th matching
14152: records)
14153:
14154:
14155: =item *
14156:
1.1172.2.59 raeburn 14157: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14158: replaces a &store() version of data with a replacement set of data
14159: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14160: reference. If $tolog is true, the transaction is logged in the courselog
14161: with an action=PUTSTORE.
1.717 albertel 14162:
14163: =item *
14164:
1.243 albertel 14165: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14166: works very similar to store/cstore, but all data is stored in a
14167: temporary location and can be reset using tmpreset, $storehash should
14168: be a hash reference, returns nothing on success
1.191 harris41 14169:
14170: =item *
14171:
1.243 albertel 14172: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14173: similar to restore, but all data is stored in a temporary location and
14174: can be reset using tmpreset. Returns a hash of values on success,
14175: error string otherwise.
1.191 harris41 14176:
14177: =item *
14178:
1.243 albertel 14179: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14180: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14181:
14182: =item *
14183:
1.243 albertel 14184: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14185: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14186:
14187: =item *
14188:
1.243 albertel 14189: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14190: namesp ($udom and $uname are optional)
1.191 harris41 14191:
14192: =item *
14193:
1.702 albertel 14194: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14195: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14196: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14197:
1.702 albertel 14198: $range should be either an integer '100' (give me the first 100
14199: matching records)
14200: or be two integers sperated by a - with no spaces
14201: '30-50' (give me the 30th through the 50th matching
14202: records)
1.449 matthew 14203: =item *
14204:
14205: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14206: $store can be a scalar, an array reference, or if the amount to be
14207: incremented is > 1, a hash reference.
14208:
14209: ($udom and $uname are optional)
1.191 harris41 14210:
14211: =item *
14212:
1.243 albertel 14213: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14214: ($udom and $uname are optional)
1.191 harris41 14215:
14216: =item *
14217:
1.243 albertel 14218: cput($namespace,$storehash,$udom,$uname) : critical put
14219: ($udom and $uname are optional)
1.191 harris41 14220:
14221: =item *
14222:
1.748 albertel 14223: newput($namespace,$storehash,$udom,$uname) :
14224:
14225: Attempts to store the items in the $storehash, but only if they don't
14226: currently exist, if this succeeds you can be certain that you have
14227: successfully created a new key value pair in the $namespace db.
14228:
14229:
14230: Args:
14231: $namespace: name of database to store values to
14232: $storehash: hashref to store to the db
14233: $udom: (optional) domain of user containing the db
14234: $uname: (optional) name of user caontaining the db
14235:
14236: Returns:
14237: 'ok' -> succeeded in storing all keys of $storehash
14238: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14239: least <key> already existed in the db (other
14240: requested keys may also already exist)
1.967 bisitz 14241: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14242: 'con_lost' -> unable to contact request server
14243: 'refused' -> action was not allowed by remote machine
14244:
14245:
14246: =item *
14247:
1.243 albertel 14248: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14249: reference filled in from namesp (encrypts the return communication)
14250: ($udom and $uname are optional)
1.191 harris41 14251:
14252: =item *
14253:
1.243 albertel 14254: log($udom,$name,$home,$message) : write to permanent log for user; use
14255: critical subroutine
14256:
1.806 raeburn 14257: =item *
14258:
1.860 raeburn 14259: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14260: array reference filled in from namespace found in domain level on either
14261: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14262:
14263: =item *
14264:
1.860 raeburn 14265: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14266: domain level either on specified domain server ($uhome) or primary domain
14267: server ($udom and $uhome are optional)
1.806 raeburn 14268:
1.943 raeburn 14269: =item *
14270:
1.1172.2.35 raeburn 14271: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14272: for: authentication, language, quotas, timezone, date locale, and portal URL in
14273: the target domain.
14274:
14275: May also include additional key => value pairs for the following groups:
14276:
14277: =over
14278:
14279: =item
14280: disk quotas (MB allocated by default to portfolios and authoring spaces).
14281:
14282: =over
14283:
14284: =item defaultquota, authorquota
14285:
14286: =back
14287:
14288: =item
14289: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14290: portfolio for users).
14291:
14292: =over
14293:
14294: =item
14295: aboutme, blog, webdav, portfolio
14296:
14297: =back
14298:
14299: =item
14300: requestcourses: ability to request courses, and how requests are processed.
14301:
14302: =over
14303:
14304: =item
1.1172.2.37 raeburn 14305: official, unofficial, community, textbook
1.1172.2.35 raeburn 14306:
14307: =back
14308:
14309: =item
14310: inststatus: types of institutional affiliation, and order in which they are displayed.
14311:
14312: =over
14313:
14314: =item
1.1172.2.44 raeburn 14315: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14316:
14317: =back
14318:
14319: =item
14320: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14321: for course's uploaded content.
14322:
14323: =over
14324:
14325: =item
1.1172.2.68 raeburn 14326: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14327: communityquota, textbookquota
1.1172.2.35 raeburn 14328:
14329: =back
14330:
14331: =item
14332: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14333: on your servers.
14334:
14335: =over
14336:
14337: =item
14338: remotesessions, hostedsessions
14339:
14340: =back
14341:
14342: =back
14343:
14344: In cases where a domain coordinator has never used the "Set Domain Configuration"
14345: utility to create a configuration.db file on a domain's primary library server
14346: only the following domain defaults: auth_def, auth_arg_def, lang_def
14347: -- corresponding values are authentication type (internal, krb4, krb5,
14348: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14349: will be available. Values are retrieved from cache (if current), unless the
14350: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14351: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14352:
14353: Typical usage:
1.943 raeburn 14354:
1.1172.2.35 raeburn 14355: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14356:
1.243 albertel 14357: =back
14358:
14359: =head2 Network Status Functions
14360:
14361: =over 4
1.191 harris41 14362:
14363: =item *
14364:
1.1137 raeburn 14365: dirlist() : return directory list based on URI (first arg).
14366:
14367: Inputs: 1 required, 5 optional.
14368:
14369: =over
14370:
14371: =item
14372: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14373:
14374: =item
14375: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14376:
14377: =item
14378: $username - username of user/course to be listed. Extracted from $uri if absent.
14379:
14380: =item
14381: $getpropath - boolean: 1 if prepend path using &propath().
14382:
14383: =item
14384: $getuserdir - boolean: 1 if prepend path for "userfiles".
14385:
14386: =item
14387: $alternateRoot - path to prepend in place of path from $uri.
14388:
14389: =back
14390:
14391: Returns: Array of up to two items.
14392:
14393: =over
14394:
14395: a reference to an array of files/subdirectories
14396:
14397: =over
14398:
14399: Each element in the array of files/subdirectories is a & separated list of
14400: item name and the result of running stat on the item. If dirlist was requested
14401: for a file instead of a directory, the item name will be ''. For a directory
14402: listing, if the item is a metadata file, the element will end &N&M
14403: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14404: default copyright set (1).
14405:
14406: =back
14407:
14408: a scalar containing error condition (if encountered).
14409:
14410: =over
14411:
14412: =item
14413: no_host (no homeserver identified for $username:$domain).
14414:
14415: =item
14416: no_such_host (server contacted for listing not identified as valid host).
14417:
14418: =item
14419: con_lost (connection to remote server failed).
14420:
14421: =item
14422: refused (invalid $username:$domain received on lond side).
14423:
14424: =item
14425: no_such_dir (directory at specified path on lond side does not exist).
14426:
14427: =item
14428: empty (directory at specified path on lond side is empty).
14429:
14430: =over
14431:
14432: This is currently not encountered because the &ls3, &ls2,
14433: &ls (_handler) routines on the lond side do not filter out
14434: . and .. from a directory listing.
14435:
14436: =back
14437:
14438: =back
14439:
14440: =back
1.191 harris41 14441:
14442: =item *
14443:
1.243 albertel 14444: spareserver() : find server with least workload from spare.tab
14445:
1.986 foxr 14446:
14447: =item *
14448:
14449: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14450: if there is no corresponding loncapa host.
14451:
1.243 albertel 14452: =back
14453:
1.986 foxr 14454:
1.243 albertel 14455: =head2 Apache Request
14456:
14457: =over 4
1.191 harris41 14458:
14459: =item *
14460:
1.243 albertel 14461: ssi($url,%hash) : server side include, does a complete request cycle on url to
14462: localhost, posts hash
14463:
14464: =back
14465:
14466: =head2 Data to String to Data
14467:
14468: =over 4
1.191 harris41 14469:
14470: =item *
14471:
1.243 albertel 14472: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14473: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14474:
14475: =item *
14476:
1.243 albertel 14477: hashref2str($hashref) : convert a hashref into a string complete with
14478: escaping and '=' and '&' separators, supports elements that are
14479: arrayrefs and hashrefs
1.191 harris41 14480:
14481: =item *
14482:
1.243 albertel 14483: arrayref2str($arrayref) : convert an arrayref into a string complete
14484: with escaping and '&' separators, supports elements that are arrayrefs
14485: and hashrefs
1.191 harris41 14486:
14487: =item *
14488:
1.243 albertel 14489: str2hash($string) : convert string to hash using unescaping and
14490: splitting on '=' and '&', supports elements that are arrayrefs and
14491: hashrefs
1.191 harris41 14492:
14493: =item *
14494:
1.243 albertel 14495: str2array($string) : convert string to hash using unescaping and
14496: splitting on '&', supports elements that are arrayrefs and hashrefs
14497:
14498: =back
14499:
14500: =head2 Logging Routines
14501:
14502:
14503: These routines allow one to make log messages in the lonnet.log and
14504: lonnet.perm logfiles.
1.191 harris41 14505:
1.1119 foxr 14506: =over 4
14507:
1.191 harris41 14508: =item *
14509:
1.243 albertel 14510: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14511:
14512: =item *
14513:
1.243 albertel 14514: logthis() : append message to the normal lonnet.log file, it gets
14515: preiodically rolled over and deleted.
1.191 harris41 14516:
14517: =item *
14518:
1.243 albertel 14519: logperm() : append a permanent message to lonnet.perm.log, this log
14520: file never gets deleted by any automated portion of the system, only
14521: messages of critical importance should go in here.
14522:
1.1119 foxr 14523:
1.243 albertel 14524: =back
14525:
14526: =head2 General File Helper Routines
14527:
14528: =over 4
1.191 harris41 14529:
14530: =item *
14531:
1.481 raeburn 14532: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14533: (a) files in /uploaded
14534: (i) If a local copy of the file exists -
14535: compares modification date of local copy with last-modified date for
14536: definitive version stored on home server for course. If local copy is
14537: stale, requests a new version from the home server and stores it.
14538: If the original has been removed from the home server, then local copy
14539: is unlinked.
14540: (ii) If local copy does not exist -
14541: requests the file from the home server and stores it.
14542:
14543: If $caller is 'uploadrep':
14544: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14545: for request for files originally uploaded via DOCS.
14546: - returns 'ok' if fresh local copy now available, -1 otherwise.
14547:
14548: Otherwise:
14549: This indicates a call from the content generation phase of the request.
14550: - returns the entire contents of the file or -1.
14551:
14552: (b) files in /res
14553: - returns the entire contents of a file or -1;
14554: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14555:
1.712 albertel 14556:
14557: =item *
14558:
14559: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14560: reference
14561:
14562: returns either a stat() list of data about the file or an empty list
14563: if the file doesn't exist or couldn't find out about it (connection
14564: problems or user unknown)
14565:
1.191 harris41 14566: =item *
14567:
1.243 albertel 14568: filelocation($dir,$file) : returns file system location of a file
14569: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14570: directory that relative $file lookups are to looked in ($dir of /a/dir
14571: and a file of ../bob will become /a/bob)
1.191 harris41 14572:
14573: =item *
14574:
14575: hreflocation($dir,$file) : returns file system location or a URL; same as
14576: filelocation except for hrefs
14577:
14578: =item *
14579:
1.1172.2.49 raeburn 14580: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14581: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14582:
1.243 albertel 14583: =back
14584:
1.608 albertel 14585: =head2 Usererfile file routines (/uploaded*)
14586:
14587: =over 4
14588:
14589: =item *
14590:
14591: userfileupload(): main rotine for putting a file in a user or course's
14592: filespace, arguments are,
14593:
1.620 albertel 14594: formname - required - this is the name of the element in $env where the
1.608 albertel 14595: filename, and the contents of the file to create/modifed exist
1.620 albertel 14596: the filename is in $env{'form.'.$formname.'.filename'} and the
14597: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14598: context - if coursedoc, store the file in the course of the active role
14599: of the current user;
14600: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14601: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14602: subdir - required - subdirectory to put the file in under ../userfiles/
14603: if undefined, it will be placed in "unknown"
14604:
14605: (This routine calls clean_filename() to remove any dangerous
14606: characters from the filename, and then calls finuserfileupload() to
14607: complete the transaction)
14608:
14609: returns either the url of the uploaded file (/uploaded/....) if successful
14610: and /adm/notfound.html if unsuccessful
14611:
14612: =item *
14613:
14614: clean_filename(): routine for cleaing a filename up for storage in
14615: userfile space, argument is:
14616:
14617: filename - proposed filename
14618:
14619: returns: the new clean filename
14620:
14621: =item *
14622:
1.1090 raeburn 14623: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14624: userspace, probably shouldn't be called directly
14625:
14626: docuname: username or courseid of destination for the file
14627: docudom: domain of user/course of destination for the file
14628: formname: same as for userfileupload()
1.1090 raeburn 14629: fname: filename (including subdirectories) for the file
14630: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14631: allfiles: reference to hash used to store objects found by parser
14632: codebase: reference to hash used for codebases of java objects found by parser
14633: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14634: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14635: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14636: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14637: context: if 'overwrite', will move the uploaded file from its temporary location to
14638: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14639: mimetype: reference to scalar to accommodate mime type determined
14640: from File::MMagic if $parser = parse.
1.608 albertel 14641:
14642: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14643: and /adm/notfound.html if unsuccessful (or an error message if context
14644: was 'overwrite').
14645:
1.608 albertel 14646:
14647: =item *
14648:
14649: renameuserfile(): renames an existing userfile to a new name
14650:
14651: Args:
14652: docuname: username or courseid of destination for the file
14653: docudom: domain of user/course of destination for the file
14654: old: current file name (including any subdirs under userfiles)
14655: new: desired file name (including any subdirs under userfiles)
14656:
14657: =item *
14658:
14659: mkdiruserfile(): creates a directory is a userfiles dir
14660:
14661: Args:
14662: docuname: username or courseid of destination for the file
14663: docudom: domain of user/course of destination for the file
14664: dir: dir to create (including any subdirs under userfiles)
14665:
14666: =item *
14667:
14668: removeuserfile(): removes a file that exists in userfiles
14669:
14670: Args:
14671: docuname: username or courseid of destination for the file
14672: docudom: domain of user/course of destination for the file
14673: fname: filname to delete (including any subdirs under userfiles)
14674:
14675: =item *
14676:
14677: removeuploadedurl(): convience function for removeuserfile()
14678:
14679: Args:
14680: url: a full /uploaded/... url to delete
14681:
1.747 albertel 14682: =item *
14683:
14684: get_portfile_permissions():
14685: Args:
14686: domain: domain of user or course contain the portfolio files
14687: user: name of user or num of course contain the portfolio files
14688: Returns:
14689: hashref of a dump of the proper file_permissions.db
14690:
14691:
14692: =item *
14693:
14694: get_access_controls():
14695:
14696: Args:
14697: current_permissions: the hash ref returned from get_portfile_permissions()
14698: group: (optional) the group you want the files associated with
14699: file: (optional) the file you want access info on
14700:
14701: Returns:
1.749 raeburn 14702: a hash (keys are file names) of hashes containing
14703: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14704: values are XML containing access control settings (see below)
1.747 albertel 14705:
14706: Internal notes:
14707:
1.749 raeburn 14708: access controls are stored in file_permissions.db as key=value pairs.
14709: key -> path to file/file_name\0uniqueID:scope_end_start
14710: where scope -> public,guest,course,group,domains or users.
14711: end -> UNIX time for end of access (0 -> no end date)
14712: start -> UNIX time for start of access
14713:
14714: value -> XML description of access control
14715: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14716: <start></start>
14717: <end></end>
14718:
14719: <password></password> for scope type = guest
14720:
14721: <domain></domain> for scope type = course or group
14722: <number></number>
14723: <roles id="">
14724: <role></role>
14725: <access></access>
14726: <section></section>
14727: <group></group>
14728: </roles>
14729:
14730: <dom></dom> for scope type = domains
14731:
14732: <users> for scope type = users
14733: <user>
14734: <uname></uname>
14735: <udom></udom>
14736: </user>
14737: </users>
14738: </scope>
14739:
14740: Access data is also aggregated for each file in an additional key=value pair:
14741: key -> path to file/file_name\0accesscontrol
14742: value -> reference to hash
14743: hash contains key = value pairs
14744: where key = uniqueID:scope_end_start
14745: value = UNIX time record was last updated
14746:
14747: Used to improve speed of look-ups of access controls for each file.
14748:
14749: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14750:
1.1172.2.13 raeburn 14751: =item *
14752:
1.749 raeburn 14753: modify_access_controls():
14754:
14755: Modifies access controls for a portfolio file
14756: Args
14757: 1. file name
14758: 2. reference to hash of required changes,
14759: 3. domain
14760: 4. username
14761: where domain,username are the domain of the portfolio owner
14762: (either a user or a course)
14763:
14764: Returns:
14765: 1. result of additions or updates ('ok' or 'error', with error message).
14766: 2. result of deletions ('ok' or 'error', with error message).
14767: 3. reference to hash of any new or updated access controls.
14768: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14769: key = integer (inbound ID)
1.1172.2.13 raeburn 14770: value = uniqueID
14771:
14772: =item *
14773:
14774: get_timebased_id():
14775:
14776: Attempts to get a unique timestamp-based suffix for use with items added to a
14777: course via the Course Editor (e.g., folders, composite pages,
14778: group bulletin boards).
14779:
14780: Args: (first three required; six others optional)
14781:
14782: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14783: docssequence, or name of group
14784:
14785: 2. keyid (alphanumeric): name of temporary locking key in hash,
14786: e.g., num, boardids
14787:
14788: 3. namespace: name of gdbm file used to store suffixes already assigned;
14789: file will be named nohist_namespace.db
14790:
14791: 4. cdom: domain of course; default is current course domain from %env
14792:
14793: 5. cnum: course number; default is current course number from %env
14794:
14795: 6. idtype: set to concat if an additional digit is to be appended to the
14796: unix timestamp to form the suffix, if the plain timestamp is already
14797: in use. Default is to not do this, but simply increment the unix
14798: timestamp by 1 until a unique key is obtained.
14799:
14800: 7. who: holder of locking key; defaults to user:domain for user.
14801:
14802: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14803: retrying); default is 3.
14804:
14805: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14806:
14807: Returns:
14808:
14809: 1. suffix obtained (numeric)
14810:
14811: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14812:
14813: 3. error: contains (localized) error message if an error occurred.
14814:
1.747 albertel 14815:
1.608 albertel 14816: =back
14817:
1.243 albertel 14818: =head2 HTTP Helper Routines
14819:
14820: =over 4
14821:
1.191 harris41 14822: =item *
14823:
14824: escape() : unpack non-word characters into CGI-compatible hex codes
14825:
14826: =item *
14827:
14828: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14829:
1.243 albertel 14830: =back
14831:
14832: =head1 PRIVATE SUBROUTINES
14833:
14834: =head2 Underlying communication routines (Shouldn't call)
14835:
14836: =over 4
14837:
14838: =item *
14839:
14840: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14841:
14842: =item *
14843:
14844: reply() : uses subreply to send a message to remote machine, logs all failures
14845:
14846: =item *
14847:
14848: critical() : passes a critical message to another server; if cannot
14849: get through then place message in connection buffer directory and
14850: returns con_delayed, if incapable of saving message, returns
14851: con_failed
14852:
14853: =item *
14854:
14855: reconlonc() : tries to reconnect lonc client processes.
14856:
14857: =back
14858:
14859: =head2 Resource Access Logging
14860:
14861: =over 4
14862:
14863: =item *
14864:
14865: flushcourselogs() : flush (save) buffer logs and access logs
14866:
14867: =item *
14868:
14869: courselog($what) : save message for course in hash
14870:
14871: =item *
14872:
14873: courseacclog($what) : save message for course using &courselog(). Perform
14874: special processing for specific resource types (problems, exams, quizzes, etc).
14875:
1.191 harris41 14876: =item *
14877:
14878: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14879: as a PerlChildExitHandler
1.243 albertel 14880:
14881: =back
14882:
14883: =head2 Other
14884:
14885: =over 4
14886:
14887: =item *
14888:
14889: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14890:
14891: =back
14892:
14893: =cut
1.877 foxr 14894:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>