Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.93.4.4
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.93.4 4(raebur 4:7): # $Id: lonnet.pm,v 1.1172.2.93.4.3 2017/10/14 21:27:51 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.1172.2.93.4 4(raebur 1844:7): unless ($homeserver eq $perlvar{'lonHostID'}) {
1845:7): if ($srch->{'srchby'} eq 'email') {
1846:7): my $lcrev = &get_server_loncaparev(undef,$homeserver);
1847:7): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
1848:7): if (($major eq '' && $minor eq '') || ($major < 2) ||
1849:7): (($major == 2) && ($minor < 11)) ||
1850:7): (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
1851:7): return;
1852:7): }
1853:7): }
1854:7): }
1.904 albertel 1855: my $queryid=&reply("querysend:instdirsearch:".
1856: &escape($srch->{'srchby'}).':'.
1857: &escape($srch->{'srchterm'}).':'.
1858: &escape($srch->{'srchtype'}),$homeserver);
1859: my $host=&hostname($homeserver);
1860: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.4 1(raebur 1861:7): &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1862: return;
1863: }
1864: my $response = &get_query_reply($queryid);
1865: my $maxtries = 5;
1866: my $tries = 1;
1867: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1868: $response = &get_query_reply($queryid);
1869: $tries ++;
1870: }
1871:
1872: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1873: if ($response eq 'unavailable') {
1874: $outcome = $response;
1875: } else {
1876: $outcome = 'ok';
1877: my @matches = split(/\n/,$response);
1878: foreach my $match (@matches) {
1879: my ($key,$value) = split(/=/,$match);
1880: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1881: }
1.899 raeburn 1882: }
1883: }
1884: }
1.909 raeburn 1885: return ($outcome,%results);
1.899 raeburn 1886: }
1887:
1888: sub usersearch {
1889: my ($srch) = @_;
1890: my $dom = $srch->{'srchdomain'};
1891: my %results;
1892: my %libserv = &all_library();
1893: my $query = 'usersearch';
1894: foreach my $tryserver (keys(%libserv)) {
1895: if (&host_domain($tryserver) eq $dom) {
1.1172.2.93.4 4(raebur 1896:7): unless ($tryserver eq $perlvar{'lonHostID'}) {
1897:7): if ($srch->{'srchby'} eq 'email') {
1898:7): my $lcrev = &get_server_loncaparev(undef,$tryserver);
1899:7): my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.([\w.\-]+)\'?$/);
1900:7): next if (($major eq '' && $minor eq '') || ($major < 2) ||
1901:7): (($major == 2) && ($minor < 11)) ||
1902:7): (($major == 2) && ($minor == 11) && ($subver !~ /^2\.B/))) {
1903:7): }
1904:7): }
1.899 raeburn 1905: my $host=&hostname($tryserver);
1906: my $queryid=
1.911 raeburn 1907: &reply("querysend:".&escape($query).':'.
1908: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1909: &escape($srch->{'srchtype'}).':'.
1910: &escape($srch->{'srchterm'}),$tryserver);
1911: if ($queryid !~/^\Q$host\E\_/) {
1912: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1913: next;
1.899 raeburn 1914: }
1915: my $reply = &get_query_reply($queryid);
1916: my $maxtries = 1;
1917: my $tries = 1;
1918: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1919: $reply = &get_query_reply($queryid);
1920: $tries ++;
1921: }
1922: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1923: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1924: } else {
1.911 raeburn 1925: my @matches;
1926: if ($reply =~ /\n/) {
1927: @matches = split(/\n/,$reply);
1928: } else {
1929: @matches = split(/\&/,$reply);
1930: }
1.899 raeburn 1931: foreach my $match (@matches) {
1932: my ($uname,$udom,%userhash);
1.911 raeburn 1933: foreach my $entry (split(/:/,$match)) {
1934: my ($key,$value) =
1935: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1936: $userhash{$key} = $value;
1937: if ($key eq 'username') {
1938: $uname = $value;
1939: } elsif ($key eq 'domain') {
1940: $udom = $value;
1.911 raeburn 1941: }
1.899 raeburn 1942: }
1943: $results{$uname.':'.$udom} = \%userhash;
1944: }
1945: }
1946: }
1947: }
1948: return %results;
1949: }
1950:
1.912 raeburn 1951: sub get_instuser {
1952: my ($udom,$uname,$id) = @_;
1953: my $homeserver = &domain($udom,'primary');
1954: my ($outcome,%results);
1955: if ($homeserver ne '') {
1956: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1957: &escape($id).':'.&escape($udom),$homeserver);
1958: my $host=&hostname($homeserver);
1959: if ($queryid !~/^\Q$host\E\_/) {
1960: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1961: return;
1962: }
1963: my $response = &get_query_reply($queryid);
1964: my $maxtries = 5;
1965: my $tries = 1;
1966: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1967: $response = &get_query_reply($queryid);
1968: $tries ++;
1969: }
1970: if (!&error($response) && $response ne 'refused') {
1971: if ($response eq 'unavailable') {
1972: $outcome = $response;
1973: } else {
1974: $outcome = 'ok';
1975: my @matches = split(/\n/,$response);
1976: foreach my $match (@matches) {
1977: my ($key,$value) = split(/=/,$match);
1978: $results{&unescape($key)} = &thaw_unescape($value);
1979: }
1980: }
1981: }
1982: }
1983: my %userinfo;
1984: if (ref($results{$uname}) eq 'HASH') {
1985: %userinfo = %{$results{$uname}};
1986: }
1987: return ($outcome,%userinfo);
1988: }
1989:
1.1172.2.69 raeburn 1990: sub get_multiple_instusers {
1991: my ($udom,$users,$caller) = @_;
1992: my ($outcome,$results);
1993: if (ref($users) eq 'HASH') {
1994: my $count = keys(%{$users});
1995: my $requested = &freeze_escape($users);
1996: my $homeserver = &domain($udom,'primary');
1997: if ($homeserver ne '') {
1998: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1999: my $host=&hostname($homeserver);
2000: if ($queryid !~/^\Q$host\E\_/) {
2001: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2002: ' for host: '.$homeserver.'in domain '.$udom);
2003: return ($outcome,$results);
2004: }
2005: my $response = &get_query_reply($queryid);
2006: my $maxtries = 5;
2007: if ($count > 100) {
2008: $maxtries = 1+int($count/20);
2009: }
2010: my $tries = 1;
2011: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2012: $response = &get_query_reply($queryid);
2013: $tries ++;
2014: }
2015: if ($response eq '') {
2016: $results = {};
2017: foreach my $key (keys(%{$users})) {
2018: my ($uname,$id);
2019: if ($caller eq 'id') {
2020: $id = $key;
2021: } else {
2022: $uname = $key;
2023: }
2024: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2025: $outcome = $resp;
2026: if ($resp eq 'ok') {
2027: %{$results} = (%{$results}, %info);
2028: } else {
2029: last;
2030: }
2031: }
2032: } elsif(!&error($response) && ($response ne 'refused')) {
2033: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2034: $outcome = $response;
2035: } else {
2036: ($outcome,my $userdata) = split(/=/,$response,2);
2037: if ($outcome eq 'ok') {
2038: $results = &thaw_unescape($userdata);
2039: }
2040: }
2041: }
2042: }
2043: }
2044: return ($outcome,$results);
2045: }
2046:
1.912 raeburn 2047: sub inst_rulecheck {
1.923 raeburn 2048: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2049: my %returnhash;
2050: if ($udom ne '') {
2051: if (ref($rules) eq 'ARRAY') {
2052: @{$rules} = map {&escape($_);} (@{$rules});
2053: my $rulestr = join(':',@{$rules});
2054: my $homeserver=&domain($udom,'primary');
2055: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2056: my $response;
2057: if ($item eq 'username') {
2058: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2059: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2060: $homeserver));
1.923 raeburn 2061: } elsif ($item eq 'id') {
2062: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2063: ':'.&escape($id).':'.$rulestr,
2064: $homeserver));
1.945 raeburn 2065: } elsif ($item eq 'selfcreate') {
2066: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2067: &escape($udom).':'.&escape($uname).
2068: ':'.$rulestr,$homeserver));
1.923 raeburn 2069: }
1.912 raeburn 2070: if ($response ne 'refused') {
2071: my @pairs=split(/\&/,$response);
2072: foreach my $item (@pairs) {
2073: my ($key,$value)=split(/=/,$item,2);
2074: $key = &unescape($key);
2075: next if ($key =~ /^error: 2 /);
2076: $returnhash{$key}=&thaw_unescape($value);
2077: }
2078: }
2079: }
2080: }
2081: }
2082: return %returnhash;
2083: }
2084:
2085: sub inst_userrules {
1.923 raeburn 2086: my ($udom,$check) = @_;
1.912 raeburn 2087: my (%ruleshash,@ruleorder);
2088: if ($udom ne '') {
2089: my $homeserver=&domain($udom,'primary');
2090: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2091: my $response;
2092: if ($check eq 'id') {
2093: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2094: $homeserver);
1.943 raeburn 2095: } elsif ($check eq 'email') {
2096: $response=&reply('instemailrules:'.&escape($udom),
2097: $homeserver);
1.923 raeburn 2098: } else {
2099: $response=&reply('instuserrules:'.&escape($udom),
2100: $homeserver);
2101: }
1.912 raeburn 2102: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2103: ($response ne 'unknown_cmd') &&
1.912 raeburn 2104: ($response ne 'no_such_host')) {
2105: my ($hashitems,$orderitems) = split(/:/,$response);
2106: my @pairs=split(/\&/,$hashitems);
2107: foreach my $item (@pairs) {
2108: my ($key,$value)=split(/=/,$item,2);
2109: $key = &unescape($key);
2110: next if ($key =~ /^error: 2 /);
2111: $ruleshash{$key}=&thaw_unescape($value);
2112: }
2113: my @esc_order = split(/\&/,$orderitems);
2114: foreach my $item (@esc_order) {
2115: push(@ruleorder,&unescape($item));
2116: }
2117: }
2118: }
2119: }
2120: return (\%ruleshash,\@ruleorder);
2121: }
2122:
1.976 raeburn 2123: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2124:
2125: sub get_domain_defaults {
1.1172.2.35 raeburn 2126: my ($domain,$ignore_cache) = @_;
2127: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2128: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2129: unless ($ignore_cache) {
2130: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2131: if (defined($cached)) {
2132: if (ref($result) eq 'HASH') {
2133: return %{$result};
2134: }
1.943 raeburn 2135: }
2136: }
2137: my %domdefaults;
2138: my %domconfig =
1.989 raeburn 2139: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2140: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2141: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2142: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2143: 'coursecategories','autoenroll',
2144: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2145: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2146: if (ref($domconfig{'defaults'}) eq 'HASH') {
2147: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2148: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2149: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2150: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2151: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2152: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2153: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2154: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2155: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2156: } else {
2157: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2158: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2159: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2160: }
1.976 raeburn 2161: if (ref($domconfig{'quotas'}) eq 'HASH') {
2162: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2163: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2164: } else {
2165: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2166: }
1.1172.2.6 raeburn 2167: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2168: foreach my $item (@usertools) {
2169: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2170: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2171: }
2172: }
1.1172.2.29 raeburn 2173: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2174: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2175: }
1.976 raeburn 2176: }
1.985 raeburn 2177: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2178: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2179: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2180: }
2181: }
1.1172.2.9 raeburn 2182: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2183: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2184: }
1.989 raeburn 2185: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2186: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2187: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2188: }
2189: }
1.1047 raeburn 2190: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2191: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2192: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2193: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2194: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2195: }
1.1172.2.41 raeburn 2196: foreach my $type (@coursetypes) {
2197: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2198: unless ($type eq 'community') {
2199: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2200: }
2201: }
2202: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2203: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2204: }
1.1172.2.60 raeburn 2205: if ($domdefaults{'postsubmit'} eq 'on') {
2206: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2207: $domdefaults{$type.'postsubtimeout'} =
2208: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2209: }
2210: }
1.1172.2.30 raeburn 2211: }
1.1172.2.67 raeburn 2212: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2213: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2214: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2215: if (@clonecodes) {
2216: $domdefaults{'canclone'} = join('+',@clonecodes);
2217: }
2218: }
2219: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2220: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2221: }
1.1047 raeburn 2222: }
1.1073 raeburn 2223: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2224: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2225: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2226: }
2227: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2228: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2229: }
1.1172.2.62 raeburn 2230: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2231: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2232: }
1.1073 raeburn 2233: }
1.1172.2.41 raeburn 2234: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2235: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2236: my @settings = ('types','registered','enroll_dates','access_dates','section',
2237: 'approval','limit');
2238: foreach my $type (@coursetypes) {
2239: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2240: my @mgrdc = ();
2241: foreach my $item (@settings) {
2242: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2243: push(@mgrdc,$item);
2244: }
2245: }
2246: if (@mgrdc) {
2247: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2248: }
2249: }
2250: }
2251: }
2252: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2253: foreach my $type (@coursetypes) {
2254: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2255: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2256: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2257: }
2258: }
2259: }
2260: }
2261: }
1.1172.2.46 raeburn 2262: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2263: $domdefaults{'catauth'} = 'std';
2264: $domdefaults{'catunauth'} = 'std';
2265: if ($domconfig{'coursecategories'}{'auth'}) {
2266: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2267: }
2268: if ($domconfig{'coursecategories'}{'unauth'}) {
2269: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2270: }
2271: }
1.1172.2.76 raeburn 2272: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2273: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2274: }
1.1172.2.89 raeburn 2275: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2276: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2277: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2278: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2279: }
2280: }
1.1172.2.23 raeburn 2281: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2282: return %domdefaults;
2283: }
2284:
1.1172.2.93.4 2(raebur 2285:7): sub course_portal_url {
2286:7): my ($cnum,$cdom) = @_;
2287:7): my $chome = &homeserver($cnum,$cdom);
2288:7): my $hostname = &hostname($chome);
2289:7): my $protocol = $protocol{$chome};
2290:7): $protocol = 'http' if ($protocol ne 'https');
2291:7): my %domdefaults = &get_domain_defaults($cdom);
2292:7): my $firsturl;
2293:7): if ($domdefaults{'portal_def'}) {
2294:7): $firsturl = $domdefaults{'portal_def'};
2295:7): } else {
2296:7): $firsturl = $protocol.'://'.$hostname;
2297:7): }
2298:7): return $firsturl;
2299:7): }
2300:7):
1.344 www 2301: # --------------------------------------------------- Assign a key to a student
2302:
2303: sub assign_access_key {
1.364 www 2304: #
2305: # a valid key looks like uname:udom#comments
2306: # comments are being appended
2307: #
1.498 www 2308: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2309: $kdom=
1.620 albertel 2310: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2311: $knum=
1.620 albertel 2312: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2313: $cdom=
1.620 albertel 2314: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2315: $cnum=
1.620 albertel 2316: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2317: $udom=$env{'user.name'} unless (defined($udom));
2318: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2319: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2320: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2321: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2322: # assigned to this person
2323: # - this should not happen,
1.345 www 2324: # unless something went wrong
2325: # the first time around
2326: # ready to assign
1.364 www 2327: $logentry=$1.'; '.$logentry;
1.496 www 2328: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2329: $kdom,$knum) eq 'ok') {
1.345 www 2330: # key now belongs to user
1.346 www 2331: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2332: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2333: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2334: return 'ok';
2335: } else {
2336: return
2337: 'error: Count not permanently assign key, will need to be re-entered later.';
2338: }
2339: } else {
2340: return 'error: Could not assign key, try again later.';
2341: }
1.364 www 2342: } elsif (!$existing{$ckey}) {
1.345 www 2343: # the key does not exist
2344: return 'error: The key does not exist';
2345: } else {
2346: # the key is somebody else's
2347: return 'error: The key is already in use';
2348: }
1.344 www 2349: }
2350:
1.364 www 2351: # ------------------------------------------ put an additional comment on a key
2352:
2353: sub comment_access_key {
2354: #
2355: # a valid key looks like uname:udom#comments
2356: # comments are being appended
2357: #
2358: my ($ckey,$cdom,$cnum,$logentry)=@_;
2359: $cdom=
1.620 albertel 2360: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2361: $cnum=
1.620 albertel 2362: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2363: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2364: if ($existing{$ckey}) {
2365: $existing{$ckey}.='; '.$logentry;
2366: # ready to assign
1.367 www 2367: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2368: $cdom,$cnum) eq 'ok') {
2369: return 'ok';
2370: } else {
2371: return 'error: Count not store comment.';
2372: }
2373: } else {
2374: # the key does not exist
2375: return 'error: The key does not exist';
2376: }
2377: }
2378:
1.344 www 2379: # ------------------------------------------------------ Generate a set of keys
2380:
2381: sub generate_access_keys {
1.364 www 2382: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2383: $cdom=
1.620 albertel 2384: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2385: $cnum=
1.620 albertel 2386: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2387: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2388: unless (($cdom) && ($cnum)) { return 0; }
2389: if ($number>10000) { return 0; }
2390: sleep(2); # make sure don't get same seed twice
2391: srand(time()^($$+($$<<15))); # from "Programming Perl"
2392: my $total=0;
2393: for (my $i=1;$i<=$number;$i++) {
2394: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2395: sprintf("%lx",int(100000*rand)).'-'.
2396: sprintf("%lx",int(100000*rand));
2397: $newkey=~s/1/g/g; # folks mix up 1 and l
2398: $newkey=~s/0/h/g; # and also 0 and O
2399: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2400: if ($existing{$newkey}) {
2401: $i--;
2402: } else {
1.364 www 2403: if (&put('accesskeys',
2404: { $newkey => '# generated '.localtime().
1.620 albertel 2405: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2406: '; '.$logentry },
2407: $cdom,$cnum) eq 'ok') {
1.344 www 2408: $total++;
2409: }
2410: }
2411: }
1.620 albertel 2412: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2413: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2414: return $total;
2415: }
2416:
2417: # ------------------------------------------------------- Validate an accesskey
2418:
2419: sub validate_access_key {
2420: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2421: $cdom=
1.620 albertel 2422: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2423: $cnum=
1.620 albertel 2424: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2425: $udom=$env{'user.domain'} unless (defined($udom));
2426: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2427: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2428: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2429: }
2430:
2431: # ------------------------------------- Find the section of student in a course
1.652 albertel 2432: sub devalidate_getsection_cache {
2433: my ($udom,$unam,$courseid)=@_;
2434: my $hashid="$udom:$unam:$courseid";
2435: &devalidate_cache_new('getsection',$hashid);
2436: }
1.298 matthew 2437:
1.815 albertel 2438: sub courseid_to_courseurl {
2439: my ($courseid) = @_;
2440: #already url style courseid
2441: return $courseid if ($courseid =~ m{^/});
2442:
2443: if (exists($env{'course.'.$courseid.'.num'})) {
2444: my $cnum = $env{'course.'.$courseid.'.num'};
2445: my $cdom = $env{'course.'.$courseid.'.domain'};
2446: return "/$cdom/$cnum";
2447: }
2448:
2449: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2450: if (exists($courseinfo{'num'})) {
2451: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2452: }
2453:
2454: return undef;
2455: }
2456:
1.298 matthew 2457: sub getsection {
2458: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2459: my $cachetime=1800;
1.551 albertel 2460:
2461: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2462: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2463: if (defined($cached)) { return $result; }
2464:
1.298 matthew 2465: my %Pending;
2466: my %Expired;
2467: #
2468: # Each role can either have not started yet (pending), be active,
2469: # or have expired.
2470: #
2471: # If there is an active role, we are done.
2472: #
2473: # If there is more than one role which has not started yet,
2474: # choose the one which will start sooner
2475: # If there is one role which has not started yet, return it.
2476: #
2477: # If there is more than one expired role, choose the one which ended last.
2478: # If there is a role which has expired, return it.
2479: #
1.815 albertel 2480: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2481: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2482: foreach my $key (keys(%roleshash)) {
1.479 albertel 2483: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2484: my $section=$1;
2485: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2486: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2487: my $now=time;
1.548 albertel 2488: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2489: $Expired{$end}=$section;
2490: next;
2491: }
1.548 albertel 2492: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2493: $Pending{$start}=$section;
2494: next;
2495: }
1.599 albertel 2496: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2497: }
2498: #
2499: # Presumedly there will be few matching roles from the above
2500: # loop and the sorting time will be negligible.
2501: if (scalar(keys(%Pending))) {
2502: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2503: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2504: }
2505: if (scalar(keys(%Expired))) {
2506: my @sorted = sort {$a <=> $b} keys(%Expired);
2507: my $time = pop(@sorted);
1.599 albertel 2508: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2509: }
1.599 albertel 2510: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2511: }
1.70 www 2512:
1.599 albertel 2513: sub save_cache {
2514: &purge_remembered();
1.722 albertel 2515: #&Apache::loncommon::validate_page();
1.620 albertel 2516: undef(%env);
1.780 albertel 2517: undef($env_loaded);
1.599 albertel 2518: }
1.452 albertel 2519:
1.599 albertel 2520: my $to_remember=-1;
2521: my %remembered;
2522: my %accessed;
2523: my $kicks=0;
2524: my $hits=0;
1.849 albertel 2525: sub make_key {
2526: my ($name,$id) = @_;
1.872 albertel 2527: if (length($id) > 65
2528: && length(&escape($id)) > 200) {
2529: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2530: }
1.849 albertel 2531: return &escape($name.':'.$id);
2532: }
2533:
1.599 albertel 2534: sub devalidate_cache_new {
2535: my ($name,$id,$debug) = @_;
2536: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2537: my $remembered_id=$name.':'.$id;
1.849 albertel 2538: $id=&make_key($name,$id);
1.599 albertel 2539: $memcache->delete($id);
1.1172.2.81 raeburn 2540: delete($remembered{$remembered_id});
2541: delete($accessed{$remembered_id});
1.599 albertel 2542: }
2543:
2544: sub is_cached_new {
2545: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2546: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2547: # keys in %remembered hash, which persists for
2548: # duration of request (no restriction on key length).
2549: if (exists($remembered{$remembered_id})) {
2550: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2551: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2552: $hits++;
1.1172.2.81 raeburn 2553: return ($remembered{$remembered_id},1);
1.599 albertel 2554: }
1.1172.2.81 raeburn 2555: $id=&make_key($name,$id);
1.599 albertel 2556: my $value = $memcache->get($id);
2557: if (!(defined($value))) {
2558: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2559: return (undef,undef);
1.416 albertel 2560: }
1.599 albertel 2561: if ($value eq '__undef__') {
2562: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2563: $value=undef;
2564: }
1.1172.2.81 raeburn 2565: &make_room($remembered_id,$value,$debug);
1.599 albertel 2566: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2567: return ($value,1);
2568: }
2569:
2570: sub do_cache_new {
2571: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2572: my $remembered_id=$name.':'.$id;
1.849 albertel 2573: $id=&make_key($name,$id);
1.599 albertel 2574: my $setvalue=$value;
2575: if (!defined($setvalue)) {
2576: $setvalue='__undef__';
2577: }
1.623 albertel 2578: if (!defined($time) ) {
2579: $time=600;
2580: }
1.599 albertel 2581: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2582: my $result = $memcache->set($id,$setvalue,$time);
2583: if (! $result) {
1.872 albertel 2584: &logthis("caching of id -> $id failed");
1.910 albertel 2585: $memcache->disconnect_all();
1.872 albertel 2586: }
1.600 albertel 2587: # need to make a copy of $value
1.1172.2.81 raeburn 2588: &make_room($remembered_id,$value,$debug);
1.599 albertel 2589: return $value;
2590: }
2591:
2592: sub make_room {
1.1172.2.81 raeburn 2593: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2594:
1.1172.2.81 raeburn 2595: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2596: : $value;
1.599 albertel 2597: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2598: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2599: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2600: my $to_kick;
2601: my $max_time=0;
2602: foreach my $other (keys(%accessed)) {
2603: if (&tv_interval($accessed{$other}) > $max_time) {
2604: $to_kick=$other;
2605: $max_time=&tv_interval($accessed{$other});
2606: }
2607: }
2608: delete($remembered{$to_kick});
2609: delete($accessed{$to_kick});
2610: $kicks++;
2611: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2612: return;
2613: }
2614:
1.599 albertel 2615: sub purge_remembered {
1.604 albertel 2616: #&logthis("Tossing ".scalar(keys(%remembered)));
2617: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2618: undef(%remembered);
2619: undef(%accessed);
1.428 albertel 2620: }
1.70 www 2621: # ------------------------------------- Read an entry from a user's environment
2622:
2623: sub userenvironment {
2624: my ($udom,$unam,@what)=@_;
1.976 raeburn 2625: my $items;
2626: foreach my $item (@what) {
2627: $items.=&escape($item).'&';
2628: }
2629: $items=~s/\&$//;
1.70 www 2630: my %returnhash=();
1.1009 raeburn 2631: my $uhome = &homeserver($unam,$udom);
2632: unless ($uhome eq 'no_host') {
2633: my @answer=split(/\&/,
2634: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2635: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2636: return %returnhash;
2637: }
1.1009 raeburn 2638: my $i;
2639: for ($i=0;$i<=$#what;$i++) {
2640: $returnhash{$what[$i]}=&unescape($answer[$i]);
2641: }
1.70 www 2642: }
2643: return %returnhash;
1.1 albertel 2644: }
2645:
1.617 albertel 2646: # ---------------------------------------------------------- Get a studentphoto
2647: sub studentphoto {
2648: my ($udom,$unam,$ext) = @_;
2649: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2650: if (defined($env{'request.course.id'})) {
1.708 raeburn 2651: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2652: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2653: return(&retrievestudentphoto($udom,$unam,$ext));
2654: } else {
2655: my ($result,$perm_reqd)=
1.707 albertel 2656: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2657: if ($result eq 'ok') {
2658: if (!($perm_reqd eq 'yes')) {
2659: return(&retrievestudentphoto($udom,$unam,$ext));
2660: }
2661: }
2662: }
2663: }
2664: } else {
2665: my ($result,$perm_reqd) =
1.707 albertel 2666: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2667: if ($result eq 'ok') {
2668: if (!($perm_reqd eq 'yes')) {
2669: return(&retrievestudentphoto($udom,$unam,$ext));
2670: }
2671: }
2672: }
2673: return '/adm/lonKaputt/lonlogo_broken.gif';
2674: }
2675:
2676: sub retrievestudentphoto {
2677: my ($udom,$unam,$ext,$type) = @_;
2678: my $home=&Apache::lonnet::homeserver($unam,$udom);
2679: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2680: if ($ret eq 'ok') {
2681: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2682: if ($type eq 'thumbnail') {
2683: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2684: }
2685: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2686: return $tokenurl;
2687: } else {
2688: if ($type eq 'thumbnail') {
2689: return '/adm/lonKaputt/genericstudent_tn.gif';
2690: } else {
2691: return '/adm/lonKaputt/lonlogo_broken.gif';
2692: }
1.617 albertel 2693: }
2694: }
2695:
1.263 www 2696: # -------------------------------------------------------------------- New chat
2697:
2698: sub chatsend {
1.724 raeburn 2699: my ($newentry,$anon,$group)=@_;
1.620 albertel 2700: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2701: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2702: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2703: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2704: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2705: &escape($newentry)).':'.$group,$chome);
1.292 www 2706: }
2707:
2708: # ------------------------------------------ Find current version of a resource
2709:
2710: sub getversion {
2711: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2712: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2713: return ¤tversion(&filelocation('',$fname));
2714: }
2715:
2716: sub currentversion {
2717: my $fname=shift;
2718: my $author=$fname;
2719: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2720: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2721: my $home=&homeserver($uname,$udom);
1.292 www 2722: if ($home eq 'no_host') {
2723: return -1;
2724: }
1.1112 www 2725: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2726: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2727: return -1;
2728: }
1.1112 www 2729: return $answer;
1.263 www 2730: }
2731:
1.1111 www 2732: #
2733: # Return special version number of resource if set by override, empty otherwise
2734: #
2735: sub usedversion {
2736: my $fname=shift;
2737: unless ($fname) { $fname=$env{'request.uri'}; }
2738: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2739: if ($urlversion) { return $urlversion; }
2740: return '';
2741: }
2742:
1.1 albertel 2743: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2744:
1.1 albertel 2745: sub subscribe {
2746: my $fname=shift;
1.761 raeburn 2747: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2748: $fname=~s/[\n\r]//g;
1.1 albertel 2749: my $author=$fname;
2750: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2751: my ($udom,$uname)=split(/\//,$author);
2752: my $home=homeserver($uname,$udom);
1.335 albertel 2753: if ($home eq 'no_host') {
2754: return 'not_found';
1.1 albertel 2755: }
2756: my $answer=reply("sub:$fname",$home);
1.64 www 2757: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2758: $answer.=' by '.$home;
2759: }
1.1 albertel 2760: return $answer;
2761: }
2762:
1.8 www 2763: # -------------------------------------------------------------- Replicate file
2764:
2765: sub repcopy {
2766: my $filename=shift;
1.23 www 2767: $filename=~s/\/+/\//g;
1.1142 raeburn 2768: my $londocroot = $perlvar{'lonDocRoot'};
2769: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2770: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2771: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2772: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2773: return &repcopy_userfile($filename);
2774: }
1.532 albertel 2775: $filename=~s/[\n\r]//g;
1.8 www 2776: my $transname="$filename.in.transfer";
1.828 www 2777: # FIXME: this should flock
1.607 raeburn 2778: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2779: my $remoteurl=subscribe($filename);
1.64 www 2780: if ($remoteurl =~ /^con_lost by/) {
2781: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2782: return 'unavailable';
1.8 www 2783: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2784: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2785: return 'not_found';
1.64 www 2786: } elsif ($remoteurl =~ /^rejected by/) {
2787: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2788: return 'forbidden';
1.20 www 2789: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2790: return 'ok';
1.8 www 2791: } else {
1.290 www 2792: my $author=$filename;
2793: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2794: my ($udom,$uname)=split(/\//,$author);
2795: my $home=homeserver($uname,$udom);
2796: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2797: my @parts=split(/\//,$filename);
2798: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2799: if ($path ne "$londocroot/res") {
1.8 www 2800: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2801: return 'bad_request';
1.8 www 2802: }
2803: my $count;
2804: for ($count=5;$count<$#parts;$count++) {
2805: $path.="/$parts[$count]";
2806: if ((-e $path)!=1) {
2807: mkdir($path,0777);
2808: }
2809: }
2810: my $ua=new LWP::UserAgent;
2811: my $request=new HTTP::Request('GET',"$remoteurl");
2812: my $response=$ua->request($request,$transname);
2813: if ($response->is_error()) {
2814: unlink($transname);
2815: my $message=$response->status_line;
1.672 albertel 2816: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2817: ." LWP get: $message: $filename</font>");
1.607 raeburn 2818: return 'unavailable';
1.8 www 2819: } else {
1.16 www 2820: if ($remoteurl!~/\.meta$/) {
2821: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2822: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2823: if ($mresponse->is_error()) {
2824: unlink($filename.'.meta');
2825: &logthis(
1.672 albertel 2826: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2827: }
2828: }
1.8 www 2829: rename($transname,$filename);
1.607 raeburn 2830: return 'ok';
1.8 www 2831: }
1.290 www 2832: }
1.8 www 2833: }
1.330 www 2834: }
2835:
2836: # ------------------------------------------------ Get server side include body
2837: sub ssi_body {
1.381 albertel 2838: my ($filelink,%form)=@_;
1.606 matthew 2839: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2840: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2841: }
1.953 www 2842: my $output='';
2843: my $response;
1.980 raeburn 2844: if ($filelink=~/^https?\:/) {
1.954 raeburn 2845: ($output,$response)=&externalssi($filelink);
1.953 www 2846: } else {
1.1004 droeschl 2847: $filelink .= $filelink=~/\?/ ? '&' : '?';
2848: $filelink .= 'inhibitmenu=yes';
1.953 www 2849: ($output,$response)=&ssi($filelink,%form);
2850: }
1.778 albertel 2851: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2852: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2853: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2854: if (wantarray) {
2855: return ($output, $response);
2856: } else {
2857: return $output;
2858: }
1.8 www 2859: }
2860:
1.15 www 2861: # --------------------------------------------------------- Server Side Include
2862:
1.782 albertel 2863: sub absolute_url {
2864: my ($host_name) = @_;
2865: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2866: if ($host_name eq '') {
2867: $host_name = $ENV{'SERVER_NAME'};
2868: }
2869: return $protocol.$host_name;
2870: }
2871:
1.942 foxr 2872: #
2873: # Server side include.
2874: # Parameters:
2875: # fn Possibly encrypted resource name/id.
2876: # form Hash that describes how the rendering should be done
2877: # and other things.
1.944 foxr 2878: # Returns:
1.950 raeburn 2879: # Scalar context: The content of the response.
2880: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2881: #
1.15 www 2882: sub ssi {
2883:
1.944 foxr 2884: my ($fn,%form)=@_;
1.15 www 2885: my $ua=new LWP::UserAgent;
1.23 www 2886: my $request;
1.711 albertel 2887:
2888: $form{'no_update_last_known'}=1;
1.895 albertel 2889: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2890: if (%form) {
1.782 albertel 2891: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2892: $request->content(join('&',map {
2893: my $name = escape($_);
2894: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2895: ? join("&$name=", map {escape($_) } @{$form{$_}})
2896: : &escape($form{$_}) );
2897: } keys(%form)));
1.23 www 2898: } else {
1.782 albertel 2899: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2900: }
2901:
1.15 www 2902: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2903: my $response= $ua->request($request);
1.944 foxr 2904: if (wantarray) {
1.1172.2.3 raeburn 2905: return ($response->content, $response);
1.944 foxr 2906: } else {
1.1172.2.3 raeburn 2907: return $response->content;
1.942 foxr 2908: }
1.324 www 2909: }
2910:
2911: sub externalssi {
2912: my ($url)=@_;
2913: my $ua=new LWP::UserAgent;
2914: my $request=new HTTP::Request('GET',$url);
2915: my $response=$ua->request($request);
1.954 raeburn 2916: if (wantarray) {
2917: return ($response->content, $response);
2918: } else {
2919: return $response->content;
2920: }
1.15 www 2921: }
1.254 www 2922:
1.492 albertel 2923: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2924:
2925: sub allowuploaded {
2926: my ($srcurl,$url)=@_;
2927: $url=&clutter(&declutter($url));
2928: my $dir=$url;
2929: $dir=~s/\/[^\/]+$//;
2930: my %httpref=();
2931: my $httpurl=&hreflocation('',$url);
2932: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2933: &Apache::lonnet::appenv(\%httpref);
1.254 www 2934: }
1.477 raeburn 2935:
1.1172.2.13 raeburn 2936: #
2937: # Determine if the current user should be able to edit a particular resource,
2938: # when viewing in course context.
2939: # (a) When viewing resource used to determine if "Edit" item is included in
2940: # Functions.
2941: # (b) When displaying folder contents in course editor, used to determine if
2942: # "Edit" link will be displayed alongside resource.
2943: #
2944: # input: six args -- filename (decluttered), course number, course domain,
2945: # url, symb (if registered) and group (if this is a group
2946: # item -- e.g., bulletin board, group page etc.).
2947: # output: array of five scalars --
2948: # $cfile -- url for file editing if editable on current server
2949: # $home -- homeserver of resource (i.e., for author if published,
2950: # or course if uploaded.).
2951: # $switchserver -- 1 if server switch will be needed.
2952: # $forceedit -- 1 if icon/link should be to go to edit mode
2953: # $forceview -- 1 if icon/link should be to go to view mode
2954: #
2955:
2956: sub can_edit_resource {
2957: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2958: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2959: #
2960: # For aboutme pages user can only edit his/her own.
2961: #
2962: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2963: my ($sdom,$sname) = ($1,$2);
2964: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2965: $home = $env{'user.home'};
2966: $cfile = $resurl;
2967: if ($env{'form.forceedit'}) {
2968: $forceview = 1;
2969: } else {
2970: $forceedit = 1;
2971: }
2972: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2973: } else {
2974: return;
2975: }
2976: }
2977:
2978: if ($env{'request.course.id'}) {
2979: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2980: if ($group ne '') {
2981: # if this is a group homepage or group bulletin board, check group privs
2982: my $allowed = 0;
2983: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2984: if ((&allowed('mdg',$env{'request.course.id'}.
2985: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2986: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2987: $allowed = 1;
2988: }
2989: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2990: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2991: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2992: $allowed = 1;
2993: }
2994: }
2995: if ($allowed) {
2996: $home=&homeserver($cnum,$cdom);
2997: if ($env{'form.forceedit'}) {
2998: $forceview = 1;
2999: } else {
3000: $forceedit = 1;
3001: }
3002: $cfile = $resurl;
3003: } else {
3004: return;
3005: }
3006: } else {
1.1172.2.15 raeburn 3007: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3008: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3009: return;
3010: }
3011: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3012: #
3013: # No edit allowed where CC has switched to student role.
3014: #
3015: return;
3016: }
3017: }
3018: }
3019:
3020: if ($file ne '') {
3021: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3022: if (&is_course_upload($file,$cnum,$cdom)) {
3023: $uploaded = 1;
3024: $incourse = 1;
3025: if ($file =~/\.(htm|html|css|js|txt)$/) {
3026: $cfile = &hreflocation('',$file);
3027: if ($env{'form.forceedit'}) {
3028: $forceview = 1;
3029: } else {
3030: $forceedit = 1;
3031: }
3032: }
3033: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3034: $incourse = 1;
3035: if ($env{'form.forceedit'}) {
3036: $forceview = 1;
3037: } else {
3038: $forceedit = 1;
3039: }
3040: $cfile = $resurl;
3041: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3042: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3043: $incourse = 1;
3044: if ($env{'form.forceedit'}) {
3045: $forceview = 1;
3046: } else {
3047: $forceedit = 1;
3048: }
3049: $cfile = $resurl;
3050: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3051: $incourse = 1;
3052: $cfile = $resurl.'/smpedit';
3053: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3054: $incourse = 1;
3055: if ($env{'form.forceedit'}) {
3056: $forceview = 1;
3057: } else {
3058: $forceedit = 1;
3059: }
3060: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3061:7): } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3062:7): $incourse = 1;
3063:7): if ($env{'form.forceedit'}) {
3064:7): $forceview = 1;
3065:7): } else {
3066:7): $forceedit = 1;
3067:7): }
3068:7): $cfile = $resurl;
1.1172.2.15 raeburn 3069: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3070: $incourse = 1;
3071: if ($env{'form.forceedit'}) {
3072: $forceview = 1;
3073: } else {
3074: $forceedit = 1;
3075: }
3076: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3077: }
3078: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3079: my $template = '/res/lib/templates/simpleproblem.problem';
3080: if (&is_on_map($template)) {
3081: $incourse = 1;
3082: $forceview = 1;
3083: $cfile = $template;
3084: }
3085: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3086: $incourse = 1;
3087: if ($env{'form.forceedit'}) {
3088: $forceview = 1;
3089: } else {
3090: $forceedit = 1;
3091: }
3092: $cfile = $resurl;
1.1172.2.93.4 2(raebur 3093:7): } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3094:7): $incourse = 1;
3095:7): if ($env{'form.forceedit'}) {
3096:7): $forceview = 1;
3097:7): } else {
3098:7): $forceedit = 1;
3099:7): }
3100:7): $cfile = $resurl;
1.1172.2.13 raeburn 3101: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3102: $incourse = 1;
3103: $forceview = 1;
3104: if ($symb) {
3105: my ($map,$id,$res)=&decode_symb($symb);
3106: $env{'request.symb'} = $symb;
3107: $cfile = &clutter($res);
3108: } else {
3109: $cfile = $env{'form.suppurl'};
1.1172.2.93.4 1(raebur 3110:7): my $escfile = &unescape($cfile);
2(raebur 3111:7): if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
3112:7): $cfile = '/adm/wrapper'.$escfile;
3113:7): } else {
3114:7): $escfile =~ s{^http://}{};
3115:7): $cfile = &escape("/adm/wrapper/ext/$escfile");
3116:7): }
1.1172.2.13 raeburn 3117: }
1.1172.2.31 raeburn 3118: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3119: if ($env{'form.forceedit'}) {
3120: $forceview = 1;
3121: } else {
3122: $forceedit = 1;
3123: }
3124: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3125: }
3126: }
3127: if ($uploaded || $incourse) {
3128: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3129: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3130: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3131: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3132: # Check that the user has permission to edit this resource
3133: my $setpriv = 1;
3134: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3135: if (defined($cfudom)) {
3136: $home=&homeserver($cfuname,$cfudom);
3137: $cfile=$file;
3138: }
3139: }
3140: if (($cfile ne '') && (!$incourse || $uploaded) &&
3141: (($home ne '') && ($home ne 'no_host'))) {
3142: my @ids=¤t_machine_ids();
3143: unless (grep(/^\Q$home\E$/,@ids)) {
3144: $switchserver=1;
3145: }
3146: }
3147: }
3148: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3149: }
3150:
3151: sub is_course_upload {
3152: my ($file,$cnum,$cdom) = @_;
3153: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3154: $uploadpath =~ s{^\/}{};
3155: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3156: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3157: return 1;
3158: }
3159: return;
3160: }
3161:
3162: sub in_course {
3163: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3164: if ($hideprivileged) {
3165: my $skipuser;
1.1172.2.23 raeburn 3166: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3167: my @possdoms = ($cdom);
3168: if ($coursehash{'checkforpriv'}) {
3169: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3170: }
3171: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3172: $skipuser = 1;
3173: if ($coursehash{'nothideprivileged'}) {
3174: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3175: my $user;
3176: if ($item =~ /:/) {
3177: $user = $item;
3178: } else {
3179: $user = join(':',split(/[\@]/,$item));
3180: }
3181: if ($user eq $uname.':'.$udom) {
3182: undef($skipuser);
3183: last;
3184: }
3185: }
3186: }
3187: if ($skipuser) {
3188: return 0;
3189: }
3190: }
3191: }
3192: $type ||= 'any';
3193: if (!defined($cdom) || !defined($cnum)) {
3194: my $cid = $env{'request.course.id'};
3195: $cdom = $env{'course.'.$cid.'.domain'};
3196: $cnum = $env{'course.'.$cid.'.num'};
3197: }
3198: my $typesref;
3199: if (($type eq 'any') || ($type eq 'all')) {
3200: $typesref = ['active','previous','future'];
3201: } elsif ($type eq 'previous' || $type eq 'future') {
3202: $typesref = [$type];
3203: }
3204: my %roles = &get_my_roles($uname,$udom,'userroles',
3205: $typesref,undef,[$cdom]);
3206: my ($tmp) = keys(%roles);
3207: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3208: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3209: if (@course_roles > 0) {
3210: return 1;
3211: }
3212: return 0;
3213: }
3214:
1.478 albertel 3215: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3216: # input: action, courseID, current domain, intended
1.637 raeburn 3217: # path to file, source of file, instruction to parse file for objects,
3218: # ref to hash for embedded objects,
3219: # ref to hash for codebase of java objects.
1.1095 raeburn 3220: # reference to scalar to accommodate mime type determined
3221: # from File::MMagic if $parser = parse.
1.637 raeburn 3222: #
1.485 raeburn 3223: # output: url to file (if action was uploaddoc),
3224: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3225: #
1.478 albertel 3226: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3227: # course.
1.477 raeburn 3228: #
1.478 albertel 3229: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3230: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3231: # course's home server.
1.477 raeburn 3232: #
1.478 albertel 3233: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3234: # be copied from $source (current location) to
3235: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3236: # and will then be copied to
3237: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3238: # course's home server.
1.485 raeburn 3239: #
1.481 raeburn 3240: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3241: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3242: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3243: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3244: # in course's home server.
1.637 raeburn 3245: #
1.477 raeburn 3246:
3247: sub process_coursefile {
1.1095 raeburn 3248: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3249: $mimetype)=@_;
1.477 raeburn 3250: my $fetchresult;
1.638 albertel 3251: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3252: if ($action eq 'propagate') {
1.638 albertel 3253: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3254: $home);
1.481 raeburn 3255: } else {
1.477 raeburn 3256: my $fpath = '';
3257: my $fname = $file;
1.478 albertel 3258: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3259: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3260: my $filepath = &build_filepath($fpath);
1.481 raeburn 3261: if ($action eq 'copy') {
3262: if ($source eq '') {
3263: $fetchresult = 'no source file';
3264: return $fetchresult;
3265: } else {
3266: my $destination = $filepath.'/'.$fname;
3267: rename($source,$destination);
3268: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3269: $home);
1.481 raeburn 3270: }
3271: } elsif ($action eq 'uploaddoc') {
3272: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3273: print $fh $env{'form.'.$source};
1.481 raeburn 3274: close($fh);
1.637 raeburn 3275: if ($parser eq 'parse') {
1.1024 raeburn 3276: my $mm = new File::MMagic;
1.1095 raeburn 3277: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3278: if ($type eq 'text/html') {
1.1024 raeburn 3279: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3280: unless ($parse_result eq 'ok') {
3281: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3282: }
1.637 raeburn 3283: }
1.1095 raeburn 3284: if (ref($mimetype)) {
3285: $$mimetype = $type;
3286: }
1.637 raeburn 3287: }
1.477 raeburn 3288: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3289: $home);
1.481 raeburn 3290: if ($fetchresult eq 'ok') {
3291: return '/uploaded/'.$fpath.'/'.$fname;
3292: } else {
3293: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3294: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3295: return '/adm/notfound.html';
3296: }
1.477 raeburn 3297: }
3298: }
1.485 raeburn 3299: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3300: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3301: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3302: }
3303: return $fetchresult;
3304: }
3305:
1.637 raeburn 3306: sub build_filepath {
3307: my ($fpath) = @_;
3308: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3309: unless ($fpath eq '') {
3310: my @parts=split('/',$fpath);
3311: foreach my $part (@parts) {
3312: $filepath.= '/'.$part;
3313: if ((-e $filepath)!=1) {
3314: mkdir($filepath,0777);
3315: }
3316: }
3317: }
3318: return $filepath;
3319: }
3320:
3321: sub store_edited_file {
1.638 albertel 3322: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3323: my $file = $primary_url;
3324: $file =~ s#^/uploaded/$docudom/$docuname/##;
3325: my $fpath = '';
3326: my $fname = $file;
3327: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3328: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3329: my $filepath = &build_filepath($fpath);
3330: open(my $fh,'>'.$filepath.'/'.$fname);
3331: print $fh $content;
3332: close($fh);
1.638 albertel 3333: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3334: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3335: $home);
1.637 raeburn 3336: if ($$fetchresult eq 'ok') {
3337: return '/uploaded/'.$fpath.'/'.$fname;
3338: } else {
1.638 albertel 3339: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3340: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3341: return '/adm/notfound.html';
3342: }
3343: }
3344:
1.531 albertel 3345: sub clean_filename {
1.831 albertel 3346: my ($fname,$args)=@_;
1.315 www 3347: # Replace Windows backslashes by forward slashes
1.257 www 3348: $fname=~s/\\/\//g;
1.831 albertel 3349: if (!$args->{'keep_path'}) {
3350: # Get rid of everything but the actual filename
3351: $fname=~s/^.*\/([^\/]+)$/$1/;
3352: }
1.315 www 3353: # Replace spaces by underscores
3354: $fname=~s/\s+/\_/g;
3355: # Replace all other weird characters by nothing
1.831 albertel 3356: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3357: # Replace all .\d. sequences with _\d. so they no longer look like version
3358: # numbers
3359: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3360: return $fname;
3361: }
1.1051 raeburn 3362: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3363: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3364: # image with the same aspect ratio as the original, but with dimensions which do
3365: # not exceed $resizewidth and $resizeheight.
3366:
1.984 neumanie 3367: sub resizeImage {
1.1051 raeburn 3368: my ($img_path,$resizewidth,$resizeheight) = @_;
3369: my $ima = Image::Magick->new;
3370: my $resized;
3371: if (-e $img_path) {
3372: $ima->Read($img_path);
3373: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3374: my $width = $ima->Get('width');
3375: my $height = $ima->Get('height');
3376: if ($width > $resizewidth) {
3377: my $factor = $width/$resizewidth;
3378: my $newheight = $height/$factor;
3379: $ima->Scale(width=>$resizewidth,height=>$newheight);
3380: $resized = 1;
3381: }
3382: }
3383: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3384: my $width = $ima->Get('width');
3385: my $height = $ima->Get('height');
3386: if ($height > $resizeheight) {
3387: my $factor = $height/$resizeheight;
3388: my $newwidth = $width/$factor;
3389: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3390: $resized = 1;
3391: }
3392: }
3393: if ($resized) {
3394: $ima->Write($img_path);
3395: }
3396: }
3397: return;
1.977 amueller 3398: }
3399:
1.608 albertel 3400: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3401: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3402: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3403: # $context - possible values: coursedoc, existingfile, overwrite,
3404: # canceloverwrite, or ''.
3405: # if 'coursedoc': upload to the current course
3406: # if 'existingfile': write file to tmp/overwrites directory
3407: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3408: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3409: # $subdir - directory in userfile to store the file into
1.858 raeburn 3410: # $parser - instruction to parse file for objects ($parser = parse)
3411: # $allfiles - reference to hash for embedded objects
3412: # $codebase - reference to hash for codebase of java objects
3413: # $desuname - username for permanent storage of uploaded file
3414: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3415: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3416: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3417: # $resizewidth - width (pixels) to which to resize uploaded image
3418: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3419: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3420: # from File::MMagic.
1.858 raeburn 3421: #
1.686 albertel 3422: # output: url of file in userspace, or error: <message>
3423: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3424:
1.531 albertel 3425: sub userfileupload {
1.1090 raeburn 3426: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3427: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3428: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3429: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3430: $fname=&clean_filename($fname);
1.1090 raeburn 3431: # See if there is anything left
1.257 www 3432: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3433: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3434: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3435: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3436: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3437: my $now = time;
1.1090 raeburn 3438: my $filepath;
1.1095 raeburn 3439: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3440: $filepath = 'tmp/helprequests/'.$now;
3441: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3442: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3443: '_'.$env{'user.domain'}.'/pending';
3444: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3445: my ($docuname,$docudom);
3446: if ($destudom) {
3447: $docudom = $destudom;
3448: } else {
3449: $docudom = $env{'user.domain'};
3450: }
3451: if ($destuname) {
3452: $docuname = $destuname;
3453: } else {
3454: $docuname = $env{'user.name'};
3455: }
3456: if (exists($env{'form.group'})) {
3457: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3458: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3459: }
3460: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3461: if ($context eq 'canceloverwrite') {
3462: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3463: if (-e $tempfile) {
3464: my @info = stat($tempfile);
3465: if ($info[9] eq $env{'form.timestamp'}) {
3466: unlink($tempfile);
3467: }
3468: }
3469: return;
1.523 raeburn 3470: }
3471: }
1.1090 raeburn 3472: # Create the directory if not present
1.741 raeburn 3473: my @parts=split(/\//,$filepath);
3474: my $fullpath = $perlvar{'lonDaemons'};
3475: for (my $i=0;$i<@parts;$i++) {
3476: $fullpath .= '/'.$parts[$i];
3477: if ((-e $fullpath)!=1) {
3478: mkdir($fullpath,0777);
3479: }
3480: }
3481: open(my $fh,'>'.$fullpath.'/'.$fname);
3482: print $fh $env{'form.'.$formname};
3483: close($fh);
1.1090 raeburn 3484: if ($context eq 'existingfile') {
3485: my @info = stat($fullpath.'/'.$fname);
3486: return ($fullpath.'/'.$fname,$info[9]);
3487: } else {
3488: return $fullpath.'/'.$fname;
3489: }
1.523 raeburn 3490: }
1.995 raeburn 3491: if ($subdir eq 'scantron') {
3492: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3493: } else {
1.995 raeburn 3494: $fname="$subdir/$fname";
3495: }
1.1090 raeburn 3496: if ($context eq 'coursedoc') {
1.638 albertel 3497: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3498: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3499: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3500: return &finishuserfileupload($docuname,$docudom,
3501: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3502: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3503: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3504: } else {
1.1172.2.21 raeburn 3505: if ($env{'form.folder'}) {
3506: $fname=$env{'form.folder'}.'/'.$fname;
3507: }
1.638 albertel 3508: return &process_coursefile('uploaddoc',$docuname,$docudom,
3509: $fname,$formname,$parser,
1.1095 raeburn 3510: $allfiles,$codebase,$mimetype);
1.481 raeburn 3511: }
1.719 banghart 3512: } elsif (defined($destuname)) {
3513: my $docuname=$destuname;
3514: my $docudom=$destudom;
1.860 raeburn 3515: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3516: $parser,$allfiles,$codebase,
1.1051 raeburn 3517: $thumbwidth,$thumbheight,
1.1095 raeburn 3518: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3519: } else {
1.638 albertel 3520: my $docuname=$env{'user.name'};
3521: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3522: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3523: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3524: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3525: }
1.860 raeburn 3526: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3527: $parser,$allfiles,$codebase,
1.1051 raeburn 3528: $thumbwidth,$thumbheight,
1.1095 raeburn 3529: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3530: }
1.271 www 3531: }
3532:
3533: sub finishuserfileupload {
1.860 raeburn 3534: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3535: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3536: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3537: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3538:
1.860 raeburn 3539: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3540: $file=$fname;
3541: if ($fname=~m|/|) {
3542: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3543: $path.=$fnamepath.'/';
3544: }
1.259 www 3545: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3546: my $count;
3547: for ($count=4;$count<=$#parts;$count++) {
3548: $filepath.="/$parts[$count]";
3549: if ((-e $filepath)!=1) {
3550: mkdir($filepath,0777);
3551: }
3552: }
1.984 neumanie 3553:
1.258 www 3554: # Save the file
3555: {
1.701 albertel 3556: if (!open(FH,'>'.$filepath.'/'.$file)) {
3557: &logthis('Failed to create '.$filepath.'/'.$file);
3558: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3559: return '/adm/notfound.html';
3560: }
1.1090 raeburn 3561: if ($context eq 'overwrite') {
1.1117 foxr 3562: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3563: my $target = $filepath.'/'.$file;
3564: if (-e $source) {
3565: my @info = stat($source);
3566: if ($info[9] eq $env{'form.timestamp'}) {
3567: unless (&File::Copy::move($source,$target)) {
3568: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3569: return "Moving from $source failed";
3570: }
3571: } else {
3572: return "Temporary file: $source had unexpected date/time for last modification";
3573: }
3574: } else {
3575: return "Temporary file: $source missing";
3576: }
3577: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3578: &logthis('Failed to write to '.$filepath.'/'.$file);
3579: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3580: return '/adm/notfound.html';
3581: }
1.570 albertel 3582: close(FH);
1.1051 raeburn 3583: if ($resizewidth && $resizeheight) {
3584: my $mm = new File::MMagic;
3585: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3586: if ($mime_type =~ m{^image/}) {
3587: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3588: }
1.977 amueller 3589: }
1.258 www 3590: }
1.1152 raeburn 3591: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3592: if (ref($mimetype)) {
3593: if ($$mimetype eq '') {
3594: my $mm = new File::MMagic;
3595: my $type = $mm->checktype_filename($filepath.'/'.$file);
3596: $$mimetype = $type;
3597: }
3598: }
3599: }
1.637 raeburn 3600: if ($parser eq 'parse') {
1.1152 raeburn 3601: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3602: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3603: $allfiles,$codebase);
3604: unless ($parse_result eq 'ok') {
3605: &logthis('Failed to parse '.$filepath.$file.
3606: ' for embedded media: '.$parse_result);
3607: }
1.637 raeburn 3608: }
3609: }
1.860 raeburn 3610: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3611: my $input = $filepath.'/'.$file;
3612: my $output = $filepath.'/'.'tn-'.$file;
3613: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3614: system("convert -sample $thumbsize $input $output");
3615: if (-e $filepath.'/'.'tn-'.$file) {
3616: $fetchthumb = 1;
3617: }
3618: }
1.858 raeburn 3619:
1.259 www 3620: # Notify homeserver to grep it
3621: #
1.984 neumanie 3622: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3623: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3624: if ($fetchresult eq 'ok') {
1.860 raeburn 3625: if ($fetchthumb) {
3626: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3627: if ($thumbresult ne 'ok') {
3628: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3629: $docuhome.': '.$thumbresult);
3630: }
3631: }
1.259 www 3632: #
1.258 www 3633: # Return the URL to it
1.494 albertel 3634: return '/uploaded/'.$path.$file;
1.263 www 3635: } else {
1.494 albertel 3636: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3637: ': '.$fetchresult);
1.263 www 3638: return '/adm/notfound.html';
1.858 raeburn 3639: }
1.493 albertel 3640: }
3641:
1.637 raeburn 3642: sub extract_embedded_items {
1.961 raeburn 3643: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3644: my @state = ();
1.1164 raeburn 3645: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3646: my %javafiles = (
3647: codebase => '',
3648: code => '',
3649: archive => ''
3650: );
3651: my %mediafiles = (
3652: src => '',
3653: movie => '',
3654: );
1.648 raeburn 3655: my $p;
3656: if ($content) {
3657: $p = HTML::LCParser->new($content);
3658: } else {
1.961 raeburn 3659: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3660: }
1.641 albertel 3661: while (my $t=$p->get_token()) {
1.640 albertel 3662: if ($t->[0] eq 'S') {
3663: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3664: push(@state, $tagname);
1.648 raeburn 3665: if (lc($tagname) eq 'allow') {
3666: &add_filetype($allfiles,$attr->{'src'},'src');
3667: }
1.640 albertel 3668: if (lc($tagname) eq 'img') {
3669: &add_filetype($allfiles,$attr->{'src'},'src');
3670: }
1.886 albertel 3671: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3672: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3673: &add_filetype($allfiles,$attr->{'href'},'href');
3674: }
1.886 albertel 3675: }
1.645 raeburn 3676: if (lc($tagname) eq 'script') {
1.1164 raeburn 3677: my $src;
1.645 raeburn 3678: if ($attr->{'archive'} =~ /\.jar$/i) {
3679: &add_filetype($allfiles,$attr->{'archive'},'archive');
3680: } else {
1.1164 raeburn 3681: if ($attr->{'src'} ne '') {
3682: $src = $attr->{'src'};
3683: &add_filetype($allfiles,$src,'src');
3684: }
3685: }
3686: my $text = $p->get_trimmed_text();
3687: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3688: my @swfargs = split(/,/,$1);
3689: foreach my $item (@swfargs) {
3690: $item =~ s/["']//g;
3691: $item =~ s/^\s+//;
3692: $item =~ s/\s+$//;
3693: }
3694: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3695: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3696: push(@{$related{$swfargs[0]}},$swfargs[2]);
3697: } else {
3698: $related{$swfargs[0]} = [$swfargs[2]];
3699: }
3700: }
1.645 raeburn 3701: }
3702: }
3703: if (lc($tagname) eq 'link') {
3704: if (lc($attr->{'rel'}) eq 'stylesheet') {
3705: &add_filetype($allfiles,$attr->{'href'},'href');
3706: }
3707: }
1.640 albertel 3708: if (lc($tagname) eq 'object' ||
3709: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3710: foreach my $item (keys(%javafiles)) {
3711: $javafiles{$item} = '';
3712: }
1.1164 raeburn 3713: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3714: $lastids{lc($tagname)} = $attr->{'id'};
3715: }
1.640 albertel 3716: }
3717: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3718: my $name = lc($attr->{'name'});
3719: foreach my $item (keys(%javafiles)) {
3720: if ($name eq $item) {
3721: $javafiles{$item} = $attr->{'value'};
3722: last;
3723: }
3724: }
1.1164 raeburn 3725: my $pathfrom;
1.640 albertel 3726: foreach my $item (keys(%mediafiles)) {
3727: if ($name eq $item) {
1.1164 raeburn 3728: $pathfrom = $attr->{'value'};
3729: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3730: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3731: last;
3732: }
3733: }
1.1164 raeburn 3734: if ($name eq 'flashvars') {
3735: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3736: }
3737: if ($pathfrom ne '') {
3738: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3739: $pathfrom);
3740: }
1.640 albertel 3741: }
3742: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3743: foreach my $item (keys(%javafiles)) {
3744: if ($attr->{$item}) {
3745: $javafiles{$item} = $attr->{$item};
3746: last;
3747: }
3748: }
3749: foreach my $item (keys(%mediafiles)) {
3750: if ($attr->{$item}) {
3751: &add_filetype($allfiles,$attr->{$item},$item);
3752: last;
3753: }
3754: }
1.1164 raeburn 3755: if (lc($tagname) eq 'embed') {
3756: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3757: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3758: $attr->{'src'});
3759: }
3760: }
1.640 albertel 3761: }
1.1172.2.35 raeburn 3762: if (lc($tagname) eq 'iframe') {
3763: my $src = $attr->{'src'} ;
3764: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3765: &add_filetype($allfiles,$src,'src');
3766: } elsif ($src =~ m{^/}) {
3767: if ($env{'request.course.id'}) {
3768: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3769: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3770: my $url = &hreflocation('',$fullpath);
3771: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3772: my $relpath = $1;
3773: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3774: &add_filetype($allfiles,$1,'src');
3775: }
3776: }
3777: }
3778: }
3779: }
1.1164 raeburn 3780: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3781: pop(@state);
1.1164 raeburn 3782: }
1.640 albertel 3783: } elsif ($t->[0] eq 'E') {
3784: my ($tagname) = ($t->[1]);
3785: if ($javafiles{'codebase'} ne '') {
3786: $javafiles{'codebase'} .= '/';
3787: }
3788: if (lc($tagname) eq 'applet' ||
3789: lc($tagname) eq 'object' ||
3790: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3791: ) {
3792: foreach my $item (keys(%javafiles)) {
3793: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3794: my $file=$javafiles{'codebase'}.$javafiles{$item};
3795: &add_filetype($allfiles,$file,$item);
3796: }
3797: }
3798: }
3799: pop @state;
3800: }
3801: }
1.1164 raeburn 3802: foreach my $id (sort(keys(%flashvars))) {
3803: if ($shockwave{$id} ne '') {
3804: my @pairs = split(/\&/,$flashvars{$id});
3805: foreach my $pair (@pairs) {
3806: my ($key,$value) = split(/\=/,$pair);
3807: if ($key eq 'thumb') {
3808: &add_filetype($allfiles,$value,$key);
3809: } elsif ($key eq 'content') {
3810: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3811: my ($ext) = ($value =~ /\.([^.]+)$/);
3812: if ($ext ne '') {
3813: &add_filetype($allfiles,$path.$value,$ext);
3814: }
3815: }
3816: }
3817: }
3818: }
1.637 raeburn 3819: return 'ok';
3820: }
3821:
1.639 albertel 3822: sub add_filetype {
3823: my ($allfiles,$file,$type)=@_;
3824: if (exists($allfiles->{$file})) {
3825: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3826: push(@{$allfiles->{$file}}, &escape($type));
3827: }
3828: } else {
3829: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3830: }
3831: }
3832:
1.1164 raeburn 3833: sub embedded_dependency {
3834: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3835: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3836: if (($identifier ne '') &&
3837: (ref($related->{$identifier}) eq 'ARRAY') &&
3838: ($pathfrom ne '')) {
3839: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3840: foreach my $dep (@{$related->{$identifier}}) {
3841: &add_filetype($allfiles,$path.$dep,'object');
3842: }
3843: }
3844: }
3845: return;
3846: }
3847:
1.493 albertel 3848: sub removeuploadedurl {
1.984 neumanie 3849: my ($url)=@_;
3850: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3851: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3852: }
3853:
3854: sub removeuserfile {
3855: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3856: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3857: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3858: if ($result eq 'ok') {
1.798 raeburn 3859: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3860: my $metafile = $fname.'.meta';
3861: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3862: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3863: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3864: my $sqlresult =
1.823 albertel 3865: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3866: 'portfolio_metadata',$group,
3867: 'delete');
1.798 raeburn 3868: }
3869: }
3870: return $result;
1.257 www 3871: }
1.15 www 3872:
1.530 albertel 3873: sub mkdiruserfile {
3874: my ($docuname,$docudom,$dir)=@_;
3875: my $home=&homeserver($docuname,$docudom);
3876: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3877: }
3878:
1.531 albertel 3879: sub renameuserfile {
3880: my ($docuname,$docudom,$old,$new)=@_;
3881: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3882: my $result = &reply("renameuserfile:$docudom:$docuname:".
3883: &escape("$old").':'.&escape("$new"),$home);
3884: if ($result eq 'ok') {
3885: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3886: my $oldmeta = $old.'.meta';
3887: my $newmeta = $new.'.meta';
3888: my $metaresult =
3889: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3890: my $url = "/uploaded/$docudom/$docuname/$old";
3891: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3892: my $sqlresult =
1.823 albertel 3893: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3894: 'portfolio_metadata',$group,
3895: 'delete');
1.798 raeburn 3896: }
3897: }
3898: return $result;
1.531 albertel 3899: }
3900:
1.14 www 3901: # ------------------------------------------------------------------------- Log
3902:
3903: sub log {
3904: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3905: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3906: }
3907:
3908: # ------------------------------------------------------------------ Course Log
1.352 www 3909: #
3910: # This routine flushes several buffers of non-mission-critical nature
3911: #
1.157 www 3912:
3913: sub flushcourselogs {
1.352 www 3914: &logthis('Flushing log buffers');
3915: #
3916: # course logs
3917: # This is a log of all transactions in a course, which can be used
3918: # for data mining purposes
3919: #
3920: # It also collects the courseid database, which lists last transaction
3921: # times and course titles for all courseids
3922: #
3923: my %courseidbuffer=();
1.921 raeburn 3924: foreach my $crsid (keys(%courselogs)) {
1.352 www 3925: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3926: &escape($courselogs{$crsid}),
3927: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3928: delete $courselogs{$crsid};
3929: } else {
3930: &logthis('Failed to flush log buffer for '.$crsid);
3931: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3932: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3933: " exceeded maximum size, deleting.</font>");
3934: delete $courselogs{$crsid};
3935: }
1.352 www 3936: }
1.920 raeburn 3937: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3938: 'description' => $coursedescrbuf{$crsid},
3939: 'inst_code' => $courseinstcodebuf{$crsid},
3940: 'type' => $coursetypebuf{$crsid},
3941: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3942: };
1.191 harris41 3943: }
1.352 www 3944: #
3945: # Write course id database (reverse lookup) to homeserver of courses
3946: # Is used in pickcourse
3947: #
1.840 albertel 3948: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3949: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3950: $courseidbuffer{$crs_home},
3951: $crs_home,'timeonly');
1.352 www 3952: }
3953: #
3954: # File accesses
3955: # Writes to the dynamic metadata of resources to get hit counts, etc.
3956: #
1.449 matthew 3957: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3958: if ($entry =~ /___count$/) {
3959: my ($dom,$name);
1.807 albertel 3960: ($dom,$name,undef)=
1.811 albertel 3961: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3962: if (! defined($dom) || $dom eq '' ||
3963: ! defined($name) || $name eq '') {
1.620 albertel 3964: my $cid = $env{'request.course.id'};
3965: $dom = $env{'request.'.$cid.'.domain'};
3966: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3967: }
1.450 matthew 3968: my $value = $accesshash{$entry};
3969: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3970: my %temphash=($url => $value);
1.449 matthew 3971: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3972: if ($result eq 'ok') {
3973: delete $accesshash{$entry};
3974: }
3975: } else {
1.811 albertel 3976: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3977: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3978: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3979: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3980: delete $accesshash{$entry};
3981: }
1.185 www 3982: }
1.191 harris41 3983: }
1.352 www 3984: #
3985: # Roles
3986: # Reverse lookup of user roles for course faculty/staff and co-authorship
3987: #
1.800 albertel 3988: foreach my $entry (keys(%userrolehash)) {
1.351 www 3989: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3990: split(/\:/,$entry);
3991: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3992: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3993: $rudom,$runame) eq 'ok') {
3994: delete $userrolehash{$entry};
3995: }
3996: }
1.662 raeburn 3997: #
1.1172.2.90 raeburn 3998: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 3999: #
4000: my %domrolebuffer = ();
1.1000 raeburn 4001: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4002: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4003: if ($domrolebuffer{$rudom}) {
4004: $domrolebuffer{$rudom}.='&'.&escape($entry).
4005: '='.&escape($domainrolehash{$entry});
4006: } else {
4007: $domrolebuffer{$rudom}.=&escape($entry).
4008: '='.&escape($domainrolehash{$entry});
4009: }
4010: delete $domainrolehash{$entry};
4011: }
4012: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4013: my %servers;
4014: if (defined(&domain($dom,'primary'))) {
4015: my $primary=&domain($dom,'primary');
4016: my $hostname=&hostname($primary);
4017: $servers{$primary} = $hostname;
4018: } else {
4019: %servers = &get_servers($dom,'library');
4020: }
1.841 albertel 4021: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4022: if (&reply('domroleput:'.$dom.':'.
4023: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4024: last;
4025: } else {
1.841 albertel 4026: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4027: }
1.662 raeburn 4028: }
4029: }
1.186 www 4030: $dumpcount++;
1.157 www 4031: }
4032:
4033: sub courselog {
4034: my $what=shift;
1.158 www 4035: $what=time.':'.$what;
1.620 albertel 4036: unless ($env{'request.course.id'}) { return ''; }
4037: $coursedombuf{$env{'request.course.id'}}=
4038: $env{'course.'.$env{'request.course.id'}.'.domain'};
4039: $coursenumbuf{$env{'request.course.id'}}=
4040: $env{'course.'.$env{'request.course.id'}.'.num'};
4041: $coursehombuf{$env{'request.course.id'}}=
4042: $env{'course.'.$env{'request.course.id'}.'.home'};
4043: $coursedescrbuf{$env{'request.course.id'}}=
4044: $env{'course.'.$env{'request.course.id'}.'.description'};
4045: $courseinstcodebuf{$env{'request.course.id'}}=
4046: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4047: $courseownerbuf{$env{'request.course.id'}}=
4048: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4049: $coursetypebuf{$env{'request.course.id'}}=
4050: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4051: if (defined $courselogs{$env{'request.course.id'}}) {
4052: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4053: } else {
1.620 albertel 4054: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4055: }
1.620 albertel 4056: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4057: &flushcourselogs();
4058: }
1.158 www 4059: }
4060:
4061: sub courseacclog {
4062: my $fnsymb=shift;
1.620 albertel 4063: unless ($env{'request.course.id'}) { return ''; }
4064: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4065: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4066: $what.=':POST';
1.583 matthew 4067: # FIXME: Probably ought to escape things....
1.800 albertel 4068: foreach my $key (keys(%env)) {
4069: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4070: my $formitem = $1;
4071: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4072: $what.=':'.$formitem.'='.$env{$key};
4073: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4074: $what.=':'.$formitem.'='.$env{$key};
4075: }
1.158 www 4076: }
1.191 harris41 4077: }
1.583 matthew 4078: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4079: # FIXME: We should not be depending on a form parameter that someone
4080: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4081: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4082: $what.= ':POST';
4083: # FIXME: Probably ought to escape things....
4084: foreach my $element ('courseexp','crsfulltext','crsrelated',
4085: 'crsdiscuss') {
1.620 albertel 4086: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4087: }
4088: }
1.158 www 4089: }
4090: &courselog($what);
1.149 www 4091: }
4092:
1.185 www 4093: sub countacc {
4094: my $url=&declutter(shift);
1.458 matthew 4095: return if (! defined($url) || $url eq '');
1.620 albertel 4096: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4097: #
4098: # Mark that this url was used in this course
4099: #
1.620 albertel 4100: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4101: #
4102: # Increase the access count for this resource in this child process
4103: #
1.281 www 4104: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4105: $accesshash{$key}++;
1.185 www 4106: }
1.349 www 4107:
1.361 www 4108: sub linklog {
4109: my ($from,$to)=@_;
4110: $from=&declutter($from);
4111: $to=&declutter($to);
4112: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4113: $accesshash{$to.'___'.$from.'___goto'}=1;
4114: }
1.1160 www 4115:
4116: sub statslog {
4117: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4118: if ($users<2) { return; }
4119: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4120: 'course' => $env{'request.course.id'},
4121: 'sections' => '"all"',
4122: 'num_students' => $users,
4123: 'part' => $part,
4124: 'symb' => $symb,
4125: 'mean_tries' => $av_attempts,
4126: 'deg_of_diff' => $degdiff});
4127: foreach my $key (keys(%dynstore)) {
4128: $accesshash{$key}=$dynstore{$key};
4129: }
4130: }
1.361 www 4131:
1.349 www 4132: sub userrolelog {
4133: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4134: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4135: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4136: $userrolehash
4137: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4138: =$tend.':'.$tstart;
1.662 raeburn 4139: }
1.1169 droeschl 4140: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4141: $userrolehash
4142: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4143: =$tend.':'.$tstart;
4144: }
1.1172.2.90 raeburn 4145: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4146: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4147: $domainrolehash
4148: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4149: = $tend.':'.$tstart;
4150: }
1.351 www 4151: }
4152:
1.957 raeburn 4153: sub courserolelog {
4154: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4155: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4156: my $cdom = $1;
4157: my $cnum = $2;
4158: my $sec = $3;
4159: my $namespace = 'rolelog';
4160: my %storehash = (
4161: role => $trole,
4162: start => $tstart,
4163: end => $tend,
4164: selfenroll => $selfenroll,
4165: context => $context,
4166: );
4167: if ($trole eq 'gr') {
4168: $namespace = 'groupslog';
4169: $storehash{'group'} = $sec;
4170: } else {
4171: $storehash{'section'} = $sec;
4172: }
4173: &write_log('course',$namespace,\%storehash,$delflag,$username,
4174: $domain,$cnum,$cdom);
4175: if (($trole ne 'st') || ($sec ne '')) {
4176: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4177: }
4178: }
4179: return;
4180: }
4181:
1.1172.2.9 raeburn 4182: sub domainrolelog {
4183: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4184: if ($area =~ m{^/($match_domain)/$}) {
4185: my $cdom = $1;
4186: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4187: my $namespace = 'rolelog';
4188: my %storehash = (
4189: role => $trole,
4190: start => $tstart,
4191: end => $tend,
4192: context => $context,
4193: );
4194: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4195: $domain,$domconfiguser,$cdom);
4196: }
4197: return;
4198:
4199: }
4200:
4201: sub coauthorrolelog {
4202: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4203: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4204: my $audom = $1;
4205: my $auname = $2;
4206: my $namespace = 'rolelog';
4207: my %storehash = (
4208: role => $trole,
4209: start => $tstart,
4210: end => $tend,
4211: context => $context,
4212: );
4213: &write_log('author',$namespace,\%storehash,$delflag,$username,
4214: $domain,$auname,$audom);
4215: }
4216: return;
4217: }
4218:
1.351 www 4219: sub get_course_adv_roles {
1.948 raeburn 4220: my ($cid,$codes) = @_;
1.620 albertel 4221: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4222: my %coursehash=&coursedescription($cid);
1.988 raeburn 4223: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4224: my %nothide=();
1.800 albertel 4225: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4226: if ($user !~ /:/) {
4227: $nothide{join(':',split(/[\@]/,$user))}=1;
4228: } else {
4229: $nothide{$user}=1;
4230: }
1.470 www 4231: }
1.1172.2.23 raeburn 4232: my @possdoms = ($coursehash{'domain'});
4233: if ($coursehash{'checkforpriv'}) {
4234: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4235: }
1.351 www 4236: my %returnhash=();
4237: my %dumphash=
4238: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4239: my $now=time;
1.997 raeburn 4240: my %privileged;
1.1000 raeburn 4241: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4242: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4243: if (($tstart) && ($tstart<0)) { next; }
4244: if (($tend) && ($tend<$now)) { next; }
4245: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4246: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4247: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4248: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4249: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4250: if ($role eq 'cr') { next; }
1.948 raeburn 4251: if ($codes) {
4252: if ($section) { $role .= ':'.$section; }
4253: if ($returnhash{$role}) {
4254: $returnhash{$role}.=','.$username.':'.$domain;
4255: } else {
4256: $returnhash{$role}=$username.':'.$domain;
4257: }
1.351 www 4258: } else {
1.988 raeburn 4259: my $key=&plaintext($role,$crstype);
1.973 bisitz 4260: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4261: if ($returnhash{$key}) {
4262: $returnhash{$key}.=','.$username.':'.$domain;
4263: } else {
4264: $returnhash{$key}=$username.':'.$domain;
4265: }
1.351 www 4266: }
1.948 raeburn 4267: }
1.400 www 4268: return %returnhash;
4269: }
4270:
4271: sub get_my_roles {
1.937 raeburn 4272: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4273: unless (defined($uname)) { $uname=$env{'user.name'}; }
4274: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4275: my (%dumphash,%nothide);
1.1086 raeburn 4276: if ($context eq 'userroles') {
1.1166 raeburn 4277: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4278: } else {
1.1172.2.23 raeburn 4279: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4280: if ($hidepriv) {
4281: my %coursehash=&coursedescription($udom.'_'.$uname);
4282: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4283: if ($user !~ /:/) {
4284: $nothide{join(':',split(/[\@]/,$user))} = 1;
4285: } else {
4286: $nothide{$user} = 1;
4287: }
4288: }
4289: }
1.858 raeburn 4290: }
1.400 www 4291: my %returnhash=();
4292: my $now=time;
1.999 raeburn 4293: my %privileged;
1.800 albertel 4294: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4295: my ($role,$tend,$tstart);
4296: if ($context eq 'userroles') {
1.1149 raeburn 4297: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4298: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4299: } else {
4300: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4301: }
1.400 www 4302: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4303: my $status = 'active';
1.939 raeburn 4304: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4305: $status = 'previous';
4306: }
4307: if (($tstart) && ($now<$tstart)) {
4308: $status = 'future';
4309: }
4310: if (ref($types) eq 'ARRAY') {
4311: if (!grep(/^\Q$status\E$/,@{$types})) {
4312: next;
4313: }
4314: } else {
4315: if ($status ne 'active') {
4316: next;
4317: }
4318: }
1.867 raeburn 4319: my ($rolecode,$username,$domain,$section,$area);
4320: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4321: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4322: (undef,$domain,$username,$section) = split(/\//,$area);
4323: } else {
4324: ($role,$username,$domain,$section) = split(/\:/,$entry);
4325: }
1.832 raeburn 4326: if (ref($roledoms) eq 'ARRAY') {
4327: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4328: next;
4329: }
4330: }
4331: if (ref($roles) eq 'ARRAY') {
4332: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4333: if ($role =~ /^cr\//) {
4334: if (!grep(/^cr$/,@{$roles})) {
4335: next;
4336: }
1.1104 raeburn 4337: } elsif ($role =~ /^gr\//) {
4338: if (!grep(/^gr$/,@{$roles})) {
4339: next;
4340: }
1.922 raeburn 4341: } else {
4342: next;
4343: }
1.832 raeburn 4344: }
1.867 raeburn 4345: }
1.937 raeburn 4346: if ($hidepriv) {
1.1172.2.23 raeburn 4347: my @privroles = ('dc','su');
1.999 raeburn 4348: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4349: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4350: } else {
1.1172.2.23 raeburn 4351: my $possdoms = [$domain];
4352: if (ref($roledoms) eq 'ARRAY') {
4353: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4354: }
1.1172.2.23 raeburn 4355: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4356: if (!$nothide{$username.':'.$domain}) {
4357: next;
4358: }
4359: }
1.937 raeburn 4360: }
4361: }
1.933 raeburn 4362: if ($withsec) {
4363: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4364: $tstart.':'.$tend;
4365: } else {
4366: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4367: }
1.832 raeburn 4368: }
1.373 www 4369: return %returnhash;
1.399 www 4370: }
4371:
1.1172.2.89 raeburn 4372: sub get_all_adhocroles {
4373: my ($dom) = @_;
4374: my @roles_by_num = ();
4375: my %domdefaults = &get_domain_defaults($dom);
4376: my (%description,%access_in_dom,%access_info);
4377: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4378: my $count = 0;
4379: my %domcurrent = %{$domdefaults{'adhocroles'}};
4380: my %ordered;
4381: foreach my $role (sort(keys(%domcurrent))) {
4382: my ($order,$desc,$access_in_dom);
4383: if (ref($domcurrent{$role}) eq 'HASH') {
4384: $order = $domcurrent{$role}{'order'};
4385: $desc = $domcurrent{$role}{'desc'};
4386: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4387: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4388: }
4389: if ($order eq '') {
4390: $order = $count;
4391: }
4392: $ordered{$order} = $role;
4393: if ($desc ne '') {
4394: $description{$role} = $desc;
4395: } else {
4396: $description{$role}= $role;
4397: }
4398: $count++;
4399: }
4400: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4401: push(@roles_by_num,$ordered{$item});
4402: }
4403: }
4404: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4405: }
4406:
4407: sub get_my_adhocroles {
4408: my ($cid,$checkreg) = @_;
4409: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4410: if ($env{'request.course.id'} eq $cid) {
4411: $cdom = $env{'course.'.$cid.'.domain'};
4412: $cnum = $env{'course.'.$cid.'.num'};
4413: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4414: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4415: $cdom = $1;
4416: $cnum = $2;
4417: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4418: $cdom,$cnum);
4419: }
4420: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4421: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4422: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4423: if ($rosterhash{$user} ne '') {
4424: my $type = (split(/:/,$rosterhash{$user}))[5];
4425: return ([],{}) if ($type eq 'auto');
4426: }
4427: }
4428: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4429: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4430: my $then=$env{'user.login.time'};
4431: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4432: if (!$update) {
4433: $update = $then;
4434: }
4435: my @liveroles;
4436: foreach my $role ('dh','da') {
4437: if ($env{"user.role.$role./$cdom/"}) {
4438: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4439: my $limit = $update;
4440: if ($env{'request.role'} eq "$role./$cdom/") {
4441: $limit = $then;
4442: }
4443: my $activerole = 1;
4444: if ($tstart && $tstart>$limit) { $activerole = 0; }
4445: if ($tend && $tend <$limit) { $activerole = 0; }
4446: if ($activerole) {
4447: push(@liveroles,$role);
4448: }
4449: }
4450: }
4451: if (@liveroles) {
1.1172.2.89 raeburn 4452: if (&homeserver($cnum,$cdom) ne 'no_host') {
4453: my ($accessref,$accessinfo,%access_in_dom);
4454: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4455: if (ref($roles_by_num) eq 'ARRAY') {
4456: if (@{$roles_by_num}) {
4457: my %settings;
4458: if ($env{'request.course.id'} eq $cid) {
4459: foreach my $envkey (keys(%env)) {
4460: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4461: $settings{$1} = $env{$envkey};
4462: }
4463: }
4464: } else {
4465: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4466: }
4467: my %setincrs;
4468: if ($settings{'internal.adhocaccess'}) {
4469: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4470: }
4471: my @statuses;
4472: if ($env{'environment.inststatus'}) {
4473: @statuses = split(/,/,$env{'environment.inststatus'});
4474: }
4475: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4476: if (ref($accessref) eq 'HASH') {
4477: %access_in_dom = %{$accessref};
4478: }
4479: foreach my $role (@{$roles_by_num}) {
4480: my ($curraccess,@okstatus,@personnel);
4481: if ($setincrs{$role}) {
4482: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4483: if ($curraccess eq 'status') {
4484: @okstatus = split(/\&/,$rest);
4485: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4486: @personnel = split(/\&/,$rest);
4487: }
4488: } else {
4489: $curraccess = $access_in_dom{$role};
4490: if (ref($accessinfo) eq 'HASH') {
4491: if ($curraccess eq 'status') {
4492: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4493: @okstatus = @{$accessinfo->{$role}};
4494: }
4495: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4496: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4497: @personnel = @{$accessinfo->{$role}};
4498: }
4499: }
4500: }
4501: }
4502: if ($curraccess eq 'none') {
4503: next;
4504: } elsif ($curraccess eq 'all') {
4505: push(@possroles,$role);
1.1172.2.90 raeburn 4506: } elsif ($curraccess eq 'dh') {
4507: if (grep(/^dh$/,@liveroles)) {
4508: push(@possroles,$role);
4509: } else {
4510: next;
4511: }
4512: } elsif ($curraccess eq 'da') {
4513: if (grep(/^da$/,@liveroles)) {
4514: push(@possroles,$role);
4515: } else {
4516: next;
4517: }
1.1172.2.89 raeburn 4518: } elsif ($curraccess eq 'status') {
4519: if (@okstatus) {
4520: if (!@statuses) {
4521: if (grep(/^default$/,@okstatus)) {
4522: push(@possroles,$role);
4523: }
4524: } else {
4525: foreach my $status (@okstatus) {
4526: if (grep(/^\Q$status\E$/,@statuses)) {
4527: push(@possroles,$role);
4528: last;
4529: }
4530: }
4531: }
4532: }
4533: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4534: if (grep(/^\Q$user\E$/,@personnel)) {
4535: if ($curraccess eq 'exc') {
4536: push(@possroles,$role);
4537: }
4538: } elsif ($curraccess eq 'inc') {
4539: push(@possroles,$role);
4540: }
4541: }
4542: }
4543: }
4544: }
4545: }
4546: }
4547: }
4548: }
4549: unless (ref($description) eq 'HASH') {
4550: if (ref($roles_by_num) eq 'ARRAY') {
4551: my %desc;
4552: map { $desc{$_} = $_; } (@{$roles_by_num});
4553: $description = \%desc;
4554: } else {
4555: $description = {};
4556: }
4557: }
4558: return (\@possroles,$description);
4559: }
4560:
1.399 www 4561: # ----------------------------------------------------- Frontpage Announcements
4562: #
4563: #
4564:
4565: sub postannounce {
4566: my ($server,$text)=@_;
1.844 albertel 4567: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4568: unless ($text=~/\w/) { $text=''; }
4569: return &reply('setannounce:'.&escape($text),$server);
4570: }
4571:
4572: sub getannounce {
1.448 albertel 4573:
4574: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4575: my $announcement='';
1.800 albertel 4576: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4577: close($fh);
1.399 www 4578: if ($announcement=~/\w/) {
4579: return
4580: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4581: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4582: } else {
4583: return '';
4584: }
4585: } else {
4586: return '';
4587: }
1.351 www 4588: }
1.353 www 4589:
4590: # ---------------------------------------------------------- Course ID routines
4591: # Deal with domain's nohist_courseid.db files
4592: #
4593:
4594: sub courseidput {
1.921 raeburn 4595: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4596: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4597: my $outcome;
4598: if ($caller eq 'timeonly') {
4599: my $cids = '';
4600: foreach my $item (keys(%$storehash)) {
4601: $cids.=&escape($item).'&';
4602: }
4603: $cids=~s/\&$//;
4604: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4605: $coursehome);
4606: } else {
4607: my $items = '';
4608: foreach my $item (keys(%$storehash)) {
4609: $items.= &escape($item).'='.
4610: &freeze_escape($$storehash{$item}).'&';
4611: }
4612: $items=~s/\&$//;
4613: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4614: $coursehome);
1.918 raeburn 4615: }
4616: if ($outcome eq 'unknown_cmd') {
4617: my $what;
4618: foreach my $cid (keys(%$storehash)) {
4619: $what .= &escape($cid).'=';
1.921 raeburn 4620: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4621: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4622: }
4623: $what =~ s/\:$/&/;
4624: }
4625: $what =~ s/\&$//;
4626: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4627: } else {
4628: return $outcome;
4629: }
1.353 www 4630: }
4631:
4632: sub courseiddump {
1.921 raeburn 4633: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4634: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4635: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4636: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4637: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4638: my $as_hash = 1;
4639: my %returnhash;
4640: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4641: my %libserv = &all_library();
4642: foreach my $tryserver (keys(%libserv)) {
4643: if ( ( $hostidflag == 1
4644: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4645: || (!defined($hostidflag)) ) {
4646:
1.918 raeburn 4647: if (($domfilter eq '') ||
4648: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4649: my $rep;
4650: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4651: $rep = &LONCAPA::Lond::dump_course_id_handler(
4652: join(":", (&host_domain($tryserver), $sincefilter,
4653: &escape($descfilter), &escape($instcodefilter),
4654: &escape($ownerfilter), &escape($coursefilter),
4655: &escape($typefilter), &escape($regexp_ok),
4656: $as_hash, &escape($selfenrollonly),
4657: &escape($catfilter), $showhidden, $caller,
4658: &escape($cloner), &escape($cc_clone), $cloneonly,
4659: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4660: &escape($creationcontext),$domcloner,$hasuniquecode,
4661: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4662: } else {
4663: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4664: $sincefilter.':'.&escape($descfilter).':'.
4665: &escape($instcodefilter).':'.&escape($ownerfilter).
4666: ':'.&escape($coursefilter).':'.&escape($typefilter).
4667: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4668: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4669: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4670: &escape($cc_clone).':'.$cloneonly.':'.
4671: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4672: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4673: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4674: }
4675:
1.918 raeburn 4676: my @pairs=split(/\&/,$rep);
4677: foreach my $item (@pairs) {
4678: my ($key,$value)=split(/\=/,$item,2);
4679: $key = &unescape($key);
4680: next if ($key =~ /^error: 2 /);
4681: my $result = &thaw_unescape($value);
4682: if (ref($result) eq 'HASH') {
4683: $returnhash{$key}=$result;
4684: } else {
1.921 raeburn 4685: my @responses = split(/:/,$value);
4686: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4687: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4688: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4689: }
1.1008 raeburn 4690: }
1.353 www 4691: }
4692: }
4693: }
4694: }
4695: return %returnhash;
4696: }
4697:
1.1055 raeburn 4698: sub courselastaccess {
4699: my ($cdom,$cnum,$hostidref) = @_;
4700: my %returnhash;
4701: if ($cdom && $cnum) {
4702: my $chome = &homeserver($cnum,$cdom);
4703: if ($chome ne 'no_host') {
4704: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4705: &extract_lastaccess(\%returnhash,$rep);
4706: }
4707: } else {
4708: if (!$cdom) { $cdom=''; }
4709: my %libserv = &all_library();
4710: foreach my $tryserver (keys(%libserv)) {
4711: if (ref($hostidref) eq 'ARRAY') {
4712: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4713: }
4714: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4715: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4716: &extract_lastaccess(\%returnhash,$rep);
4717: }
4718: }
4719: }
4720: return %returnhash;
4721: }
4722:
4723: sub extract_lastaccess {
4724: my ($returnhash,$rep) = @_;
4725: if (ref($returnhash) eq 'HASH') {
4726: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4727: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4728: $rep eq '') {
4729: my @pairs=split(/\&/,$rep);
4730: foreach my $item (@pairs) {
4731: my ($key,$value)=split(/\=/,$item,2);
4732: $key = &unescape($key);
4733: next if ($key =~ /^error: 2 /);
4734: $returnhash->{$key} = &thaw_unescape($value);
4735: }
4736: }
4737: }
4738: return;
4739: }
4740:
1.658 raeburn 4741: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4742:
4743: sub dcmailput {
1.685 raeburn 4744: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4745: my $status = &Apache::lonnet::critical(
1.740 www 4746: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4747: &escape($message),$server);
1.662 raeburn 4748: return $status;
4749: }
4750:
1.658 raeburn 4751: sub dcmaildump {
4752: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4753: my %returnhash=();
1.846 albertel 4754:
4755: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4756: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4757: &escape($enddate).':';
4758: my @esc_senders=map { &escape($_)} @$senders;
4759: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4760: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4761: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4762: if (($key) && ($value)) {
4763: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4764: }
4765: }
4766: }
4767: return %returnhash;
4768: }
1.662 raeburn 4769: # ---------------------------------------------------------- Domain roles
4770:
4771: sub get_domain_roles {
4772: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4773: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4774: $startdate = '.';
4775: }
1.1018 raeburn 4776: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4777: $enddate = '.';
4778: }
1.922 raeburn 4779: my $rolelist;
4780: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4781: $rolelist = join('&',@{$roles});
1.922 raeburn 4782: }
1.662 raeburn 4783: my %personnel = ();
1.841 albertel 4784:
4785: my %servers = &get_servers($dom,'library');
4786: foreach my $tryserver (keys(%servers)) {
4787: %{$personnel{$tryserver}}=();
4788: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4789: &escape($startdate).':'.
4790: &escape($enddate).':'.
4791: &escape($rolelist), $tryserver))) {
4792: my ($key,$value) = split(/\=/,$line,2);
4793: if (($key) && ($value)) {
4794: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4795: }
4796: }
1.662 raeburn 4797: }
4798: return %personnel;
4799: }
1.658 raeburn 4800:
1.1172.2.89 raeburn 4801: sub get_active_domroles {
4802: my ($dom,$roles) = @_;
4803: return () unless (ref($roles) eq 'ARRAY');
4804: my $now = time;
4805: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4806: my %domroles;
4807: foreach my $server (keys(%dompersonnel)) {
4808: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4809: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4810: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4811: }
4812: }
4813: return %domroles;
4814: }
4815:
1.1057 www 4816: # ----------------------------------------------------------- Interval timing
1.149 www 4817:
1.1153 www 4818: {
4819: # Caches needed for speedup of navmaps
4820: # We don't want to cache this for very long at all (5 seconds at most)
4821: #
4822: # The user for whom we cache
4823: my $cachedkey='';
4824: # The cached times for this user
4825: my %cachedtimes=();
4826: # When this was last done
1.1172.2.66 raeburn 4827: my $cachedtime='';
1.1153 www 4828:
4829: sub load_all_first_access {
1.1172.2.93.4 1(raebur 4830:7): my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4831: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.4 1(raebur 4832:7): (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4833:7): (!$ignorecache)) {
1.1154 raeburn 4834: return;
4835: }
4836: $cachedtime=time;
4837: $cachedkey=$uname.':'.$udom;
4838: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4839: }
4840:
1.504 albertel 4841: sub get_first_access {
1.1172.2.93.4 1(raebur 4842:7): my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4843: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4844: if ($argsymb) { $symb=$argsymb; }
4845: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4846: if ($argmap) { $map = $argmap; }
1.926 albertel 4847: if ($type eq 'course') {
4848: $res='course';
4849: } elsif ($type eq 'map') {
1.588 albertel 4850: $res=&symbread($map);
4851: } else {
4852: $res=$symb;
4853: }
1.1172.2.93.4 1(raebur 4854:7): &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4855: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4856: }
4857:
4858: sub set_first_access {
1.1162 raeburn 4859: my ($type,$interval)=@_;
1.790 albertel 4860: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4861: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4862: if ($type eq 'course') {
4863: $res='course';
4864: } elsif ($type eq 'map') {
1.588 albertel 4865: $res=&symbread($map);
4866: } else {
4867: $res=$symb;
4868: }
1.1153 www 4869: $cachedkey='';
1.1162 raeburn 4870: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4871: if (!$firstaccess) {
1.1162 raeburn 4872: my $start = time;
4873: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4874: $udom,$uname);
4875: if ($putres eq 'ok') {
4876: &put('timerinterval',{"$courseid\0$res"=>$interval},
4877: $udom,$uname);
4878: &appenv(
4879: {
4880: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4881: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4882: }
4883: );
4884: }
4885: return $putres;
1.505 albertel 4886: }
4887: return 'already_set';
1.504 albertel 4888: }
1.1153 www 4889: }
1.1172.2.32 raeburn 4890:
4891: sub checkout {
4892: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4893: my $now=time;
4894: my $lonhost=$perlvar{'lonHostID'};
4895: my $infostr=&escape(
4896: 'CHECKOUTTOKEN&'.
4897: $tuname.'&'.
4898: $tudom.'&'.
4899: $tcrsid.'&'.
4900: $symb.'&'.
4901: $now.'&'.$ENV{'REMOTE_ADDR'});
4902: my $token=&reply('tmpput:'.$infostr,$lonhost);
4903: if ($token=~/^error\:/) {
4904: &logthis("<font color=\"blue\">WARNING: ".
4905: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4906: "</font>");
4907: return '';
4908: }
4909:
4910: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4911: $token=~tr/a-z/A-Z/;
4912:
4913: my %infohash=('resource.0.outtoken' => $token,
4914: 'resource.0.checkouttime' => $now,
4915: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4916:
4917: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4918: return '';
4919: } else {
4920: &logthis("<font color=\"blue\">WARNING: ".
4921: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4922: "</font>");
4923: }
4924:
4925: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4926: &escape('Checkout '.$infostr.' - '.
4927: $token)) ne 'ok') {
4928: return '';
4929: } else {
4930: &logthis("<font color=\"blue\">WARNING: ".
4931: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4932: "</font>");
4933: }
4934: return $token;
4935: }
4936:
4937: # ------------------------------------------------------------ Check in an item
4938:
4939: sub checkin {
4940: my $token=shift;
4941: my $now=time;
4942: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4943: $lonhost=~tr/A-Z/a-z/;
4944: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4945: $dtoken=~s/\W/\_/g;
4946: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4947: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4948:
4949: unless (($tuname) && ($tudom)) {
4950: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4951: return '';
4952: }
4953:
4954: unless (&allowed('mgr',$tcrsid)) {
4955: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4956: $env{'user.name'}.' - '.$env{'user.domain'});
4957: return '';
4958: }
4959:
4960: my %infohash=('resource.0.intoken' => $token,
4961: 'resource.0.checkintime' => $now,
4962: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4963:
4964: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4965: return '';
4966: }
4967:
4968: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4969: &escape('Checkin - '.$token)) ne 'ok') {
4970: return '';
4971: }
4972:
4973: return ($symb,$tuname,$tudom,$tcrsid);
4974: }
4975:
1.110 www 4976: # --------------------------------------------- Set Expire Date for Spreadsheet
4977:
4978: sub expirespread {
4979: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4980: my $cid=$env{'request.course.id'};
1.110 www 4981: if ($cid) {
4982: my $now=time;
4983: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4984: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4985: $env{'course.'.$cid.'.num'}.
1.110 www 4986: ':nohist_expirationdates:'.
4987: &escape($key).'='.$now,
1.620 albertel 4988: $env{'course.'.$cid.'.home'})
1.110 www 4989: }
4990: return 'ok';
1.14 www 4991: }
4992:
1.109 www 4993: # ----------------------------------------------------- Devalidate Spreadsheets
4994:
4995: sub devalidate {
1.325 www 4996: my ($symb,$uname,$udom)=@_;
1.620 albertel 4997: my $cid=$env{'request.course.id'};
1.109 www 4998: if ($cid) {
1.391 matthew 4999: # delete the stored spreadsheets for
5000: # - the student level sheet of this user in course's homespace
5001: # - the assessment level sheet for this resource
5002: # for this user in user's homespace
1.553 albertel 5003: # - current conditional state info
1.325 www 5004: my $key=$uname.':'.$udom.':';
1.109 www 5005: my $status=
1.299 matthew 5006: &del('nohist_calculatedsheets',
1.391 matthew 5007: [$key.'studentcalc:'],
1.620 albertel 5008: $env{'course.'.$cid.'.domain'},
5009: $env{'course.'.$cid.'.num'})
1.133 albertel 5010: .' '.
5011: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5012: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5013: unless ($status eq 'ok ok') {
5014: &logthis('Could not devalidate spreadsheet '.
1.325 www 5015: $uname.' at '.$udom.' for '.
1.109 www 5016: $symb.': '.$status);
1.133 albertel 5017: }
1.553 albertel 5018: &delenv('user.state.'.$cid);
1.109 www 5019: }
5020: }
5021:
1.265 albertel 5022: sub get_scalar {
5023: my ($string,$end) = @_;
5024: my $value;
5025: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5026: $value = $1;
5027: } elsif ($$string =~ s/^([^&]*?)&//) {
5028: $value = $1;
5029: }
5030: return &unescape($value);
5031: }
5032:
5033: sub array2str {
5034: my (@array) = @_;
5035: my $result=&arrayref2str(\@array);
5036: $result=~s/^__ARRAY_REF__//;
5037: $result=~s/__END_ARRAY_REF__$//;
5038: return $result;
5039: }
5040:
1.204 albertel 5041: sub arrayref2str {
5042: my ($arrayref) = @_;
1.265 albertel 5043: my $result='__ARRAY_REF__';
1.204 albertel 5044: foreach my $elem (@$arrayref) {
1.265 albertel 5045: if(ref($elem) eq 'ARRAY') {
5046: $result.=&arrayref2str($elem).'&';
5047: } elsif(ref($elem) eq 'HASH') {
5048: $result.=&hashref2str($elem).'&';
5049: } elsif(ref($elem)) {
5050: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5051: } else {
5052: $result.=&escape($elem).'&';
5053: }
5054: }
5055: $result=~s/\&$//;
1.265 albertel 5056: $result .= '__END_ARRAY_REF__';
1.204 albertel 5057: return $result;
5058: }
5059:
1.168 albertel 5060: sub hash2str {
1.204 albertel 5061: my (%hash) = @_;
5062: my $result=&hashref2str(\%hash);
1.265 albertel 5063: $result=~s/^__HASH_REF__//;
5064: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5065: return $result;
5066: }
5067:
5068: sub hashref2str {
5069: my ($hashref)=@_;
1.265 albertel 5070: my $result='__HASH_REF__';
1.800 albertel 5071: foreach my $key (sort(keys(%$hashref))) {
5072: if (ref($key) eq 'ARRAY') {
5073: $result.=&arrayref2str($key).'=';
5074: } elsif (ref($key) eq 'HASH') {
5075: $result.=&hashref2str($key).'=';
5076: } elsif (ref($key)) {
1.265 albertel 5077: $result.='=';
1.800 albertel 5078: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5079: } else {
1.1132 raeburn 5080: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5081: }
5082:
1.800 albertel 5083: if(ref($hashref->{$key}) eq 'ARRAY') {
5084: $result.=&arrayref2str($hashref->{$key}).'&';
5085: } elsif(ref($hashref->{$key}) eq 'HASH') {
5086: $result.=&hashref2str($hashref->{$key}).'&';
5087: } elsif(ref($hashref->{$key})) {
1.265 albertel 5088: $result.='&';
1.800 albertel 5089: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5090: } else {
1.800 albertel 5091: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5092: }
5093: }
1.168 albertel 5094: $result=~s/\&$//;
1.265 albertel 5095: $result .= '__END_HASH_REF__';
1.168 albertel 5096: return $result;
5097: }
5098:
5099: sub str2hash {
1.265 albertel 5100: my ($string)=@_;
5101: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5102: return %$hash;
5103: }
5104:
5105: sub str2hashref {
1.168 albertel 5106: my ($string) = @_;
1.265 albertel 5107:
5108: my %hash;
5109:
5110: if($string !~ /^__HASH_REF__/) {
5111: if (! ($string eq '' || !defined($string))) {
5112: $hash{'error'}='Not hash reference';
5113: }
5114: return (\%hash, $string);
5115: }
5116:
5117: $string =~ s/^__HASH_REF__//;
5118:
5119: while($string !~ /^__END_HASH_REF__/) {
5120: #key
5121: my $key='';
5122: if($string =~ /^__HASH_REF__/) {
5123: ($key, $string)=&str2hashref($string);
5124: if(defined($key->{'error'})) {
5125: $hash{'error'}='Bad data';
5126: return (\%hash, $string);
5127: }
5128: } elsif($string =~ /^__ARRAY_REF__/) {
5129: ($key, $string)=&str2arrayref($string);
5130: if($key->[0] eq 'Array reference error') {
5131: $hash{'error'}='Bad data';
5132: return (\%hash, $string);
5133: }
5134: } else {
5135: $string =~ s/^(.*?)=//;
1.267 albertel 5136: $key=&unescape($1);
1.265 albertel 5137: }
5138: $string =~ s/^=//;
5139:
5140: #value
5141: my $value='';
5142: if($string =~ /^__HASH_REF__/) {
5143: ($value, $string)=&str2hashref($string);
5144: if(defined($value->{'error'})) {
5145: $hash{'error'}='Bad data';
5146: return (\%hash, $string);
5147: }
5148: } elsif($string =~ /^__ARRAY_REF__/) {
5149: ($value, $string)=&str2arrayref($string);
5150: if($value->[0] eq 'Array reference error') {
5151: $hash{'error'}='Bad data';
5152: return (\%hash, $string);
5153: }
5154: } else {
5155: $value=&get_scalar(\$string,'__END_HASH_REF__');
5156: }
5157: $string =~ s/^&//;
5158:
5159: $hash{$key}=$value;
1.204 albertel 5160: }
1.265 albertel 5161:
5162: $string =~ s/^__END_HASH_REF__//;
5163:
5164: return (\%hash, $string);
1.204 albertel 5165: }
5166:
5167: sub str2array {
1.265 albertel 5168: my ($string)=@_;
5169: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5170: return @$array;
5171: }
5172:
5173: sub str2arrayref {
1.204 albertel 5174: my ($string) = @_;
1.265 albertel 5175: my @array;
5176:
5177: if($string !~ /^__ARRAY_REF__/) {
5178: if (! ($string eq '' || !defined($string))) {
5179: $array[0]='Array reference error';
5180: }
5181: return (\@array, $string);
5182: }
5183:
5184: $string =~ s/^__ARRAY_REF__//;
5185:
5186: while($string !~ /^__END_ARRAY_REF__/) {
5187: my $value='';
5188: if($string =~ /^__HASH_REF__/) {
5189: ($value, $string)=&str2hashref($string);
5190: if(defined($value->{'error'})) {
5191: $array[0] ='Array reference error';
5192: return (\@array, $string);
5193: }
5194: } elsif($string =~ /^__ARRAY_REF__/) {
5195: ($value, $string)=&str2arrayref($string);
5196: if($value->[0] eq 'Array reference error') {
5197: $array[0] ='Array reference error';
5198: return (\@array, $string);
5199: }
5200: } else {
5201: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5202: }
5203: $string =~ s/^&//;
5204:
5205: push(@array, $value);
1.191 harris41 5206: }
1.265 albertel 5207:
5208: $string =~ s/^__END_ARRAY_REF__//;
5209:
5210: return (\@array, $string);
1.168 albertel 5211: }
5212:
1.167 albertel 5213: # -------------------------------------------------------------------Temp Store
5214:
1.168 albertel 5215: sub tmpreset {
5216: my ($symb,$namespace,$domain,$stuname) = @_;
5217: if (!$symb) {
5218: $symb=&symbread();
1.620 albertel 5219: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5220: }
5221: $symb=escape($symb);
5222:
1.620 albertel 5223: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5224: $namespace=~s/\//\_/g;
5225: $namespace=~s/\W//g;
5226:
1.620 albertel 5227: if (!$domain) { $domain=$env{'user.domain'}; }
5228: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5229: if ($domain eq 'public' && $stuname eq 'public') {
5230: $stuname=$ENV{'REMOTE_ADDR'};
5231: }
1.1117 foxr 5232: my $path=LONCAPA::tempdir();
1.168 albertel 5233: my %hash;
5234: if (tie(%hash,'GDBM_File',
5235: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5236: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5237: foreach my $key (keys(%hash)) {
1.180 albertel 5238: if ($key=~ /:$symb/) {
1.168 albertel 5239: delete($hash{$key});
5240: }
5241: }
5242: }
5243: }
5244:
1.167 albertel 5245: sub tmpstore {
1.168 albertel 5246: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5247:
5248: if (!$symb) {
5249: $symb=&symbread();
1.620 albertel 5250: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5251: }
5252: $symb=escape($symb);
5253:
5254: if (!$namespace) {
5255: # I don't think we would ever want to store this for a course.
5256: # it seems this will only be used if we don't have a course.
1.620 albertel 5257: #$namespace=$env{'request.course.id'};
1.168 albertel 5258: #if (!$namespace) {
1.620 albertel 5259: $namespace=$env{'request.state'};
1.168 albertel 5260: #}
5261: }
5262: $namespace=~s/\//\_/g;
5263: $namespace=~s/\W//g;
1.620 albertel 5264: if (!$domain) { $domain=$env{'user.domain'}; }
5265: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5266: if ($domain eq 'public' && $stuname eq 'public') {
5267: $stuname=$ENV{'REMOTE_ADDR'};
5268: }
1.168 albertel 5269: my $now=time;
5270: my %hash;
1.1117 foxr 5271: my $path=LONCAPA::tempdir();
1.168 albertel 5272: if (tie(%hash,'GDBM_File',
5273: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5274: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5275: $hash{"version:$symb"}++;
5276: my $version=$hash{"version:$symb"};
5277: my $allkeys='';
5278: foreach my $key (keys(%$storehash)) {
5279: $allkeys.=$key.':';
1.591 albertel 5280: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5281: }
5282: $hash{"$version:$symb:timestamp"}=$now;
5283: $allkeys.='timestamp';
5284: $hash{"$version:keys:$symb"}=$allkeys;
5285: if (untie(%hash)) {
5286: return 'ok';
5287: } else {
5288: return "error:$!";
5289: }
5290: } else {
5291: return "error:$!";
5292: }
5293: }
1.167 albertel 5294:
1.168 albertel 5295: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5296:
1.168 albertel 5297: sub tmprestore {
5298: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5299:
1.168 albertel 5300: if (!$symb) {
5301: $symb=&symbread();
1.620 albertel 5302: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5303: }
5304: $symb=escape($symb);
5305:
1.620 albertel 5306: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5307:
1.620 albertel 5308: if (!$domain) { $domain=$env{'user.domain'}; }
5309: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5310: if ($domain eq 'public' && $stuname eq 'public') {
5311: $stuname=$ENV{'REMOTE_ADDR'};
5312: }
1.168 albertel 5313: my %returnhash;
5314: $namespace=~s/\//\_/g;
5315: $namespace=~s/\W//g;
5316: my %hash;
1.1117 foxr 5317: my $path=LONCAPA::tempdir();
1.168 albertel 5318: if (tie(%hash,'GDBM_File',
5319: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5320: &GDBM_READER(),0640)) {
1.168 albertel 5321: my $version=$hash{"version:$symb"};
5322: $returnhash{'version'}=$version;
5323: my $scope;
5324: for ($scope=1;$scope<=$version;$scope++) {
5325: my $vkeys=$hash{"$scope:keys:$symb"};
5326: my @keys=split(/:/,$vkeys);
5327: my $key;
5328: $returnhash{"$scope:keys"}=$vkeys;
5329: foreach $key (@keys) {
1.591 albertel 5330: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5331: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5332: }
5333: }
1.168 albertel 5334: if (!(untie(%hash))) {
5335: return "error:$!";
5336: }
5337: } else {
5338: return "error:$!";
5339: }
5340: return %returnhash;
1.167 albertel 5341: }
5342:
1.9 www 5343: # ----------------------------------------------------------------------- Store
5344:
5345: sub store {
1.1172.2.64 raeburn 5346: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5347: my $home='';
5348:
1.168 albertel 5349: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5350:
1.213 www 5351: $symb=&symbclean($symb);
1.122 albertel 5352: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5353:
1.620 albertel 5354: if (!$domain) { $domain=$env{'user.domain'}; }
5355: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5356:
5357: &devalidate($symb,$stuname,$domain);
1.109 www 5358:
5359: $symb=escape($symb);
1.187 www 5360: if (!$namespace) {
1.620 albertel 5361: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5362: return '';
5363: }
5364: }
1.620 albertel 5365: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5366:
5367: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5368: $$storehash{'host'}=$perlvar{'lonHostID'};
5369:
1.12 www 5370: my $namevalue='';
1.800 albertel 5371: foreach my $key (keys(%$storehash)) {
5372: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5373: }
1.12 www 5374: $namevalue=~s/\&$//;
1.187 www 5375: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5376: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5377: }
5378:
1.47 www 5379: # -------------------------------------------------------------- Critical Store
5380:
5381: sub cstore {
1.1172.2.64 raeburn 5382: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5383: my $home='';
5384:
1.168 albertel 5385: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5386:
1.213 www 5387: $symb=&symbclean($symb);
1.122 albertel 5388: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5389:
1.620 albertel 5390: if (!$domain) { $domain=$env{'user.domain'}; }
5391: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5392:
5393: &devalidate($symb,$stuname,$domain);
1.109 www 5394:
5395: $symb=escape($symb);
1.187 www 5396: if (!$namespace) {
1.620 albertel 5397: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5398: return '';
5399: }
5400: }
1.620 albertel 5401: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5402:
5403: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5404: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5405:
1.47 www 5406: my $namevalue='';
1.800 albertel 5407: foreach my $key (keys(%$storehash)) {
5408: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5409: }
1.47 www 5410: $namevalue=~s/\&$//;
1.187 www 5411: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5412: return critical
1.1172.2.64 raeburn 5413: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5414: }
5415:
1.9 www 5416: # --------------------------------------------------------------------- Restore
5417:
5418: sub restore {
1.124 www 5419: my ($symb,$namespace,$domain,$stuname) = @_;
5420: my $home='';
5421:
1.168 albertel 5422: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5423:
1.122 albertel 5424: if (!$symb) {
1.1172.2.26 raeburn 5425: return if ($namespace eq 'courserequests');
5426: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5427: } else {
1.1172.2.26 raeburn 5428: unless ($namespace eq 'courserequests') {
5429: $symb=&escape(&symbclean($symb));
5430: }
1.122 albertel 5431: }
1.188 www 5432: if (!$namespace) {
1.620 albertel 5433: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5434: return '';
5435: }
5436: }
1.620 albertel 5437: if (!$domain) { $domain=$env{'user.domain'}; }
5438: if (!$stuname) { $stuname=$env{'user.name'}; }
5439: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5440: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5441:
1.12 www 5442: my %returnhash=();
1.800 albertel 5443: foreach my $line (split(/\&/,$answer)) {
5444: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5445: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5446: }
1.75 www 5447: my $version;
5448: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5449: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5450: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5451: }
1.75 www 5452: }
1.13 www 5453: return %returnhash;
1.34 www 5454: }
5455:
5456: # ---------------------------------------------------------- Course Description
1.1118 foxr 5457: #
5458: #
1.34 www 5459:
5460: sub coursedescription {
1.731 albertel 5461: my ($courseid,$args)=@_;
1.34 www 5462: $courseid=~s/^\///;
1.49 www 5463: $courseid=~s/\_/\//g;
1.34 www 5464: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5465: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5466: my $normalid=$cdomain.'_'.$cnum;
5467: # need to always cache even if we get errors otherwise we keep
5468: # trying and trying and trying to get the course description.
5469: my %envhash=();
5470: my %returnhash=();
1.731 albertel 5471:
5472: my $expiretime=600;
5473: if ($env{'request.course.id'} eq $normalid) {
5474: $expiretime=120;
5475: }
5476:
5477: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5478: if (!$args->{'freshen_cache'}
5479: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5480: foreach my $key (keys(%env)) {
5481: next if ($key !~ /^\Q$prefix\E(.*)/);
5482: my ($setting) = $1;
5483: $returnhash{$setting} = $env{$key};
5484: }
5485: return %returnhash;
5486: }
5487:
1.1118 foxr 5488: # get the data again
5489:
1.731 albertel 5490: if (!$args->{'one_time'}) {
5491: $envhash{'course.'.$normalid.'.last_cache'}=time;
5492: }
1.811 albertel 5493:
1.34 www 5494: if ($chome ne 'no_host') {
1.302 albertel 5495: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5496: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5497: my $username = $env{'user.name'}; # Defult username
5498: if(defined $args->{'user'}) {
5499: $username = $args->{'user'};
5500: }
1.129 albertel 5501: $returnhash{'home'}= $chome;
5502: $returnhash{'domain'} = $cdomain;
5503: $returnhash{'num'} = $cnum;
1.741 raeburn 5504: if (!defined($returnhash{'type'})) {
5505: $returnhash{'type'} = 'Course';
5506: }
1.130 albertel 5507: while (my ($name,$value) = each %returnhash) {
1.53 www 5508: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5509: }
1.270 www 5510: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5511: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5512: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5513: $envhash{'course.'.$normalid.'.home'}=$chome;
5514: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5515: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5516: }
5517: }
1.731 albertel 5518: if (!$args->{'one_time'}) {
1.949 raeburn 5519: &appenv(\%envhash);
1.731 albertel 5520: }
1.302 albertel 5521: return %returnhash;
1.461 www 5522: }
5523:
1.1080 raeburn 5524: sub update_released_required {
5525: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5526: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5527: $cid = $env{'request.course.id'};
5528: $cdom = $env{'course.'.$cid.'.domain'};
5529: $cnum = $env{'course.'.$cid.'.num'};
5530: $chome = $env{'course.'.$cid.'.home'};
5531: }
5532: if ($needsrelease) {
5533: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5534: my $needsupdate;
5535: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5536: $needsupdate = 1;
5537: } else {
5538: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5539: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5540: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5541: $needsupdate = 1;
5542: }
5543: }
5544: if ($needsupdate) {
5545: my %needshash = (
5546: 'internal.releaserequired' => $needsrelease,
5547: );
5548: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5549: if ($putresult eq 'ok') {
5550: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5551: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5552: if (ref($crsinfo{$cid}) eq 'HASH') {
5553: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5554: &courseidput($cdom,\%crsinfo,$chome,'notime');
5555: }
5556: }
5557: }
5558: }
5559: return;
5560: }
5561:
1.461 www 5562: # -------------------------------------------------See if a user is privileged
5563:
5564: sub privileged {
1.1172.2.23 raeburn 5565: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5566: my $now = time;
1.1172.2.23 raeburn 5567: my $roles;
5568: if (ref($possroles) eq 'ARRAY') {
5569: $roles = $possroles;
5570: } else {
5571: $roles = ['dc','su'];
5572: }
5573: if (ref($possdomains) eq 'ARRAY') {
5574: my %privileged = &privileged_by_domain($possdomains,$roles);
5575: foreach my $dom (@{$possdomains}) {
5576: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5577: (ref($privileged{$dom}) eq 'HASH')) {
5578: foreach my $role (@{$roles}) {
5579: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5580: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5581: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5582: return 1 unless (($end && $end < $now) ||
5583: ($start && $start > $now));
5584: }
5585: }
5586: }
5587: }
5588: }
5589: } else {
5590: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5591: my $now = time;
1.1170 droeschl 5592:
1.1172.2.58 raeburn 5593: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5594: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5595: if (grep(/^\Q$trole\E$/,@{$roles})) {
5596: return 1 unless ($tend && $tend < $now)
5597: or ($tstart && $tstart > $now);
1.1170 droeschl 5598: }
1.1172.2.23 raeburn 5599: }
5600: }
1.461 www 5601: return 0;
1.9 www 5602: }
1.1 albertel 5603:
1.1172.2.23 raeburn 5604: sub privileged_by_domain {
5605: my ($domains,$roles) = @_;
5606: my %privileged = ();
5607: my $cachetime = 60*60*24;
5608: my $now = time;
5609: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5610: return %privileged;
5611: }
5612: foreach my $dom (@{$domains}) {
5613: next if (ref($privileged{$dom}) eq 'HASH');
5614: my $needroles;
5615: foreach my $role (@{$roles}) {
5616: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5617: if (defined($cached)) {
5618: if (ref($result) eq 'HASH') {
5619: $privileged{$dom}{$role} = $result;
5620: }
5621: } else {
5622: $needroles = 1;
5623: }
5624: }
5625: if ($needroles) {
5626: my %dompersonnel = &get_domain_roles($dom,$roles);
5627: $privileged{$dom} = {};
5628: foreach my $server (keys(%dompersonnel)) {
5629: if (ref($dompersonnel{$server}) eq 'HASH') {
5630: foreach my $item (keys(%{$dompersonnel{$server}})) {
5631: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5632: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5633: next if ($end && $end < $now);
5634: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5635: $dompersonnel{$server}{$item};
5636: }
5637: }
5638: }
5639: if (ref($privileged{$dom}) eq 'HASH') {
5640: foreach my $role (@{$roles}) {
5641: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5642: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5643: } else {
5644: my %hash = ();
5645: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5646: }
5647: }
5648: }
5649: }
5650: }
5651: return %privileged;
5652: }
5653:
1.103 harris41 5654: # -------------------------------------------------------- Get user privileges
1.11 www 5655:
5656: sub rolesinit {
1.1169 droeschl 5657: my ($domain, $username) = @_;
5658: my %userroles = ('user.login.time' => time);
5659: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5660:
5661: # firstaccess and timerinterval are related to timed maps/resources.
5662: # also, blocking can be triggered by an activating timer
5663: # it's saved in the user's %env.
5664: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5665: my %timerinterval = &dump('timerinterval', $domain, $username);
5666: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5667: %timerintchk, %timerintenv);
5668:
1.1162 raeburn 5669: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5670: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5671: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5672: }
1.1169 droeschl 5673:
1.1162 raeburn 5674: foreach my $key (keys(%timerinterval)) {
5675: my ($cid,$rest) = split(/\0/,$key);
5676: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5677: }
1.1169 droeschl 5678:
1.11 www 5679: my %allroles=();
1.1162 raeburn 5680: my %allgroups=();
1.11 www 5681:
1.1172.2.58 raeburn 5682: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5683: my $role = $rolesdump{$area};
5684: $area =~ s/\_\w\w$//;
5685:
5686: my ($trole, $tend, $tstart, $group_privs);
5687:
5688: if ($role =~ /^cr/) {
5689: # Custom role, defined by a user
5690: # e.g., user.role.cr/msu/smith/mynewrole
5691: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5692: $trole = $1;
5693: ($tend, $tstart) = split('_', $2);
5694: } else {
5695: $trole = $role;
5696: }
5697: } elsif ($role =~ m|^gr/|) {
5698: # Role of member in a group, defined within a course/community
5699: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5700: ($trole, $tend, $tstart) = split(/_/, $role);
5701: next if $tstart eq '-1';
5702: ($trole, $group_privs) = split(/\//, $trole);
5703: $group_privs = &unescape($group_privs);
5704: } else {
5705: # Just a normal role, defined in roles.tab
5706: ($trole, $tend, $tstart) = split(/_/,$role);
5707: }
5708:
5709: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5710: $username);
5711: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5712:
5713: # role expired or not available yet?
5714: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5715: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5716:
5717: next if $area eq '' or $trole eq '';
5718:
5719: my $spec = "$trole.$area";
5720: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5721:
5722: if ($trole =~ /^cr\//) {
5723: # Custom role, defined by a user
5724: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5725: } elsif ($trole eq 'gr') {
5726: # Role of a member in a group, defined within a course/community
5727: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5728: next;
5729: } else {
5730: # Normal role, defined in roles.tab
5731: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5732: }
5733:
5734: my $cid = $tdomain.'_'.$trest;
5735: unless ($firstaccchk{$cid}) {
5736: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5737: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5738: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5739: $coursetimerstarts{$cid}{$item};
5740: }
5741: }
5742: $firstaccchk{$cid} = 1;
5743: }
5744: unless ($timerintchk{$cid}) {
5745: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5746: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5747: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5748: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5749: }
1.12 www 5750: }
1.1169 droeschl 5751: $timerintchk{$cid} = 1;
1.191 harris41 5752: }
1.11 www 5753: }
1.1169 droeschl 5754:
1.1172.2.91 raeburn 5755: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5756: \%allroles, \%allgroups);
1.1169 droeschl 5757: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 5758: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5759:
1.1162 raeburn 5760: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5761: }
5762:
1.567 raeburn 5763: sub set_arearole {
1.1172.2.19 raeburn 5764: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5765: unless ($nolog) {
1.567 raeburn 5766: # log the associated role with the area
1.1172.2.19 raeburn 5767: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5768: }
1.743 albertel 5769: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5770: }
5771:
5772: sub custom_roleprivs {
5773: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5774: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5775: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5776: if (&hostname($homsvr) ne '') {
1.567 raeburn 5777: my ($rdummy,$roledef)=
5778: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5779: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5780: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5781: if (defined($syspriv)) {
1.1043 raeburn 5782: if ($trest =~ /^$match_community$/) {
5783: $syspriv =~ s/bre\&S//;
5784: }
1.567 raeburn 5785: $$allroles{'cm./'}.=':'.$syspriv;
5786: $$allroles{$spec.'./'}.=':'.$syspriv;
5787: }
5788: if ($tdomain ne '') {
5789: if (defined($dompriv)) {
5790: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5791: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5792: }
5793: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 5794: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5795: my $rolename = $1;
5796: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5797: }
1.567 raeburn 5798: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5799: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5800: }
5801: }
5802: }
5803: }
5804: }
5805:
1.1172.2.89 raeburn 5806: sub course_adhocrole_privs {
5807: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5808: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5809: if ($overrides{"internal.adhocpriv.$rolename"}) {
5810: my (%currprivs,%storeprivs);
5811: foreach my $item (split(/:/,$coursepriv)) {
5812: my ($priv,$restrict) = split(/\&/,$item);
5813: $currprivs{$priv} = $restrict;
5814: }
5815: my (%possadd,%possremove,%full);
5816: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5817: my ($priv,$restrict)=split(/\&/,$item);
5818: $full{$priv} = $restrict;
5819: }
5820: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5821: next if ($item eq '');
5822: my ($rule,$rest) = split(/=/,$item);
5823: next unless (($rule eq 'off') || ($rule eq 'on'));
5824: foreach my $priv (split(/:/,$rest)) {
5825: if ($priv ne '') {
5826: if ($rule eq 'off') {
5827: $possremove{$priv} = 1;
5828: } else {
5829: $possadd{$priv} = 1;
5830: }
5831: }
5832: }
5833: }
5834: foreach my $priv (sort(keys(%full))) {
5835: if (exists($currprivs{$priv})) {
5836: unless (exists($possremove{$priv})) {
5837: $storeprivs{$priv} = $currprivs{$priv};
5838: }
5839: } elsif (exists($possadd{$priv})) {
5840: $storeprivs{$priv} = $full{$priv};
5841: }
5842: }
5843: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5844: }
5845: return $coursepriv;
5846: }
5847:
1.678 raeburn 5848: sub group_roleprivs {
5849: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5850: my $access = 1;
5851: my $now = time;
5852: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5853: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5854: if ($access) {
1.811 albertel 5855: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5856: $$allgroups{$course}{$group} .=':'.$group_privs;
5857: }
5858: }
1.567 raeburn 5859:
5860: sub standard_roleprivs {
5861: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5862: if (defined($pr{$trole.':s'})) {
5863: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5864: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5865: }
5866: if ($tdomain ne '') {
5867: if (defined($pr{$trole.':d'})) {
5868: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5869: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5870: }
5871: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5872: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5873: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5874: }
5875: }
5876: }
5877:
5878: sub set_userprivs {
1.1064 raeburn 5879: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5880: my $author=0;
5881: my $adv=0;
1.1172.2.91 raeburn 5882: my $rar=0;
1.678 raeburn 5883: my %grouproles = ();
5884: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5885: my @groupkeys;
1.1000 raeburn 5886: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5887: push(@groupkeys,$role);
5888: }
5889: if (ref($groups_roles) eq 'HASH') {
5890: foreach my $key (keys(%{$groups_roles})) {
5891: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5892: push(@groupkeys,$key);
5893: }
5894: }
5895: }
5896: if (@groupkeys > 0) {
5897: foreach my $role (@groupkeys) {
5898: my ($trole,$area,$sec,$extendedarea);
5899: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5900: $trole = $1;
5901: $area = $2;
5902: $sec = $3;
5903: $extendedarea = $area.$sec;
5904: if (exists($$allgroups{$area})) {
5905: foreach my $group (keys(%{$$allgroups{$area}})) {
5906: my $spec = $trole.'.'.$extendedarea;
5907: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5908: $$allgroups{$area}{$group};
1.1064 raeburn 5909: }
1.678 raeburn 5910: }
5911: }
5912: }
5913: }
5914: }
1.800 albertel 5915: foreach my $group (keys(%grouproles)) {
5916: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5917: }
1.800 albertel 5918: foreach my $role (keys(%{$allroles})) {
5919: my %thesepriv;
1.941 raeburn 5920: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5921: foreach my $item (split(/:/,$$allroles{$role})) {
5922: if ($item ne '') {
5923: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5924: if ($restrictions eq '') {
5925: $thesepriv{$privilege}='F';
5926: } elsif ($thesepriv{$privilege} ne 'F') {
5927: $thesepriv{$privilege}.=$restrictions;
5928: }
5929: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 5930: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5931: }
5932: }
5933: my $thesestr='';
1.1104 raeburn 5934: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5935: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5936: }
5937: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5938: }
1.1172.2.91 raeburn 5939: return ($author,$adv,$rar);
1.567 raeburn 5940: }
5941:
1.994 raeburn 5942: sub role_status {
1.1104 raeburn 5943: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5944: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5945: my ($one,$two) = split(m{\./},$rolekey,2);
5946: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5947: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5948: $$where = '/'.$two;
1.994 raeburn 5949: $$trolecode=$$role.'.'.$$where;
5950: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5951: $$tstatus='is';
1.1104 raeburn 5952: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5953: $$tstatus='future';
1.1034 raeburn 5954: if ($$tstart<$now) {
5955: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5956: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5957: my (%allroles,%allgroups,$group_privs,
5958: %groups_roles,@rolecodes);
1.1002 raeburn 5959: my %userroles = (
5960: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5961: );
1.1064 raeburn 5962: @rolecodes = ('cm');
1.1002 raeburn 5963: my $spec=$$role.'.'.$$where;
5964: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5965: if ($$role =~ /^cr\//) {
5966: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5967: push(@rolecodes,'cr');
1.1002 raeburn 5968: } elsif ($$role eq 'gr') {
1.1064 raeburn 5969: push(@rolecodes,$$role);
1.1002 raeburn 5970: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5971: $env{'user.name'});
1.1064 raeburn 5972: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5973: (undef,my $group_privs) = split(/\//,$trole);
5974: $group_privs = &unescape($group_privs);
5975: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5976: 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 5977: &get_groups_roles($tdomain,$trest,
5978: \%course_roles,\@rolecodes,
5979: \%groups_roles);
1.1002 raeburn 5980: } else {
1.1064 raeburn 5981: push(@rolecodes,$$role);
1.1002 raeburn 5982: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5983: }
1.1172.2.91 raeburn 5984: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
5985: \%groups_roles);
1.1064 raeburn 5986: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 5987: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 5988: }
5989: }
1.1034 raeburn 5990: $$tstatus = 'is';
1.1002 raeburn 5991: }
1.994 raeburn 5992: }
5993: if ($$tend) {
1.1104 raeburn 5994: if ($$tend<$update) {
1.994 raeburn 5995: $$tstatus='expired';
5996: } elsif ($$tend<$now) {
5997: $$tstatus='will_not';
5998: }
5999: }
6000: }
6001: }
6002: }
6003:
1.1104 raeburn 6004: sub get_groups_roles {
6005: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6006: return unless((ref($cdom_courseroles) eq 'HASH') &&
6007: (ref($rolecodes) eq 'ARRAY') &&
6008: (ref($groups_roles) eq 'HASH'));
6009: if (keys(%{$cdom_courseroles}) > 0) {
6010: my ($cnum) = ($rest =~ /^($match_courseid)/);
6011: if ($cdom ne '' && $cnum ne '') {
6012: foreach my $key (keys(%{$cdom_courseroles})) {
6013: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6014: my $crsrole = $1;
6015: my $crssec = $2;
6016: if ($crsrole =~ /^cr/) {
6017: unless (grep(/^cr$/,@{$rolecodes})) {
6018: push(@{$rolecodes},'cr');
6019: }
6020: } else {
6021: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6022: push(@{$rolecodes},$crsrole);
6023: }
6024: }
6025: my $rolekey = "$crsrole./$cdom/$cnum";
6026: if ($crssec ne '') {
6027: $rolekey .= "/$crssec";
6028: }
6029: $rolekey .= './';
6030: $groups_roles->{$rolekey} = $rolecodes;
6031: }
6032: }
6033: }
6034: }
6035: return;
6036: }
6037:
6038: sub delete_env_groupprivs {
6039: my ($where,$courseroles,$possroles) = @_;
6040: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6041: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6042: unless (ref($courseroles->{$udom}) eq 'HASH') {
6043: %{$courseroles->{$udom}} =
6044: &get_my_roles('','','userroles',['active'],
6045: $possroles,[$udom],1);
6046: }
6047: if (ref($courseroles->{$udom}) eq 'HASH') {
6048: foreach my $item (keys(%{$courseroles->{$udom}})) {
6049: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6050: my $area = '/'.$cdom.'/'.$cnum;
6051: my $privkey = "user.priv.$crsrole.$area";
6052: if ($crssec ne '') {
6053: $privkey .= '/'.$crssec;
6054: }
6055: $privkey .= ".$area/$group";
6056: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6057: }
6058: }
6059: return;
6060: }
6061:
1.994 raeburn 6062: sub check_adhoc_privs {
1.1172.2.86 raeburn 6063: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6064: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6065: if ($sec) {
6066: $cckey .= '/'.$sec;
6067: }
1.1172.2.9 raeburn 6068: my $setprivs;
1.994 raeburn 6069: if ($env{$cckey}) {
6070: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6071: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6072: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6073: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6074: $setprivs = 1;
1.994 raeburn 6075: }
6076: } else {
1.1172.2.87 raeburn 6077: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6078: $setprivs = 1;
1.994 raeburn 6079: }
1.1172.2.9 raeburn 6080: return $setprivs;
1.994 raeburn 6081: }
6082:
6083: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6084: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6085: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6086: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6087: if ($sec ne '') {
6088: $area .= '/'.$sec;
6089: }
1.994 raeburn 6090: my $spec = $role.'.'.$area;
6091: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6092: $env{'user.name'},1);
1.1172.2.84 raeburn 6093: my %rolehash = ();
1.1172.2.89 raeburn 6094: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6095: my $rolename = $1;
1.1172.2.84 raeburn 6096: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6097: my %domdef = &get_domain_defaults($dcdom);
6098: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6099: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6100: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6101: }
6102: }
1.1172.2.84 raeburn 6103: } else {
6104: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6105: }
1.1172.2.91 raeburn 6106: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6107: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6108: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6109: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6110: &appenv( {'request.role' => $spec,
6111: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6112: 'request.course.sec' => $sec,
1.1088 raeburn 6113: }
6114: );
6115: my $tadv=0;
6116: if (&allowed('adv') eq 'F') { $tadv=1; }
6117: &appenv({'request.role.adv' => $tadv});
6118: }
1.994 raeburn 6119: }
6120:
1.12 www 6121: # --------------------------------------------------------------- get interface
6122:
6123: sub get {
1.131 albertel 6124: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6125: my $items='';
1.800 albertel 6126: foreach my $item (@$storearr) {
6127: $items.=&escape($item).'&';
1.191 harris41 6128: }
1.12 www 6129: $items=~s/\&$//;
1.620 albertel 6130: if (!$udomain) { $udomain=$env{'user.domain'}; }
6131: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6132: my $uhome=&homeserver($uname,$udomain);
6133:
1.133 albertel 6134: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6135: my @pairs=split(/\&/,$rep);
1.273 albertel 6136: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6137: return @pairs;
6138: }
1.15 www 6139: my %returnhash=();
1.42 www 6140: my $i=0;
1.800 albertel 6141: foreach my $item (@$storearr) {
6142: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6143: $i++;
1.191 harris41 6144: }
1.15 www 6145: return %returnhash;
1.27 www 6146: }
6147:
6148: # --------------------------------------------------------------- del interface
6149:
6150: sub del {
1.133 albertel 6151: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6152: my $items='';
1.800 albertel 6153: foreach my $item (@$storearr) {
6154: $items.=&escape($item).'&';
1.191 harris41 6155: }
1.984 neumanie 6156:
1.27 www 6157: $items=~s/\&$//;
1.620 albertel 6158: if (!$udomain) { $udomain=$env{'user.domain'}; }
6159: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6160: my $uhome=&homeserver($uname,$udomain);
6161: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6162: }
6163:
6164: # -------------------------------------------------------------- dump interface
6165:
1.1172.2.22 raeburn 6166: sub unserialize {
6167: my ($rep, $escapedkeys) = @_;
6168:
6169: return {} if $rep =~ /^error/;
6170:
6171: my %returnhash=();
6172: foreach my $item (split(/\&/,$rep)) {
6173: my ($key, $value) = split(/=/, $item, 2);
6174: $key = unescape($key) unless $escapedkeys;
6175: next if $key =~ /^error: 2 /;
6176: $returnhash{$key} = &thaw_unescape($value);
6177: }
6178: return \%returnhash;
6179: }
6180:
6181: # see Lond::dump_with_regexp
6182: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6183: sub dump {
1.1172.2.22 raeburn 6184: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6185: if (!$udomain) { $udomain=$env{'user.domain'}; }
6186: if (!$uname) { $uname=$env{'user.name'}; }
6187: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6188:
1.1172.2.55 raeburn 6189: if ($regexp) {
6190: $regexp=&escape($regexp);
6191: } else {
6192: $regexp='.';
6193: }
1.1172.2.22 raeburn 6194: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6195: # user is hosted on this machine
1.1172.2.55 raeburn 6196: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6197: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6198: return %{&unserialize($reply, $escapedkeys)};
6199: }
1.1166 raeburn 6200: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6201: my @pairs=split(/\&/,$rep);
6202: my %returnhash=();
1.1098 foxr 6203: if (!($rep =~ /^error/ )) {
6204: foreach my $item (@pairs) {
6205: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6206: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6207: next if ($key =~ /^error: 2 /);
6208: $returnhash{$key}=&thaw_unescape($value);
6209: }
1.755 albertel 6210: }
6211: return %returnhash;
1.407 www 6212: }
6213:
1.1098 foxr 6214:
1.717 albertel 6215: # --------------------------------------------------------- dumpstore interface
6216:
6217: sub dumpstore {
6218: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6219: # same as dump but keys must be escaped. They may contain colon separated
6220: # lists of values that may themself contain colons (e.g. symbs).
6221: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6222: }
6223:
1.407 www 6224: # -------------------------------------------------------------- keys interface
6225:
6226: sub getkeys {
6227: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6228: if (!$udomain) { $udomain=$env{'user.domain'}; }
6229: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6230: my $uhome=&homeserver($uname,$udomain);
6231: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6232: my @keyarray=();
1.800 albertel 6233: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6234: next if ($key =~ /^error: 2 /);
1.800 albertel 6235: push(@keyarray,&unescape($key));
1.407 www 6236: }
6237: return @keyarray;
1.318 matthew 6238: }
6239:
1.319 matthew 6240: # --------------------------------------------------------------- currentdump
6241: sub currentdump {
1.328 matthew 6242: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6243: $courseid = $env{'request.course.id'} if (! defined($courseid));
6244: $sdom = $env{'user.domain'} if (! defined($sdom));
6245: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6246: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6247: my $rep;
6248:
6249: if (grep { $_ eq $uhome } current_machine_ids()) {
6250: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6251: $courseid)));
6252: } else {
6253: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6254: }
6255:
1.318 matthew 6256: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6257: #
1.318 matthew 6258: my %returnhash=();
1.319 matthew 6259: #
1.1172.2.93.4 2(raebur 6260:7): if ($rep eq 'unknown_cmd') {
1.319 matthew 6261: # an old lond will not know currentdump
6262: # Do a dump and make it look like a currentdump
1.822 albertel 6263: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6264: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6265: my %hash = @tmp;
6266: @tmp=();
1.424 matthew 6267: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6268: } else {
6269: my @pairs=split(/\&/,$rep);
1.800 albertel 6270: foreach my $pair (@pairs) {
6271: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6272: my ($symb,$param) = split(/:/,$key);
6273: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6274: &thaw_unescape($value);
1.319 matthew 6275: }
1.191 harris41 6276: }
1.12 www 6277: return %returnhash;
1.424 matthew 6278: }
6279:
6280: sub convert_dump_to_currentdump{
6281: my %hash = %{shift()};
6282: my %returnhash;
6283: # Code ripped from lond, essentially. The only difference
6284: # here is the unescaping done by lonnet::dump(). Conceivably
6285: # we might run in to problems with parameter names =~ /^v\./
6286: while (my ($key,$value) = each(%hash)) {
6287: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6288: $symb = &unescape($symb);
6289: $param = &unescape($param);
1.424 matthew 6290: next if ($v eq 'version' || $symb eq 'keys');
6291: next if (exists($returnhash{$symb}) &&
6292: exists($returnhash{$symb}->{$param}) &&
6293: $returnhash{$symb}->{'v.'.$param} > $v);
6294: $returnhash{$symb}->{$param}=$value;
6295: $returnhash{$symb}->{'v.'.$param}=$v;
6296: }
6297: #
6298: # Remove all of the keys in the hashes which keep track of
6299: # the version of the parameter.
6300: while (my ($symb,$param_hash) = each(%returnhash)) {
6301: # use a foreach because we are going to delete from the hash.
6302: foreach my $key (keys(%$param_hash)) {
6303: delete($param_hash->{$key}) if ($key =~ /^v\./);
6304: }
6305: }
6306: return \%returnhash;
1.12 www 6307: }
6308:
1.627 albertel 6309: # ------------------------------------------------------ critical inc interface
6310:
6311: sub cinc {
6312: return &inc(@_,'critical');
6313: }
6314:
1.449 matthew 6315: # --------------------------------------------------------------- inc interface
6316:
6317: sub inc {
1.627 albertel 6318: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6319: if (!$udomain) { $udomain=$env{'user.domain'}; }
6320: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6321: my $uhome=&homeserver($uname,$udomain);
6322: my $items='';
6323: if (! ref($store)) {
6324: # got a single value, so use that instead
6325: $items = &escape($store).'=&';
6326: } elsif (ref($store) eq 'SCALAR') {
6327: $items = &escape($$store).'=&';
6328: } elsif (ref($store) eq 'ARRAY') {
6329: $items = join('=&',map {&escape($_);} @{$store});
6330: } elsif (ref($store) eq 'HASH') {
6331: while (my($key,$value) = each(%{$store})) {
6332: $items.= &escape($key).'='.&escape($value).'&';
6333: }
6334: }
6335: $items=~s/\&$//;
1.627 albertel 6336: if ($critical) {
6337: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6338: } else {
6339: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6340: }
1.449 matthew 6341: }
6342:
1.12 www 6343: # --------------------------------------------------------------- put interface
6344:
6345: sub put {
1.134 albertel 6346: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6347: if (!$udomain) { $udomain=$env{'user.domain'}; }
6348: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6349: my $uhome=&homeserver($uname,$udomain);
1.12 www 6350: my $items='';
1.800 albertel 6351: foreach my $item (keys(%$storehash)) {
6352: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6353: }
1.12 www 6354: $items=~s/\&$//;
1.134 albertel 6355: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6356: }
6357:
1.631 albertel 6358: # ------------------------------------------------------------ newput interface
6359:
6360: sub newput {
6361: my ($namespace,$storehash,$udomain,$uname)=@_;
6362: if (!$udomain) { $udomain=$env{'user.domain'}; }
6363: if (!$uname) { $uname=$env{'user.name'}; }
6364: my $uhome=&homeserver($uname,$udomain);
6365: my $items='';
6366: foreach my $key (keys(%$storehash)) {
6367: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6368: }
6369: $items=~s/\&$//;
6370: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6371: }
6372:
6373: # --------------------------------------------------------- putstore interface
6374:
1.524 raeburn 6375: sub putstore {
1.1172.2.59 raeburn 6376: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6377: if (!$udomain) { $udomain=$env{'user.domain'}; }
6378: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6379: my $uhome=&homeserver($uname,$udomain);
6380: my $items='';
1.715 albertel 6381: foreach my $key (keys(%$storehash)) {
6382: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6383: }
1.715 albertel 6384: $items=~s/\&$//;
1.716 albertel 6385: my $esc_symb=&escape($symb);
6386: my $esc_v=&escape($version);
1.715 albertel 6387: my $reply =
1.716 albertel 6388: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6389: $uhome);
1.1172.2.59 raeburn 6390: if (($tolog) && ($reply eq 'ok')) {
6391: my $namevalue='';
6392: foreach my $key (keys(%{$storehash})) {
6393: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6394: }
6395: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6396: '&host='.&escape($perlvar{'lonHostID'}).
6397: '&version='.$esc_v.
6398: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6399: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6400: }
1.715 albertel 6401: if ($reply eq 'unknown_cmd') {
1.716 albertel 6402: # gfall back to way things use to be done
1.715 albertel 6403: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6404: $uname);
1.524 raeburn 6405: }
1.715 albertel 6406: return $reply;
6407: }
6408:
6409: sub old_putstore {
1.716 albertel 6410: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6411: if (!$udomain) { $udomain=$env{'user.domain'}; }
6412: if (!$uname) { $uname=$env{'user.name'}; }
6413: my $uhome=&homeserver($uname,$udomain);
6414: my %newstorehash;
1.800 albertel 6415: foreach my $item (keys(%$storehash)) {
6416: my $key = $version.':'.&escape($symb).':'.$item;
6417: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6418: }
6419: my $items='';
6420: my %allitems = ();
1.800 albertel 6421: foreach my $item (keys(%newstorehash)) {
6422: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6423: my $key = $1.':keys:'.$2;
6424: $allitems{$key} .= $3.':';
6425: }
1.800 albertel 6426: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6427: }
1.800 albertel 6428: foreach my $item (keys(%allitems)) {
6429: $allitems{$item} =~ s/\:$//;
6430: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6431: }
6432: $items=~s/\&$//;
6433: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6434: }
6435:
1.47 www 6436: # ------------------------------------------------------ critical put interface
6437:
6438: sub cput {
1.134 albertel 6439: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6440: if (!$udomain) { $udomain=$env{'user.domain'}; }
6441: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6442: my $uhome=&homeserver($uname,$udomain);
1.47 www 6443: my $items='';
1.800 albertel 6444: foreach my $item (keys(%$storehash)) {
6445: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6446: }
1.47 www 6447: $items=~s/\&$//;
1.134 albertel 6448: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6449: }
6450:
6451: # -------------------------------------------------------------- eget interface
6452:
6453: sub eget {
1.133 albertel 6454: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6455: my $items='';
1.800 albertel 6456: foreach my $item (@$storearr) {
6457: $items.=&escape($item).'&';
1.191 harris41 6458: }
1.12 www 6459: $items=~s/\&$//;
1.620 albertel 6460: if (!$udomain) { $udomain=$env{'user.domain'}; }
6461: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6462: my $uhome=&homeserver($uname,$udomain);
6463: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6464: my @pairs=split(/\&/,$rep);
6465: my %returnhash=();
1.42 www 6466: my $i=0;
1.800 albertel 6467: foreach my $item (@$storearr) {
6468: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6469: $i++;
1.191 harris41 6470: }
1.12 www 6471: return %returnhash;
6472: }
6473:
1.667 albertel 6474: # ------------------------------------------------------------ tmpput interface
6475: sub tmpput {
1.802 raeburn 6476: my ($storehash,$server,$context)=@_;
1.667 albertel 6477: my $items='';
1.800 albertel 6478: foreach my $item (keys(%$storehash)) {
6479: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6480: }
6481: $items=~s/\&$//;
1.802 raeburn 6482: if (defined($context)) {
6483: $items .= ':'.&escape($context);
6484: }
1.667 albertel 6485: return &reply("tmpput:$items",$server);
6486: }
6487:
6488: # ------------------------------------------------------------ tmpget interface
6489: sub tmpget {
1.688 albertel 6490: my ($token,$server)=@_;
6491: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6492: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6493: my %returnhash;
1.1172.2.85 raeburn 6494: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6495: return %returnhash;
6496: }
1.667 albertel 6497: foreach my $item (split(/\&/,$rep)) {
6498: my ($key,$value)=split(/=/,$item);
6499: $returnhash{&unescape($key)}=&thaw_unescape($value);
6500: }
6501: return %returnhash;
6502: }
6503:
1.1113 raeburn 6504: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6505: sub tmpdel {
6506: my ($token,$server)=@_;
6507: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6508: return &reply("tmpdel:$token",$server);
6509: }
6510:
1.1172.2.13 raeburn 6511: # ------------------------------------------------------------ get_timebased_id
6512:
6513: sub get_timebased_id {
6514: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6515: $maxtries) = @_;
6516: my ($newid,$error,$dellock);
6517: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6518: return ('','ok','invalid call to get suffix');
6519: }
6520:
6521: # set defaults for any optional args for which values were not supplied
6522: if ($who eq '') {
6523: $who = $env{'user.name'}.':'.$env{'user.domain'};
6524: }
6525: if (!$locktries) {
6526: $locktries = 3;
6527: }
6528: if (!$maxtries) {
6529: $maxtries = 10;
6530: }
6531:
6532: if (($cdom eq '') || ($cnum eq '')) {
6533: if ($env{'request.course.id'}) {
6534: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6535: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6536: }
6537: if (($cdom eq '') || ($cnum eq '')) {
6538: return ('','ok','call to get suffix not in course context');
6539: }
6540: }
6541:
6542: # construct locking item
6543: my $lockhash = {
6544: $prefix."\0".'locked_'.$keyid => $who,
6545: };
6546: my $tries = 0;
6547:
6548: # attempt to get lock on nohist_$namespace file
6549: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6550: while (($gotlock ne 'ok') && $tries <$locktries) {
6551: $tries ++;
6552: sleep 1;
6553: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6554: }
6555:
6556: # attempt to get unique identifier, based on current timestamp
6557: if ($gotlock eq 'ok') {
6558: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6559: my $id = time;
6560: $newid = $id;
1.1172.2.56 raeburn 6561: if ($idtype eq 'addcode') {
6562: $newid .= &sixnum_code();
6563: }
1.1172.2.13 raeburn 6564: my $idtries = 0;
6565: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6566: if ($idtype eq 'concat') {
6567: $newid = $id.$idtries;
1.1172.2.56 raeburn 6568: } elsif ($idtype eq 'addcode') {
6569: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6570: } else {
6571: $newid ++;
6572: }
6573: $idtries ++;
6574: }
6575: if (!exists($inuse{$prefix."\0".$newid})) {
6576: my %new_item = (
6577: $prefix."\0".$newid => $who,
6578: );
6579: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6580: $cdom,$cnum);
6581: if ($putresult ne 'ok') {
6582: undef($newid);
6583: $error = 'error saving new item: '.$putresult;
6584: }
6585: } else {
1.1172.2.56 raeburn 6586: undef($newid);
1.1172.2.13 raeburn 6587: $error = ('error: no unique suffix available for the new item ');
6588: }
6589: # remove lock
6590: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6591: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6592: } else {
6593: $error = "error: could not obtain lockfile\n";
6594: $dellock = 'ok';
1.1172.2.58 raeburn 6595: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6596: $dellock = 'nolock';
6597: }
1.1172.2.13 raeburn 6598: }
6599: return ($newid,$dellock,$error);
6600: }
6601:
1.1172.2.56 raeburn 6602: sub sixnum_code {
6603: my $code;
6604: for (0..6) {
6605: $code .= int( rand(9) );
6606: }
6607: return $code;
6608: }
6609:
1.765 albertel 6610: # -------------------------------------------------- portfolio access checking
6611:
6612: sub portfolio_access {
1.1172.2.77 raeburn 6613: my ($requrl,$clientip) = @_;
1.765 albertel 6614: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6615: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6616: if ($result) {
6617: my %setters;
6618: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6619: my ($startblock,$endblock) =
6620: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6621: if ($startblock && $endblock) {
6622: return 'B';
6623: }
6624: } else {
6625: my ($startblock,$endblock) =
6626: &Apache::loncommon::blockcheck(\%setters,'port');
6627: if ($startblock && $endblock) {
6628: return 'B';
6629: }
6630: }
6631: }
1.765 albertel 6632: if ($result eq 'ok') {
1.766 albertel 6633: return 'F';
1.765 albertel 6634: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6635: return 'A';
1.765 albertel 6636: }
1.766 albertel 6637: return '';
1.765 albertel 6638: }
6639:
6640: sub get_portfolio_access {
1.1172.2.77 raeburn 6641: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6642:
6643: if (!ref($access_hash)) {
6644: my $current_perms = &get_portfile_permissions($udom,$unum);
6645: my %access_controls = &get_access_controls($current_perms,$group,
6646: $file_name);
6647: $access_hash = $access_controls{$file_name};
6648: }
6649:
1.1172.2.77 raeburn 6650: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6651: my $now = time;
6652: if (ref($access_hash) eq 'HASH') {
6653: foreach my $key (keys(%{$access_hash})) {
6654: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6655: if ($start > $now) {
6656: next;
6657: }
6658: if ($end && $end<$now) {
6659: next;
6660: }
6661: if ($scope eq 'public') {
6662: $public = $key;
6663: last;
6664: } elsif ($scope eq 'guest') {
6665: $guest = $key;
6666: } elsif ($scope eq 'domains') {
6667: push(@domains,$key);
6668: } elsif ($scope eq 'users') {
6669: push(@users,$key);
6670: } elsif ($scope eq 'course') {
6671: push(@courses,$key);
6672: } elsif ($scope eq 'group') {
6673: push(@groups,$key);
1.1172.2.77 raeburn 6674: } elsif ($scope eq 'ip') {
6675: push(@ips,$key);
1.765 albertel 6676: }
6677: }
6678: if ($public) {
6679: return 'ok';
1.1172.2.77 raeburn 6680: } elsif (@ips > 0) {
6681: my $allowed;
6682: foreach my $ipkey (@ips) {
6683: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6684: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6685: $allowed = 1;
6686: last;
6687: }
6688: }
6689: }
6690: if ($allowed) {
6691: return 'ok';
6692: }
1.765 albertel 6693: }
6694: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6695: if ($guest) {
6696: return $guest;
6697: }
6698: } else {
6699: if (@domains > 0) {
6700: foreach my $domkey (@domains) {
6701: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6702: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6703: return 'ok';
6704: }
6705: }
6706: }
6707: }
6708: if (@users > 0) {
6709: foreach my $userkey (@users) {
1.865 raeburn 6710: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6711: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6712: if (ref($item) eq 'HASH') {
6713: if (($item->{'uname'} eq $env{'user.name'}) &&
6714: ($item->{'udom'} eq $env{'user.domain'})) {
6715: return 'ok';
6716: }
6717: }
6718: }
6719: }
1.765 albertel 6720: }
6721: }
6722: my %roleshash;
6723: my @courses_and_groups = @courses;
6724: push(@courses_and_groups,@groups);
6725: if (@courses_and_groups > 0) {
6726: my (%allgroups,%allroles);
6727: my ($start,$end,$role,$sec,$group);
6728: foreach my $envkey (%env) {
1.1060 raeburn 6729: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6730: my $cid = $2.'_'.$3;
6731: if ($1 eq 'gr') {
6732: $group = $4;
6733: $allgroups{$cid}{$group} = $env{$envkey};
6734: } else {
6735: if ($4 eq '') {
6736: $sec = 'none';
6737: } else {
6738: $sec = $4;
6739: }
6740: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6741: }
1.811 albertel 6742: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6743: my $cid = $2.'_'.$3;
6744: if ($4 eq '') {
6745: $sec = 'none';
6746: } else {
6747: $sec = $4;
6748: }
6749: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6750: }
6751: }
6752: if (keys(%allroles) == 0) {
6753: return;
6754: }
6755: foreach my $key (@courses_and_groups) {
6756: my %content = %{$$access_hash{$key}};
6757: my $cnum = $content{'number'};
6758: my $cdom = $content{'domain'};
6759: my $cid = $cdom.'_'.$cnum;
6760: if (!exists($allroles{$cid})) {
6761: next;
6762: }
6763: foreach my $role_id (keys(%{$content{'roles'}})) {
6764: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6765: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6766: my @status = @{$content{'roles'}{$role_id}{'access'}};
6767: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6768: foreach my $role (keys(%{$allroles{$cid}})) {
6769: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6770: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6771: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6772: if (grep/^all$/,@sections) {
6773: return 'ok';
6774: } else {
6775: if (grep/^$sec$/,@sections) {
6776: return 'ok';
6777: }
6778: }
6779: }
6780: }
6781: if (keys(%{$allgroups{$cid}}) == 0) {
6782: if (grep/^none$/,@groups) {
6783: return 'ok';
6784: }
6785: } else {
6786: if (grep/^all$/,@groups) {
6787: return 'ok';
6788: }
6789: foreach my $group (keys(%{$allgroups{$cid}})) {
6790: if (grep/^$group$/,@groups) {
6791: return 'ok';
6792: }
6793: }
6794: }
6795: }
6796: }
6797: }
6798: }
6799: }
6800: if ($guest) {
6801: return $guest;
6802: }
6803: }
6804: }
6805: return;
6806: }
6807:
6808: sub course_group_datechecker {
6809: my ($dates,$now,$status) = @_;
6810: my ($start,$end) = split(/\./,$dates);
6811: if (!$start && !$end) {
6812: return 'ok';
6813: }
6814: if (grep/^active$/,@{$status}) {
6815: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6816: return 'ok';
6817: }
6818: }
6819: if (grep/^previous$/,@{$status}) {
6820: if ($end > $now ) {
6821: return 'ok';
6822: }
6823: }
6824: if (grep/^future$/,@{$status}) {
6825: if ($start > $now) {
6826: return 'ok';
6827: }
6828: }
6829: return;
6830: }
6831:
6832: sub parse_portfolio_url {
6833: my ($url) = @_;
6834:
6835: my ($type,$udom,$unum,$group,$file_name);
6836:
1.823 albertel 6837: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6838: $type = 1;
6839: $udom = $1;
6840: $unum = $2;
6841: $file_name = $3;
1.823 albertel 6842: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6843: $type = 2;
6844: $udom = $1;
6845: $unum = $2;
6846: $group = $3;
6847: $file_name = $3.'/'.$4;
6848: }
6849: if (wantarray) {
6850: return ($type,$udom,$unum,$file_name,$group);
6851: }
6852: return $type;
6853: }
6854:
6855: sub is_portfolio_url {
6856: my ($url) = @_;
6857: return scalar(&parse_portfolio_url($url));
6858: }
6859:
1.798 raeburn 6860: sub is_portfolio_file {
6861: my ($file) = @_;
1.820 raeburn 6862: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6863: return 1;
6864: }
6865: return;
6866: }
6867:
1.976 raeburn 6868: sub usertools_access {
1.1084 raeburn 6869: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6870: my ($access,%tools);
6871: if ($context eq '') {
6872: $context = 'tools';
6873: }
6874: if ($context eq 'requestcourses') {
6875: %tools = (
6876: official => 1,
6877: unofficial => 1,
1.1006 raeburn 6878: community => 1,
1.1172.2.37 raeburn 6879: textbook => 1,
1.985 raeburn 6880: );
1.1172.2.9 raeburn 6881: } elsif ($context eq 'requestauthor') {
6882: %tools = (
6883: requestauthor => 1,
6884: );
1.985 raeburn 6885: } else {
6886: %tools = (
6887: aboutme => 1,
6888: blog => 1,
1.1172.2.6 raeburn 6889: webdav => 1,
1.985 raeburn 6890: portfolio => 1,
6891: );
6892: }
1.976 raeburn 6893: return if (!defined($tools{$tool}));
6894:
1.1172.2.35 raeburn 6895: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6896: $udom = $env{'user.domain'};
6897: $uname = $env{'user.name'};
6898: }
6899:
1.978 raeburn 6900: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6901: if ($action ne 'reload') {
1.985 raeburn 6902: if ($context eq 'requestcourses') {
6903: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6904: } elsif ($context eq 'requestauthor') {
6905: return $env{'environment.canrequest.author'};
1.985 raeburn 6906: } else {
6907: return $env{'environment.availabletools.'.$tool};
6908: }
6909: }
1.976 raeburn 6910: }
6911:
1.1172.2.9 raeburn 6912: my ($toolstatus,$inststatus,$envkey);
6913: if ($context eq 'requestauthor') {
6914: $envkey = $context;
6915: } else {
6916: $envkey = $context.'.'.$tool;
6917: }
1.976 raeburn 6918:
1.985 raeburn 6919: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6920: ($action ne 'reload')) {
1.1172.2.9 raeburn 6921: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6922: $inststatus = $env{'environment.inststatus'};
6923: } else {
1.1084 raeburn 6924: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6925: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6926: $inststatus = $userenvref->{'inststatus'};
6927: } else {
1.1172.2.9 raeburn 6928: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6929: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6930: $inststatus = $userenv{'inststatus'};
6931: }
1.976 raeburn 6932: }
6933:
6934: if ($toolstatus ne '') {
6935: if ($toolstatus) {
6936: $access = 1;
6937: } else {
6938: $access = 0;
6939: }
6940: return $access;
6941: }
6942:
1.1084 raeburn 6943: my ($is_adv,%domdef);
6944: if (ref($is_advref) eq 'HASH') {
6945: $is_adv = $is_advref->{'is_adv'};
6946: } else {
6947: $is_adv = &is_advanced_user($udom,$uname);
6948: }
6949: if (ref($domdefref) eq 'HASH') {
6950: %domdef = %{$domdefref};
6951: } else {
6952: %domdef = &get_domain_defaults($udom);
6953: }
1.976 raeburn 6954: if (ref($domdef{$tool}) eq 'HASH') {
6955: if ($is_adv) {
6956: if ($domdef{$tool}{'_LC_adv'} ne '') {
6957: if ($domdef{$tool}{'_LC_adv'}) {
6958: $access = 1;
6959: } else {
6960: $access = 0;
6961: }
6962: return $access;
6963: }
6964: }
6965: if ($inststatus ne '') {
6966: my ($hasaccess,$hasnoaccess);
6967: foreach my $affiliation (split(/:/,$inststatus)) {
6968: if ($domdef{$tool}{$affiliation} ne '') {
6969: if ($domdef{$tool}{$affiliation}) {
6970: $hasaccess = 1;
6971: } else {
6972: $hasnoaccess = 1;
6973: }
6974: }
6975: }
6976: if ($hasaccess || $hasnoaccess) {
6977: if ($hasaccess) {
6978: $access = 1;
6979: } elsif ($hasnoaccess) {
6980: $access = 0;
6981: }
6982: return $access;
6983: }
6984: } else {
6985: if ($domdef{$tool}{'default'} ne '') {
6986: if ($domdef{$tool}{'default'}) {
6987: $access = 1;
6988: } elsif ($domdef{$tool}{'default'} == 0) {
6989: $access = 0;
6990: }
6991: return $access;
6992: }
6993: }
6994: } else {
1.1172.2.6 raeburn 6995: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6996: $access = 1;
6997: } else {
6998: $access = 0;
6999: }
1.976 raeburn 7000: return $access;
7001: }
7002: }
7003:
1.1050 raeburn 7004: sub is_course_owner {
7005: my ($cdom,$cnum,$udom,$uname) = @_;
7006: if (($udom eq '') || ($uname eq '')) {
7007: $udom = $env{'user.domain'};
7008: $uname = $env{'user.name'};
7009: }
7010: unless (($udom eq '') || ($uname eq '')) {
7011: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7012: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7013: return 1;
7014: } else {
7015: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7016: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7017: return 1;
7018: }
7019: }
7020: }
7021: }
7022: return;
7023: }
7024:
1.976 raeburn 7025: sub is_advanced_user {
7026: my ($udom,$uname) = @_;
1.1085 raeburn 7027: if ($udom ne '' && $uname ne '') {
7028: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7029: if (wantarray) {
7030: return ($env{'user.adv'},$env{'user.author'});
7031: } else {
7032: return $env{'user.adv'};
7033: }
1.1085 raeburn 7034: }
7035: }
1.976 raeburn 7036: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7037: my %allroles;
1.1128 raeburn 7038: my ($is_adv,$is_author);
1.976 raeburn 7039: foreach my $role (keys(%roleshash)) {
7040: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7041: my $area = '/'.$tdomain.'/'.$trest;
7042: if ($sec ne '') {
7043: $area .= '/'.$sec;
7044: }
7045: if (($area ne '') && ($trole ne '')) {
7046: my $spec=$trole.'.'.$area;
7047: if ($trole =~ /^cr\//) {
7048: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7049: } elsif ($trole ne 'gr') {
7050: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7051: }
1.1128 raeburn 7052: if ($trole eq 'au') {
7053: $is_author = 1;
7054: }
1.976 raeburn 7055: }
7056: }
7057: foreach my $role (keys(%allroles)) {
7058: last if ($is_adv);
7059: foreach my $item (split(/:/,$allroles{$role})) {
7060: if ($item ne '') {
7061: my ($privilege,$restrictions)=split(/&/,$item);
7062: if ($privilege eq 'adv') {
7063: $is_adv = 1;
7064: last;
7065: }
7066: }
7067: }
7068: }
1.1128 raeburn 7069: if (wantarray) {
7070: return ($is_adv,$is_author);
7071: }
1.976 raeburn 7072: return $is_adv;
7073: }
1.798 raeburn 7074:
1.1035 raeburn 7075: sub check_can_request {
1.1036 raeburn 7076: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7077: my $canreq = 0;
7078: my ($types,$typename) = &Apache::loncommon::course_types();
7079: my @options = ('approval','validate','autolimit');
7080: my $optregex = join('|',@options);
7081: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7082: foreach my $type (@{$types}) {
7083: if (&usertools_access($env{'user.name'},
7084: $env{'user.domain'},
7085: $type,undef,'requestcourses')) {
7086: $canreq ++;
1.1036 raeburn 7087: if (ref($request_domains) eq 'HASH') {
7088: push(@{$request_domains->{$type}},$env{'user.domain'});
7089: }
1.1035 raeburn 7090: if ($dom eq $env{'user.domain'}) {
7091: $can_request->{$type} = 1;
7092: }
7093: }
7094: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7095: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7096: if (@curr > 0) {
1.1036 raeburn 7097: foreach my $item (@curr) {
7098: if (ref($request_domains) eq 'HASH') {
7099: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7100: if ($otherdom ne '') {
7101: if (ref($request_domains->{$type}) eq 'ARRAY') {
7102: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7103: push(@{$request_domains->{$type}},$otherdom);
7104: }
7105: } else {
7106: push(@{$request_domains->{$type}},$otherdom);
7107: }
7108: }
7109: }
7110: }
7111: unless($dom eq $env{'user.domain'}) {
7112: $canreq ++;
1.1035 raeburn 7113: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7114: $can_request->{$type} = 1;
7115: }
7116: }
7117: }
7118: }
7119: }
7120: }
7121: return $canreq;
7122: }
7123:
1.341 www 7124: # ---------------------------------------------- Custom access rule evaluation
7125:
7126: sub customaccess {
7127: my ($priv,$uri)=@_;
1.807 albertel 7128: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7129: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7130: $udom = &LONCAPA::clean_domain($udom);
7131: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7132: my $access=0;
1.800 albertel 7133: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7134: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7135: if ($type eq 'user') {
7136: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7137: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7138: if ($tdom) {
7139: if ($tdom ne $env{'user.domain'}) { next; }
7140: }
1.896 albertel 7141: if ($tuname) {
7142: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7143: }
7144: $access=($effect eq 'allow');
7145: last;
7146: }
7147: } else {
7148: if ($role) {
7149: if ($role ne $urole) { next; }
7150: }
7151: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7152: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7153: if ($tdom) {
7154: if ($tdom ne $udom) { next; }
7155: }
7156: if ($tcrs) {
7157: if ($tcrs ne $ucrs) { next; }
7158: }
7159: if ($tsec) {
7160: if ($tsec ne $usec) { next; }
7161: }
7162: $access=($effect eq 'allow');
7163: last;
7164: }
7165: if ($realm eq '' && $role eq '') {
7166: $access=($effect eq 'allow');
7167: }
1.402 bowersj2 7168: }
1.341 www 7169: }
7170: return $access;
7171: }
7172:
1.103 harris41 7173: # ------------------------------------------------- Check for a user privilege
1.12 www 7174:
7175: sub allowed {
1.1172.2.65 raeburn 7176: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7177: my $ver_orguri=$uri;
1.439 www 7178: $uri=&deversion($uri);
1.152 www 7179: my $orguri=$uri;
1.52 www 7180: $uri=&declutter($uri);
1.809 raeburn 7181:
1.810 raeburn 7182: if ($priv eq 'evb') {
7183: # Evade communication block restrictions for specified role in a course
7184: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7185: return $1;
7186: } else {
7187: return;
7188: }
7189: }
7190:
1.620 albertel 7191: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7192: # Free bre access to adm and meta resources
1.1172.2.93.4 2(raebur 7193:7): if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7194: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7195: && ($priv eq 'bre')) {
1.14 www 7196: return 'F';
1.159 www 7197: }
7198:
1.545 banghart 7199: # Free bre access to user's own portfolio contents
1.714 raeburn 7200: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7201: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7202: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7203: my %setters;
7204: my ($startblock,$endblock) =
7205: &Apache::loncommon::blockcheck(\%setters,'port');
7206: if ($startblock && $endblock) {
7207: return 'B';
7208: } else {
7209: return 'F';
7210: }
1.545 banghart 7211: }
7212:
1.762 raeburn 7213: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7214: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7215: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7216: if (exists($env{'request.course.id'})) {
7217: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7218: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7219: if (($domain eq $cdom) && ($name eq $cnum)) {
7220: my $courseprivid=$env{'request.course.id'};
7221: $courseprivid=~s/\_/\//;
7222: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7223: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7224: return $1;
1.762 raeburn 7225: } else {
7226: if ($env{'request.course.sec'}) {
7227: $courseprivid.='/'.$env{'request.course.sec'};
7228: }
7229: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7230: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7231: return $2;
7232: }
1.714 raeburn 7233: }
7234: }
7235: }
7236: }
7237:
1.159 www 7238: # Free bre to public access
7239:
7240: if ($priv eq 'bre') {
1.238 www 7241: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7242: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7243: return 'F';
7244: }
1.238 www 7245: if ($copyright eq 'priv') {
7246: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7247: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7248: return '';
7249: }
7250: }
7251: if ($copyright eq 'domain') {
7252: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7253: unless (($env{'user.domain'} eq $1) ||
7254: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7255: return '';
7256: }
1.262 matthew 7257: }
1.620 albertel 7258: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7259: # Library role, so allow browsing of resources in this domain.
7260: return 'F';
1.238 www 7261: }
1.341 www 7262: if ($copyright eq 'custom') {
7263: unless (&customaccess($priv,$uri)) { return ''; }
7264: }
1.14 www 7265: }
1.264 matthew 7266: # Domain coordinator is trying to create a course
1.620 albertel 7267: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7268: # uri is the requested domain in this case.
7269: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7270: # a role of dc for the domain in question.
1.620 albertel 7271: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7272: }
1.29 www 7273:
1.52 www 7274: my $thisallowed='';
7275: my $statecond=0;
7276: my $courseprivid='';
7277:
1.1039 raeburn 7278: my $ownaccess;
1.1043 raeburn 7279: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7280: if (($priv eq 'bro') && ($env{'user.author'})) {
7281: if ($uri eq '') {
7282: $ownaccess = 1;
7283: } else {
7284: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7285: my $udom = $env{'user.domain'};
7286: my $uname = $env{'user.name'};
7287: if ($uri =~ m{^\Q$udom\E/?$}) {
7288: $ownaccess = 1;
1.1040 raeburn 7289: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7290: unless ($uri =~ m{\.\./}) {
7291: $ownaccess = 1;
7292: }
7293: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7294: my $now = time;
7295: if ($uri =~ m{^([^/]+)/?$}) {
7296: my $adom = $1;
7297: foreach my $key (keys(%env)) {
1.1042 raeburn 7298: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7299: my ($start,$end) = split('.',$env{$key});
7300: if (($now >= $start) && (!$end || $end < $now)) {
7301: $ownaccess = 1;
7302: last;
7303: }
7304: }
7305: }
7306: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7307: my $adom = $1;
7308: my $aname = $2;
1.1042 raeburn 7309: foreach my $role ('ca','aa') {
7310: if ($env{"user.role.$role./$adom/$aname"}) {
7311: my ($start,$end) =
7312: split('.',$env{"user.role.$role./$adom/$aname"});
7313: if (($now >= $start) && (!$end || $end < $now)) {
7314: $ownaccess = 1;
7315: last;
7316: }
1.1039 raeburn 7317: }
7318: }
7319: }
7320: }
7321: }
7322: }
7323: }
7324:
1.52 www 7325: # Course
7326:
1.620 albertel 7327: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7328: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7329: $thisallowed.=$1;
7330: }
1.52 www 7331: }
1.29 www 7332:
1.52 www 7333: # Domain
7334:
1.620 albertel 7335: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7336: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7337: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7338: $thisallowed.=$1;
7339: }
1.12 www 7340: }
1.52 www 7341:
1.1141 raeburn 7342: # User who is not author or co-author might still be able to edit
7343: # resource of an author in the domain (e.g., if Domain Coordinator).
7344: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7345: (&allowed('mdc',$env{'request.course.id'}))) {
7346: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7347: $thisallowed.=$1;
7348: }
7349: }
7350:
1.52 www 7351: # Course: uri itself is a course
1.66 www 7352: my $courseuri=$uri;
7353: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7354: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7355:
1.620 albertel 7356: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7357: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7358: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7359: $thisallowed.=$1;
7360: }
1.12 www 7361: }
1.29 www 7362:
1.665 albertel 7363: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7364: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7365: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7366: $thisallowed='';
1.671 raeburn 7367: my ($match)=&is_on_map($uri);
7368: if ($match) {
7369: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7370: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7371: my $value = $1;
7372: if ($noblockcheck) {
7373: $thisallowed.=$value;
1.1162 raeburn 7374: } else {
1.1172.2.65 raeburn 7375: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7376: if (@blockers > 0) {
7377: $thisallowed = 'B';
7378: } else {
7379: $thisallowed.=$value;
7380: }
1.1162 raeburn 7381: }
1.671 raeburn 7382: }
7383: } else {
1.705 albertel 7384: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7385: if ($refuri) {
7386: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7387: $thisallowed='F';
1.671 raeburn 7388: } else {
7389: $refuri=&declutter($refuri);
7390: my ($match) = &is_on_map($refuri);
7391: if ($match) {
1.1172.2.65 raeburn 7392: if ($noblockcheck) {
1.1162 raeburn 7393: $thisallowed='F';
1.1172.2.65 raeburn 7394: } else {
7395: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7396: if (@blockers > 0) {
7397: $thisallowed = 'B';
7398: } else {
7399: $thisallowed='F';
7400: }
1.1162 raeburn 7401: }
1.671 raeburn 7402: }
1.669 raeburn 7403: }
1.671 raeburn 7404: }
7405: }
1.314 www 7406: }
1.492 albertel 7407:
1.766 albertel 7408: if ($priv eq 'bre'
7409: && $thisallowed ne 'F'
7410: && $thisallowed ne '2'
7411: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7412: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7413: }
7414:
1.52 www 7415: # Full access at system, domain or course-wide level? Exit.
1.29 www 7416: if ($thisallowed=~/F/) {
7417: return 'F';
7418: }
7419:
1.52 www 7420: # If this is generating or modifying users, exit with special codes
1.29 www 7421:
1.643 www 7422: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7423: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7424: my ($audom,$auname)=split('/',$uri);
1.643 www 7425: # no author name given, so this just checks on the general right to make a co-author in this domain
7426: unless ($auname) { return $thisallowed; }
7427: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7428: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7429: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7430: ($audom ne $env{'request.role.domain'}))) { return ''; }
7431: }
1.52 www 7432: return $thisallowed;
7433: }
7434: #
1.103 harris41 7435: # Gathered so far: system, domain and course wide privileges
1.52 www 7436: #
7437: # Course: See if uri or referer is an individual resource that is part of
7438: # the course
7439:
1.620 albertel 7440: if ($env{'request.course.id'}) {
1.232 www 7441:
1.620 albertel 7442: $courseprivid=$env{'request.course.id'};
7443: if ($env{'request.course.sec'}) {
7444: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7445: }
7446: $courseprivid=~s/\_/\//;
7447: my $checkreferer=1;
1.232 www 7448: my ($match,$cond)=&is_on_map($uri);
7449: if ($match) {
7450: $statecond=$cond;
1.620 albertel 7451: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7452: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7453: my $value = $1;
7454: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7455: if ($noblockcheck) {
1.1162 raeburn 7456: $thisallowed.=$value;
1.1172.2.65 raeburn 7457: } else {
7458: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7459: if (@blockers > 0) {
7460: $thisallowed = 'B';
7461: } else {
7462: $thisallowed.=$value;
7463: }
1.1162 raeburn 7464: }
7465: } else {
7466: $thisallowed.=$value;
7467: }
1.52 www 7468: $checkreferer=0;
7469: }
1.29 www 7470: }
1.83 www 7471:
1.148 www 7472: if ($checkreferer) {
1.620 albertel 7473: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7474: unless ($refuri) {
1.800 albertel 7475: foreach my $key (keys(%env)) {
7476: if ($key=~/^httpref\..*\*/) {
7477: my $pattern=$key;
1.156 www 7478: $pattern=~s/^httpref\.\/res\///;
1.148 www 7479: $pattern=~s/\*/\[\^\/\]\+/g;
7480: $pattern=~s/\//\\\//g;
1.152 www 7481: if ($orguri=~/$pattern/) {
1.800 albertel 7482: $refuri=$env{$key};
1.148 www 7483: }
7484: }
1.191 harris41 7485: }
1.148 www 7486: }
1.232 www 7487:
1.148 www 7488: if ($refuri) {
1.152 www 7489: $refuri=&declutter($refuri);
1.232 www 7490: my ($match,$cond)=&is_on_map($refuri);
7491: if ($match) {
7492: my $refstatecond=$cond;
1.620 albertel 7493: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7494: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7495: my $value = $1;
7496: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7497: if ($noblockcheck) {
1.1162 raeburn 7498: $thisallowed.=$value;
1.1172.2.65 raeburn 7499: } else {
7500: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7501: if (@blockers > 0) {
7502: $thisallowed = 'B';
7503: } else {
7504: $thisallowed.=$value;
7505: }
1.1162 raeburn 7506: }
7507: } else {
7508: $thisallowed.=$value;
7509: }
1.53 www 7510: $uri=$refuri;
7511: $statecond=$refstatecond;
1.52 www 7512: }
7513: }
1.148 www 7514: }
1.29 www 7515: }
1.52 www 7516: }
1.29 www 7517:
1.52 www 7518: #
1.103 harris41 7519: # Gathered now: all privileges that could apply, and condition number
1.52 www 7520: #
7521: #
7522: # Full or no access?
7523: #
1.29 www 7524:
1.52 www 7525: if ($thisallowed=~/F/) {
7526: return 'F';
7527: }
1.29 www 7528:
1.52 www 7529: unless ($thisallowed) {
7530: return '';
7531: }
1.29 www 7532:
1.52 www 7533: # Restrictions exist, deal with them
7534: #
7535: # C:according to course preferences
7536: # R:according to resource settings
7537: # L:unless locked
7538: # X:according to user session state
7539: #
7540:
7541: # Possibly locked functionality, check all courses
1.54 www 7542: # Locks might take effect only after 10 minutes cache expiration for other
7543: # courses, and 2 minutes for current course
1.52 www 7544:
7545: my $envkey;
7546: if ($thisallowed=~/L/) {
1.1000 raeburn 7547: foreach $envkey (keys(%env)) {
1.54 www 7548: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7549: my $courseid=$2;
7550: my $roleid=$1.'.'.$2;
1.92 www 7551: $courseid=~s/^\///;
1.54 www 7552: my $expiretime=600;
1.620 albertel 7553: if ($env{'request.role'} eq $roleid) {
1.54 www 7554: $expiretime=120;
7555: }
7556: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7557: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7558: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7559: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7560: }
1.620 albertel 7561: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7562: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7563: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7564: &log($env{'user.domain'},$env{'user.name'},
7565: $env{'user.home'},
1.57 www 7566: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7567: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7568: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7569: return '';
7570: }
7571: }
1.620 albertel 7572: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7573: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7574: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7575: &log($env{'user.domain'},$env{'user.name'},
7576: $env{'user.home'},
1.57 www 7577: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7578: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7579: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7580: return '';
7581: }
7582: }
7583: }
1.29 www 7584: }
1.52 www 7585: }
7586:
7587: #
7588: # Rest of the restrictions depend on selected course
7589: #
7590:
1.620 albertel 7591: unless ($env{'request.course.id'}) {
1.766 albertel 7592: if ($thisallowed eq 'A') {
7593: return 'A';
1.814 raeburn 7594: } elsif ($thisallowed eq 'B') {
7595: return 'B';
1.766 albertel 7596: } else {
7597: return '1';
7598: }
1.52 www 7599: }
1.29 www 7600:
1.52 www 7601: #
7602: # Now user is definitely in a course
7603: #
1.53 www 7604:
7605:
7606: # Course preferences
7607:
7608: if ($thisallowed=~/C/) {
1.620 albertel 7609: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7610: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7611: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7612: =~/\Q$rolecode\E/) {
1.1103 raeburn 7613: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7614: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7615: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7616: $env{'request.course.id'});
7617: }
1.237 www 7618: return '';
7619: }
7620:
1.620 albertel 7621: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7622: =~/\Q$unamedom\E/) {
1.1103 raeburn 7623: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7624: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7625: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7626: $env{'request.course.id'});
7627: }
1.54 www 7628: return '';
7629: }
1.53 www 7630: }
7631:
7632: # Resource preferences
7633:
7634: if ($thisallowed=~/R/) {
1.620 albertel 7635: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7636: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7637: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7638: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7639: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7640: }
7641: return '';
1.54 www 7642: }
1.53 www 7643: }
1.30 www 7644:
1.246 www 7645: # Restricted by state or randomout?
1.30 www 7646:
1.52 www 7647: if ($thisallowed=~/X/) {
1.620 albertel 7648: if ($env{'acc.randomout'}) {
1.579 albertel 7649: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7650: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7651: return '';
7652: }
1.247 www 7653: }
7654: if (&condval($statecond)) {
1.52 www 7655: return '2';
7656: } else {
7657: return '';
7658: }
7659: }
1.30 www 7660:
1.766 albertel 7661: if ($thisallowed eq 'A') {
7662: return 'A';
1.814 raeburn 7663: } elsif ($thisallowed eq 'B') {
7664: return 'B';
1.766 albertel 7665: }
1.52 www 7666: return 'F';
1.232 www 7667: }
1.1162 raeburn 7668:
1.1172.2.13 raeburn 7669: # ------------------------------------------- Check construction space access
7670:
7671: sub constructaccess {
7672: my ($url,$setpriv)=@_;
7673:
7674: # We do not allow editing of previous versions of files
7675: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7676:
7677: # Get username and domain from URL
7678: my ($ownername,$ownerdomain,$ownerhome);
7679:
7680: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7681: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7682:
7683: # The URL does not really point to any authorspace, forget it
7684: unless (($ownername) && ($ownerdomain)) { return ''; }
7685:
7686: # Now we need to see if the user has access to the authorspace of
7687: # $ownername at $ownerdomain
7688:
7689: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7690: # Real author for this?
7691: $ownerhome = $env{'user.home'};
7692: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7693: return ($ownername,$ownerdomain,$ownerhome);
7694: }
7695: } else {
7696: # Co-author for this?
7697: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7698: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7699: $ownerhome = &homeserver($ownername,$ownerdomain);
7700: return ($ownername,$ownerdomain,$ownerhome);
7701: }
7702: }
7703:
7704: # We don't have any access right now. If we are not possibly going to do anything about this,
7705: # we might as well leave
7706: unless ($setpriv) { return ''; }
7707:
7708: # Backdoor access?
7709: my $allowed=&allowed('eco',$ownerdomain);
7710: # Nope
7711: unless ($allowed) { return ''; }
7712: # Looks like we may have access, but could be locked by the owner of the construction space
7713: if ($allowed eq 'U') {
7714: my %blocked=&get('environment',['domcoord.author'],
7715: $ownerdomain,$ownername);
7716: # Is blocked by owner
7717: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7718: }
7719: if (($allowed eq 'F') || ($allowed eq 'U')) {
7720: # Grant temporary access
7721: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7722: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7723: if (!$update) { $update = $then; }
7724: my $refresh=$env{'user.refresh.time'};
7725: if (!$refresh) { $refresh = $update; }
7726: my $now = time;
7727: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7728: $now,'ca','constructaccess');
7729: $ownerhome = &homeserver($ownername,$ownerdomain);
7730: return($ownername,$ownerdomain,$ownerhome);
7731: }
7732: # No business here
7733: return '';
7734: }
7735:
1.1172.2.66 raeburn 7736: # ----------------------------------------------------------- Content Blocking
7737:
7738: {
7739: # Caches for faster Course Contents display where content blocking
7740: # is in operation (i.e., interval param set) for timed quiz.
7741: #
7742: # User for whom data are being temporarily cached.
7743: my $cacheduser='';
7744: # Cached blockers for this user (a hash of blocking items).
7745: my %cachedblockers=();
7746: # When the data were last cached.
7747: my $cachedlast='';
7748:
7749: sub load_all_blockers {
7750: my ($uname,$udom,$blocks)=@_;
7751: if (($uname ne '') && ($udom ne '')) {
7752: if (($cacheduser eq $uname.':'.$udom) &&
7753: (abs($cachedlast-time)<5)) {
7754: return;
7755: }
7756: }
7757: $cachedlast=time;
7758: $cacheduser=$uname.':'.$udom;
7759: %cachedblockers = &get_commblock_resources($blocks);
7760: }
7761:
1.1162 raeburn 7762: sub get_comm_blocks {
7763: my ($cdom,$cnum) = @_;
7764: if ($cdom eq '' || $cnum eq '') {
7765: return unless ($env{'request.course.id'});
7766: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7767: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7768: }
7769: my %commblocks;
7770: my $hashid=$cdom.'_'.$cnum;
7771: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7772: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7773: %commblocks = %{$blocksref};
7774: } else {
7775: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7776: my $cachetime = 600;
7777: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7778: }
7779: return %commblocks;
7780: }
7781:
1.1172.2.66 raeburn 7782: sub get_commblock_resources {
7783: my ($blocks) = @_;
7784: my %blockers = ();
7785: return %blockers unless ($env{'request.course.id'});
7786: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7787: my %commblocks;
7788: if (ref($blocks) eq 'HASH') {
7789: %commblocks = %{$blocks};
7790: } else {
7791: %commblocks = &get_comm_blocks();
7792: }
1.1172.2.66 raeburn 7793: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7794: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7795: return %blockers unless (ref($navmap));
7796: my $now = time;
1.1162 raeburn 7797: foreach my $block (keys(%commblocks)) {
7798: if ($block =~ /^(\d+)____(\d+)$/) {
7799: my ($start,$end) = ($1,$2);
7800: if ($start <= $now && $end >= $now) {
7801: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7802: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7803: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7804: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7805: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7806: }
7807: }
7808: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7809: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7810: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7811: }
7812: }
7813: }
7814: }
7815: }
7816: } elsif ($block =~ /^firstaccess____(.+)$/) {
7817: my $item = $1;
1.1163 raeburn 7818: my @to_test;
1.1162 raeburn 7819: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7820: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7821: my @interval;
7822: my $type = 'map';
7823: if ($item eq 'course') {
7824: $type = 'course';
7825: @interval=&EXT("resource.0.interval");
7826: } else {
7827: if ($item =~ /___\d+___/) {
7828: $type = 'resource';
7829: @interval=&EXT("resource.0.interval",$item);
7830: if (ref($navmap)) {
7831: my $res = $navmap->getBySymb($item);
7832: push(@to_test,$res);
7833: }
1.1162 raeburn 7834: } else {
1.1172.2.66 raeburn 7835: my $mapsymb = &symbread($item,1);
7836: if ($mapsymb) {
7837: if (ref($navmap)) {
7838: my $mapres = $navmap->getBySymb($mapsymb);
7839: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7840: foreach my $res (@to_test) {
7841: my $symb = $res->symb();
7842: next if ($symb eq $mapsymb);
7843: if ($symb ne '') {
7844: @interval=&EXT("resource.0.interval",$symb);
7845: if ($interval[1] eq 'map') {
7846: last;
1.1162 raeburn 7847: }
7848: }
7849: }
7850: }
7851: }
7852: }
1.1172.2.66 raeburn 7853: }
1.1172.2.93.4 1(raebur 7854:7): if ($interval[0] =~ /^(\d+)/) {
7855:7): my $timelimit = $1;
1.1172.2.66 raeburn 7856: my $first_access;
7857: if ($type eq 'resource') {
7858: $first_access=&get_first_access($interval[1],$item);
7859: } elsif ($type eq 'map') {
7860: $first_access=&get_first_access($interval[1],undef,$item);
7861: } else {
7862: $first_access=&get_first_access($interval[1]);
7863: }
7864: if ($first_access) {
1.1172.2.93.4 1(raebur 7865:7): my $timesup = $first_access+$timelimit;
1.1172.2.66 raeburn 7866: if ($timesup > $now) {
7867: my $activeblock;
7868: foreach my $res (@to_test) {
7869: if ($res->answerable()) {
7870: $activeblock = 1;
7871: last;
7872: }
7873: }
7874: if ($activeblock) {
7875: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7876: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7877: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7878: }
7879: }
7880: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7881: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7882: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7883: }
1.1162 raeburn 7884: }
7885: }
7886: }
7887: }
7888: }
7889: }
7890: }
7891: }
7892: }
1.1172.2.66 raeburn 7893: return %blockers;
1.1162 raeburn 7894: }
7895:
1.1172.2.66 raeburn 7896: sub has_comm_blocking {
7897: my ($priv,$symb,$uri,$blocks) = @_;
7898: my @blockers;
7899: return unless ($env{'request.course.id'});
7900: return unless ($priv eq 'bre');
7901: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7902: return if ($env{'request.state'} eq 'construct');
7903: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7904: return unless (keys(%cachedblockers) > 0);
7905: my (%possibles,@symbs);
7906: if (!$symb) {
7907: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7908: }
1.1172.2.66 raeburn 7909: if ($symb) {
7910: @symbs = ($symb);
7911: } elsif (keys(%possibles)) {
7912: @symbs = keys(%possibles);
7913: }
7914: my $noblock;
7915: foreach my $symb (@symbs) {
7916: last if ($noblock);
7917: my ($map,$resid,$resurl)=&decode_symb($symb);
7918: foreach my $block (keys(%cachedblockers)) {
7919: if ($block =~ /^firstaccess____(.+)$/) {
7920: my $item = $1;
7921: if (($item eq $map) || ($item eq $symb)) {
7922: $noblock = 1;
7923: last;
7924: }
1.1162 raeburn 7925: }
1.1172.2.66 raeburn 7926: if (ref($cachedblockers{$block}) eq 'HASH') {
7927: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7928: if ($cachedblockers{$block}{'resources'}{$symb}) {
7929: unless (grep(/^\Q$block\E$/,@blockers)) {
7930: push(@blockers,$block);
7931: }
7932: }
7933: }
7934: }
7935: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7936: if ($cachedblockers{$block}{'maps'}{$map}) {
7937: unless (grep(/^\Q$block\E$/,@blockers)) {
7938: push(@blockers,$block);
7939: }
7940: }
1.1162 raeburn 7941: }
7942: }
7943: }
1.1172.2.66 raeburn 7944: return if ($noblock);
7945: return @blockers;
7946: }
1.1162 raeburn 7947: }
7948:
1.1172.2.66 raeburn 7949: # -------------------------------- Deversion and split uri into path an filename
7950:
1.1133 foxr 7951: #
1.1172.2.66 raeburn 7952: # Removes the version from a URI and
1.1133 foxr 7953: # splits it in to its filename and path to the filename.
7954: # Seems like File::Basename could have done this more clearly.
7955: # Parameters:
7956: # $uri - input URI
7957: # Returns:
7958: # Two element list consisting of
7959: # $pathname - the URI up to and excluding the trailing /
7960: # $filename - The part of the URI following the last /
7961: # NOTE:
7962: # Another realization of this is simply:
7963: # use File::Basename;
7964: # ...
7965: # $uri = shift;
7966: # $filename = basename($uri);
7967: # $path = dirname($uri);
7968: # return ($filename, $path);
7969: #
7970: # The implementation below is probably faster however.
7971: #
1.710 albertel 7972: sub split_uri_for_cond {
7973: my $uri=&deversion(&declutter(shift));
7974: my @uriparts=split(/\//,$uri);
7975: my $filename=pop(@uriparts);
7976: my $pathname=join('/',@uriparts);
7977: return ($pathname,$filename);
7978: }
1.232 www 7979: # --------------------------------------------------- Is a resource on the map?
7980:
7981: sub is_on_map {
1.710 albertel 7982: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7983: #Trying to find the conditional for the file
1.620 albertel 7984: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7985: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7986: if ($match) {
1.289 bowersj2 7987: return (1,$1);
7988: } else {
1.434 www 7989: return (0,0);
1.289 bowersj2 7990: }
1.12 www 7991: }
7992:
1.427 www 7993: # --------------------------------------------------------- Get symb from alias
7994:
7995: sub get_symb_from_alias {
7996: my $symb=shift;
7997: my ($map,$resid,$url)=&decode_symb($symb);
7998: # Already is a symb
7999: if ($url) { return $symb; }
8000: # Must be an alias
8001: my $aliassymb='';
8002: my %bighash;
1.620 albertel 8003: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8004: &GDBM_READER(),0640)) {
8005: my $rid=$bighash{'mapalias_'.$symb};
8006: if ($rid) {
8007: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8008: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8009: $resid,$bighash{'src_'.$rid});
1.427 www 8010: }
8011: untie %bighash;
8012: }
8013: return $aliassymb;
8014: }
8015:
1.12 www 8016: # ----------------------------------------------------------------- Define Role
8017:
8018: sub definerole {
8019: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8020: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8021: foreach my $role (split(':',$sysrole)) {
8022: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8023: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8024: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8025: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8026: return "refused:s:$crole&$cqual";
8027: }
8028: }
1.191 harris41 8029: }
1.800 albertel 8030: foreach my $role (split(':',$domrole)) {
8031: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8032: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8033: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8034: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8035: return "refused:d:$crole&$cqual";
8036: }
8037: }
1.191 harris41 8038: }
1.800 albertel 8039: foreach my $role (split(':',$courole)) {
8040: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8041: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8042: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8043: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8044: return "refused:c:$crole&$cqual";
8045: }
8046: }
1.191 harris41 8047: }
1.1172.2.84 raeburn 8048: my $uhome;
8049: if (($uname ne '') && ($udom ne '')) {
8050: $uhome = &homeserver($uname,$udom);
8051: return $uhome if ($uhome eq 'no_host');
8052: } else {
8053: $uname = $env{'user.name'};
8054: $udom = $env{'user.domain'};
8055: $uhome = $env{'user.home'};
8056: }
1.620 albertel 8057: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8058: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8059: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8060: return reply($command,$uhome);
1.12 www 8061: } else {
8062: return 'refused';
8063: }
1.105 harris41 8064: }
8065:
8066: # ---------------- Make a metadata query against the network of library servers
8067:
8068: sub metadata_query {
1.1172.2.33 raeburn 8069: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8070: my %rhash;
1.845 albertel 8071: my %libserv = &all_library();
1.244 matthew 8072: my @server_list = (defined($server_array) ? @$server_array
8073: : keys(%libserv) );
8074: for my $server (@server_list) {
1.1172.2.33 raeburn 8075: my $domains = '';
8076: if (ref($domains_hash) eq 'HASH') {
8077: $domains = $domains_hash->{$server};
8078: }
1.118 harris41 8079: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8080: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8081: $rhash{$server}=$reply;
8082: }
8083: else {
8084: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8085: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8086: $server);
8087: $rhash{$server}=$reply;
8088: }
1.112 harris41 8089: }
1.118 harris41 8090: return \%rhash;
1.240 www 8091: }
8092:
8093: # ----------------------------------------- Send log queries and wait for reply
8094:
8095: sub log_query {
8096: my ($uname,$udom,$query,%filters)=@_;
8097: my $uhome=&homeserver($uname,$udom);
8098: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8099: my $uhost=&hostname($uhome);
1.800 albertel 8100: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8101: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8102: $uhome);
1.479 albertel 8103: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8104: return get_query_reply($queryid);
8105: }
8106:
1.818 raeburn 8107: # -------------------------- Update MySQL table for portfolio file
8108:
8109: sub update_portfolio_table {
1.821 raeburn 8110: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8111: if ($group ne '') {
8112: $file_name =~s /^\Q$group\E//;
8113: }
1.818 raeburn 8114: my $homeserver = &homeserver($uname,$udom);
8115: my $queryid=
1.821 raeburn 8116: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8117: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8118: my $reply = &get_query_reply($queryid);
8119: return $reply;
8120: }
8121:
1.899 raeburn 8122: # -------------------------- Update MySQL allusers table
8123:
8124: sub update_allusers_table {
8125: my ($uname,$udom,$names) = @_;
8126: my $homeserver = &homeserver($uname,$udom);
8127: my $queryid=
8128: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8129: 'lastname='.&escape($names->{'lastname'}).'%%'.
8130: 'firstname='.&escape($names->{'firstname'}).'%%'.
8131: 'middlename='.&escape($names->{'middlename'}).'%%'.
8132: 'generation='.&escape($names->{'generation'}).'%%'.
8133: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8134: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8135: return;
1.899 raeburn 8136: }
8137:
1.508 raeburn 8138: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8139:
8140: sub fetch_enrollment_query {
1.511 raeburn 8141: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8142: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8143: my $maxtries = 1;
1.508 raeburn 8144: if ($context eq 'automated') {
8145: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8146: $sleep = 2;
8147: $loopmax = 100;
1.547 raeburn 8148: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8149: } else {
8150: $homeserver = &homeserver($cnum,$dom);
8151: }
1.838 albertel 8152: my $host=&hostname($homeserver);
1.506 raeburn 8153: my $cmd = '';
1.1000 raeburn 8154: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8155: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8156: }
8157: $cmd =~ s/%%$//;
8158: $cmd = &escape($cmd);
8159: my $query = 'fetchenrollment';
1.620 albertel 8160: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8161: unless ($queryid=~/^\Q$host\E\_/) {
8162: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8163: return 'error: '.$queryid;
8164: }
1.1172.2.93 raeburn 8165: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8166: my $tries = 1;
8167: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8168: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8169: $tries ++;
8170: }
1.526 raeburn 8171: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8172: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8173: } else {
1.901 albertel 8174: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8175: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8176: foreach my $line (@responses) {
8177: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8178: $$replyref{$key} = $value;
8179: }
8180: } else {
1.1117 foxr 8181: my $pathname = LONCAPA::tempdir();
1.800 albertel 8182: foreach my $line (@responses) {
8183: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8184: $$replyref{$key} = $value;
8185: if ($value > 0) {
1.800 albertel 8186: foreach my $item (@{$$affiliatesref{$key}}) {
8187: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8188: my $destname = $pathname.'/'.$filename;
8189: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8190: if ($xml_classlist =~ /^error/) {
8191: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8192: } else {
1.506 raeburn 8193: if ( open(FILE,">$destname") ) {
8194: print FILE &unescape($xml_classlist);
8195: close(FILE);
1.526 raeburn 8196: } else {
8197: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8198: }
8199: }
8200: }
8201: }
8202: }
8203: }
8204: return 'ok';
8205: }
8206: return 'error';
8207: }
8208:
1.242 www 8209: sub get_query_reply {
1.1172.2.79 raeburn 8210: my ($queryid,$sleep,$loopmax) = @_;
8211: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8212: $sleep = 0.2;
8213: }
8214: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8215: $loopmax = 100;
8216: }
1.1117 foxr 8217: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8218: my $reply='';
1.1172.2.79 raeburn 8219: for (1..$loopmax) {
8220: sleep($sleep);
1.240 www 8221: if (-e $replyfile.'.end') {
1.448 albertel 8222: if (open(my $fh,$replyfile)) {
1.904 albertel 8223: $reply = join('',<$fh>);
8224: close($fh);
1.240 www 8225: } else { return 'error: reply_file_error'; }
1.242 www 8226: return &unescape($reply);
8227: }
1.240 www 8228: }
1.242 www 8229: return 'timeout:'.$queryid;
1.240 www 8230: }
8231:
8232: sub courselog_query {
1.241 www 8233: #
8234: # possible filters:
8235: # url: url or symb
8236: # username
8237: # domain
8238: # action: view, submit, grade
8239: # start: timestamp
8240: # end: timestamp
8241: #
1.240 www 8242: my (%filters)=@_;
1.620 albertel 8243: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8244: if ($filters{'url'}) {
8245: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8246: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8247: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8248: }
1.620 albertel 8249: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8250: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8251: return &log_query($cname,$cdom,'courselog',%filters);
8252: }
8253:
8254: sub userlog_query {
1.858 raeburn 8255: #
8256: # possible filters:
8257: # action: log check role
8258: # start: timestamp
8259: # end: timestamp
8260: #
1.240 www 8261: my ($uname,$udom,%filters)=@_;
8262: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8263: }
8264:
1.506 raeburn 8265: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8266:
8267: sub auto_run {
1.508 raeburn 8268: my ($cnum,$cdom) = @_;
1.876 raeburn 8269: my $response = 0;
8270: my $settings;
8271: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8272: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8273: $settings = $domconfig{'autoenroll'};
8274: if ($settings->{'run'} eq '1') {
8275: $response = 1;
8276: }
8277: } else {
1.934 raeburn 8278: my $homeserver;
8279: if (&is_course($cdom,$cnum)) {
8280: $homeserver = &homeserver($cnum,$cdom);
8281: } else {
8282: $homeserver = &domain($cdom,'primary');
8283: }
8284: if ($homeserver ne 'no_host') {
8285: $response = &reply('autorun:'.$cdom,$homeserver);
8286: }
1.876 raeburn 8287: }
1.506 raeburn 8288: return $response;
8289: }
1.776 albertel 8290:
1.506 raeburn 8291: sub auto_get_sections {
1.508 raeburn 8292: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8293: my $homeserver;
8294: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8295: $homeserver = &homeserver($cnum,$cdom);
8296: }
8297: if (!defined($homeserver)) {
8298: if ($cdom =~ /^$match_domain$/) {
8299: $homeserver = &domain($cdom,'primary');
8300: }
8301: }
8302: my @secs;
8303: if (defined($homeserver)) {
8304: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8305: unless ($response eq 'refused') {
8306: @secs = split(/:/,$response);
8307: }
1.506 raeburn 8308: }
8309: return @secs;
8310: }
1.776 albertel 8311:
1.506 raeburn 8312: sub auto_new_course {
1.1099 raeburn 8313: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8314: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8315: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8316: return $response;
8317: }
1.776 albertel 8318:
1.506 raeburn 8319: sub auto_validate_courseID {
1.508 raeburn 8320: my ($cnum,$cdom,$inst_course_id) = @_;
8321: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8322: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8323: return $response;
8324: }
1.776 albertel 8325:
1.1007 raeburn 8326: sub auto_validate_instcode {
1.1020 raeburn 8327: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8328: my ($homeserver,$response);
8329: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8330: $homeserver = &homeserver($cnum,$cdom);
8331: }
8332: if (!defined($homeserver)) {
8333: if ($cdom =~ /^$match_domain$/) {
8334: $homeserver = &domain($cdom,'primary');
8335: }
8336: }
1.1065 raeburn 8337: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8338: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8339: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8340: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8341: }
8342:
1.506 raeburn 8343: sub auto_create_password {
1.873 raeburn 8344: my ($cnum,$cdom,$authparam,$udom) = @_;
8345: my ($homeserver,$response);
1.506 raeburn 8346: my $create_passwd = 0;
8347: my $authchk = '';
1.873 raeburn 8348: if ($udom =~ /^$match_domain$/) {
8349: $homeserver = &domain($udom,'primary');
8350: }
8351: if ($homeserver eq '') {
8352: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8353: $homeserver = &homeserver($cnum,$cdom);
8354: }
8355: }
8356: if ($homeserver eq '') {
8357: $authchk = 'nodomain';
1.506 raeburn 8358: } else {
1.873 raeburn 8359: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8360: if ($response eq 'refused') {
8361: $authchk = 'refused';
8362: } else {
1.901 albertel 8363: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8364: }
1.506 raeburn 8365: }
8366: return ($authparam,$create_passwd,$authchk);
8367: }
8368:
1.706 raeburn 8369: sub auto_photo_permission {
8370: my ($cnum,$cdom,$students) = @_;
8371: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8372: my ($outcome,$perm_reqd,$conditions) =
8373: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8374: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8375: return (undef,undef);
8376: }
1.706 raeburn 8377: return ($outcome,$perm_reqd,$conditions);
8378: }
8379:
8380: sub auto_checkphotos {
8381: my ($uname,$udom,$pid) = @_;
8382: my $homeserver = &homeserver($uname,$udom);
8383: my ($result,$resulttype);
8384: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8385: &escape($uname).':'.&escape($pid),
8386: $homeserver));
1.709 albertel 8387: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8388: return (undef,undef);
8389: }
1.706 raeburn 8390: if ($outcome) {
8391: ($result,$resulttype) = split(/:/,$outcome);
8392: }
8393: return ($result,$resulttype);
8394: }
8395:
8396: sub auto_photochoice {
8397: my ($cnum,$cdom) = @_;
8398: my $homeserver = &homeserver($cnum,$cdom);
8399: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8400: &escape($cdom),
8401: $homeserver)));
1.709 albertel 8402: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8403: return (undef,undef);
8404: }
1.706 raeburn 8405: return ($update,$comment);
8406: }
8407:
8408: sub auto_photoupdate {
8409: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8410: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8411: my $host=&hostname($homeserver);
1.706 raeburn 8412: my $cmd = '';
8413: my $maxtries = 1;
1.800 albertel 8414: foreach my $affiliate (keys(%{$affiliatesref})) {
8415: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8416: }
8417: $cmd =~ s/%%$//;
8418: $cmd = &escape($cmd);
8419: my $query = 'institutionalphotos';
8420: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8421: unless ($queryid=~/^\Q$host\E\_/) {
8422: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8423: return 'error: '.$queryid;
8424: }
8425: my $reply = &get_query_reply($queryid);
8426: my $tries = 1;
8427: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8428: $reply = &get_query_reply($queryid);
8429: $tries ++;
8430: }
8431: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8432: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8433: } else {
8434: my @responses = split(/:/,$reply);
8435: my $outcome = shift(@responses);
8436: foreach my $item (@responses) {
8437: my ($key,$value) = split(/=/,$item);
8438: $$photo{$key} = $value;
8439: }
8440: return $outcome;
8441: }
8442: return 'error';
8443: }
8444:
1.521 raeburn 8445: sub auto_instcode_format {
1.793 albertel 8446: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8447: $cat_order) = @_;
1.521 raeburn 8448: my $courses = '';
1.772 raeburn 8449: my @homeservers;
1.521 raeburn 8450: if ($caller eq 'global') {
1.841 albertel 8451: my %servers = &get_servers($codedom,'library');
8452: foreach my $tryserver (keys(%servers)) {
8453: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8454: push(@homeservers,$tryserver);
8455: }
1.584 raeburn 8456: }
1.1022 raeburn 8457: } elsif ($caller eq 'requests') {
8458: if ($codedom =~ /^$match_domain$/) {
8459: my $chome = &domain($codedom,'primary');
8460: unless ($chome eq 'no_host') {
8461: push(@homeservers,$chome);
8462: }
8463: }
1.521 raeburn 8464: } else {
1.772 raeburn 8465: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8466: }
1.793 albertel 8467: foreach my $code (keys(%{$instcodes})) {
8468: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8469: }
8470: chop($courses);
1.772 raeburn 8471: my $ok_response = 0;
8472: my $response;
8473: while (@homeservers > 0 && $ok_response == 0) {
8474: my $server = shift(@homeservers);
8475: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8476: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8477: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8478: split(/:/,$response);
1.772 raeburn 8479: %{$codes} = (%{$codes},&str2hash($codes_str));
8480: push(@{$codetitles},&str2array($codetitles_str));
8481: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8482: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8483: $ok_response = 1;
8484: }
8485: }
8486: if ($ok_response) {
1.521 raeburn 8487: return 'ok';
1.772 raeburn 8488: } else {
8489: return $response;
1.521 raeburn 8490: }
8491: }
8492:
1.792 raeburn 8493: sub auto_instcode_defaults {
8494: my ($domain,$returnhash,$code_order) = @_;
8495: my @homeservers;
1.841 albertel 8496:
8497: my %servers = &get_servers($domain,'library');
8498: foreach my $tryserver (keys(%servers)) {
8499: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8500: push(@homeservers,$tryserver);
8501: }
1.792 raeburn 8502: }
1.841 albertel 8503:
1.792 raeburn 8504: my $response;
1.841 albertel 8505: foreach my $server (@homeservers) {
1.792 raeburn 8506: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8507: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8508:
8509: foreach my $pair (split(/\&/,$response)) {
8510: my ($name,$value)=split(/\=/,$pair);
8511: if ($name eq 'code_order') {
8512: @{$code_order} = split(/\&/,&unescape($value));
8513: } else {
8514: $returnhash->{&unescape($name)}=&unescape($value);
8515: }
8516: }
8517: return 'ok';
1.792 raeburn 8518: }
1.841 albertel 8519:
8520: return $response;
1.1003 raeburn 8521: }
8522:
8523: sub auto_possible_instcodes {
1.1007 raeburn 8524: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8525: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8526: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8527: return;
8528: }
1.1003 raeburn 8529: my (@homeservers,$uhome);
8530: if (defined(&domain($domain,'primary'))) {
8531: $uhome=&domain($domain,'primary');
8532: push(@homeservers,&domain($domain,'primary'));
8533: } else {
8534: my %servers = &get_servers($domain,'library');
8535: foreach my $tryserver (keys(%servers)) {
8536: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8537: push(@homeservers,$tryserver);
8538: }
8539: }
8540: }
8541: my $response;
8542: foreach my $server (@homeservers) {
8543: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8544: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8545: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8546: split(':',$response);
8547: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8548: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8549: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8550: my ($name,$value)=split('=',$item);
8551: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8552: }
8553: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8554: my ($name,$value)=split('=',$item);
8555: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8556: }
8557: return 'ok';
8558: }
8559: return $response;
8560: }
1.792 raeburn 8561:
1.1010 raeburn 8562: sub auto_courserequest_checks {
8563: my ($dom) = @_;
1.1020 raeburn 8564: my ($homeserver,%validations);
8565: if ($dom =~ /^$match_domain$/) {
8566: $homeserver = &domain($dom,'primary');
8567: }
8568: unless ($homeserver eq 'no_host') {
8569: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8570: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8571: my @items = split(/&/,$response);
8572: foreach my $item (@items) {
8573: my ($key,$value) = split('=',$item);
8574: $validations{&unescape($key)} = &thaw_unescape($value);
8575: }
8576: }
8577: }
1.1010 raeburn 8578: return %validations;
8579: }
8580:
1.1020 raeburn 8581: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8582: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8583: my ($homeserver,$response);
8584: if ($dom =~ /^$match_domain$/) {
8585: $homeserver = &domain($dom,'primary');
8586: }
1.1172.2.43 raeburn 8587: unless ($homeserver eq 'no_host') {
8588: my $customdata;
8589: if (ref($custominfo) eq 'HASH') {
8590: $customdata = &freeze_escape($custominfo);
8591: }
1.1020 raeburn 8592: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8593: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8594: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8595: $customdata,$homeserver));
1.1020 raeburn 8596: }
8597: return $response;
8598: }
8599:
1.777 albertel 8600: sub auto_validate_class_sec {
1.918 raeburn 8601: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8602: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8603: my $ownerlist;
8604: if (ref($owners) eq 'ARRAY') {
8605: $ownerlist = join(',',@{$owners});
8606: } else {
8607: $ownerlist = $owners;
8608: }
1.773 raeburn 8609: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8610: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8611: return $response;
8612: }
8613:
1.1172.2.38 raeburn 8614: sub auto_crsreq_update {
8615: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8616: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8617: my ($homeserver,%crsreqresponse);
8618: if ($cdom =~ /^$match_domain$/) {
8619: $homeserver = &domain($cdom,'primary');
8620: }
8621: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8622: my $info;
8623: if (ref($inbound) eq 'HASH') {
8624: $info = &freeze_escape($inbound);
8625: }
8626: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8627: ':'.&escape($action).':'.&escape($ownername).':'.
8628: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8629: &escape($title).':'.&escape($code).':'.
8630: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8631: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8632: my @items = split(/&/,$response);
8633: foreach my $item (@items) {
8634: my ($key,$value) = split('=',$item);
8635: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8636: }
8637: }
8638: }
8639: return \%crsreqresponse;
8640: }
8641:
1.1172.2.78 raeburn 8642: sub auto_export_grades {
8643: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8644: my ($homeserver,%exportresponse);
8645: if ($cdom =~ /^$match_domain$/) {
8646: $homeserver = &domain($cdom,'primary');
8647: }
8648: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8649: my $info;
8650: if (ref($inforef) eq 'HASH') {
8651: $info = &freeze_escape($inforef);
8652: }
8653: if (ref($gradesref) eq 'HASH') {
8654: my $grades = &freeze_escape($gradesref);
8655: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8656: $info.':'.$grades,$homeserver);
8657: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8658: my @items = split(/&/,$response);
8659: foreach my $item (@items) {
8660: my ($key,$value) = split('=',$item);
8661: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8662: }
8663: }
8664: }
8665: }
8666: return \%exportresponse;
8667: }
8668:
1.1172.2.68 raeburn 8669: sub check_instcode_cloning {
8670: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8671: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8672: return;
8673: }
8674: my $canclone;
8675: if (@{$code_order} > 0) {
8676: my $instcoderegexp ='^';
8677: my @clonecodes = split(/\&/,$cloner);
8678: foreach my $item (@{$code_order}) {
8679: if (grep(/^\Q$item\E=/,@clonecodes)) {
8680: foreach my $pair (@clonecodes) {
8681: my ($key,$val) = split(/\=/,$pair,2);
8682: $val = &unescape($val);
8683: if ($key eq $item) {
8684: $instcoderegexp .= '('.$val.')';
8685: last;
8686: }
8687: }
8688: } else {
8689: $instcoderegexp .= $codedefaults->{$item};
8690: }
8691: }
8692: $instcoderegexp .= '$';
8693: my (@from,@to);
8694: eval {
8695: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8696: (@to) = ($clonetocode =~ /$instcoderegexp/);
8697: };
8698: if ((@from > 0) && (@to > 0)) {
8699: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8700: if (!@diffs) {
8701: $canclone = 1;
8702: }
8703: }
8704: }
8705: return $canclone;
8706: }
8707:
8708: sub default_instcode_cloning {
8709: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8710: my (%codedefaults,@code_order,$canclone);
8711: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8712: %codedefaults = %{$codedefaultsref};
8713: @code_order = @{$codeorderref};
8714: } elsif ($clonedom) {
8715: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8716: }
8717: if (($domdefclone) && (@code_order)) {
8718: my @clonecodes = split(/\+/,$domdefclone);
8719: my $instcoderegexp ='^';
8720: foreach my $item (@code_order) {
8721: if (grep(/^\Q$item\E$/,@clonecodes)) {
8722: $instcoderegexp .= '('.$codedefaults{$item}.')';
8723: } else {
8724: $instcoderegexp .= $codedefaults{$item};
8725: }
8726: }
8727: $instcoderegexp .= '$';
8728: my (@from,@to);
8729: eval {
8730: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8731: (@to) = ($clonetocode =~ /$instcoderegexp/);
8732: };
8733: if ((@from > 0) && (@to > 0)) {
8734: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8735: if (!@diffs) {
8736: $canclone = 1;
8737: }
8738: }
8739: }
8740: return $canclone;
8741: }
8742:
1.679 raeburn 8743: # ------------------------------------------------------- Course Group routines
8744:
8745: sub get_coursegroups {
1.809 raeburn 8746: my ($cdom,$cnum,$group,$namespace) = @_;
8747: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8748: }
8749:
1.679 raeburn 8750: sub modify_coursegroup {
8751: my ($cdom,$cnum,$groupsettings) = @_;
8752: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8753: }
8754:
1.809 raeburn 8755: sub toggle_coursegroup_status {
8756: my ($cdom,$cnum,$group,$action) = @_;
8757: my ($from_namespace,$to_namespace);
8758: if ($action eq 'delete') {
8759: $from_namespace = 'coursegroups';
8760: $to_namespace = 'deleted_groups';
8761: } else {
8762: $from_namespace = 'deleted_groups';
8763: $to_namespace = 'coursegroups';
8764: }
8765: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8766: if (my $tmp = &error(%curr_group)) {
8767: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8768: return ('read error',$tmp);
8769: } else {
8770: my %savedsettings = %curr_group;
1.809 raeburn 8771: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8772: my $deloutcome;
8773: if ($result eq 'ok') {
1.809 raeburn 8774: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8775: } else {
8776: return ('write error',$result);
8777: }
8778: if ($deloutcome eq 'ok') {
8779: return 'ok';
8780: } else {
8781: return ('delete error',$deloutcome);
8782: }
8783: }
8784: }
8785:
1.679 raeburn 8786: sub modify_group_roles {
1.957 raeburn 8787: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8788: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8789: my $role = 'gr/'.&escape($userprivs);
8790: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8791: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8792: if ($result eq 'ok') {
8793: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8794: }
1.679 raeburn 8795: return $result;
8796: }
8797:
8798: sub modify_coursegroup_membership {
8799: my ($cdom,$cnum,$membership) = @_;
8800: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8801: return $result;
8802: }
8803:
1.682 raeburn 8804: sub get_active_groups {
8805: my ($udom,$uname,$cdom,$cnum) = @_;
8806: my $now = time;
8807: my %groups = ();
8808: foreach my $key (keys(%env)) {
1.811 albertel 8809: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8810: my ($start,$end) = split(/\./,$env{$key});
8811: if (($end!=0) && ($end<$now)) { next; }
8812: if (($start!=0) && ($start>$now)) { next; }
8813: if ($1 eq $cdom && $2 eq $cnum) {
8814: $groups{$3} = $env{$key} ;
8815: }
8816: }
8817: }
8818: return %groups;
8819: }
8820:
1.683 raeburn 8821: sub get_group_membership {
8822: my ($cdom,$cnum,$group) = @_;
8823: return(&dump('groupmembership',$cdom,$cnum,$group));
8824: }
8825:
8826: sub get_users_groups {
8827: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8828: my @usersgroups;
1.683 raeburn 8829: my $cachetime=1800;
8830:
8831: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8832: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8833: if (defined($cached)) {
1.734 albertel 8834: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8835: } else {
8836: $grouplist = '';
1.816 raeburn 8837: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8838: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8839: my $access_end = $env{'course.'.$courseid.
8840: '.default_enrollment_end_date'};
8841: my $now = time;
8842: foreach my $key (keys(%roleshash)) {
8843: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8844: my $group = $1;
8845: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8846: my $start = $2;
8847: my $end = $1;
8848: if ($start == -1) { next; } # deleted from group
8849: if (($start!=0) && ($start>$now)) { next; }
8850: if (($end!=0) && ($end<$now)) {
8851: if ($access_end && $access_end < $now) {
8852: if ($access_end - $end < 86400) {
8853: push(@usersgroups,$group);
1.733 raeburn 8854: }
8855: }
1.817 raeburn 8856: next;
1.733 raeburn 8857: }
1.817 raeburn 8858: push(@usersgroups,$group);
1.683 raeburn 8859: }
8860: }
8861: }
1.817 raeburn 8862: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8863: $grouplist = join(':',@usersgroups);
8864: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8865: }
1.733 raeburn 8866: return @usersgroups;
1.683 raeburn 8867: }
8868:
8869: sub devalidate_getgroups_cache {
8870: my ($udom,$uname,$cdom,$cnum)=@_;
8871: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8872:
1.683 raeburn 8873: my $hashid="$udom:$uname:$courseid";
8874: &devalidate_cache_new('getgroups',$hashid);
8875: }
8876:
1.12 www 8877: # ------------------------------------------------------------------ Plain Text
8878:
8879: sub plaintext {
1.988 raeburn 8880: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8881: if ($short =~ m{^cr/}) {
1.758 albertel 8882: return (split('/',$short))[-1];
8883: }
1.742 raeburn 8884: if (!defined($cid)) {
8885: $cid = $env{'request.course.id'};
8886: }
8887: my %rolenames = (
1.1008 raeburn 8888: Course => 'std',
8889: Community => 'alt1',
1.742 raeburn 8890: );
1.1037 raeburn 8891: if ($cid ne '') {
8892: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8893: unless ($forcedefault) {
8894: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8895: &Apache::lonlocal::mt_escape(\$roletext);
8896: return &Apache::lonlocal::mt($roletext);
8897: }
8898: }
8899: }
8900: if ((defined($type)) && (defined($rolenames{$type})) &&
8901: (defined($rolenames{$type})) &&
8902: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8903: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8904: } elsif ($cid ne '') {
8905: my $crstype = $env{'course.'.$cid.'.type'};
8906: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8907: (defined($prp{$short}{$rolenames{$crstype}}))) {
8908: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8909: }
1.742 raeburn 8910: }
1.1037 raeburn 8911: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8912: }
8913:
8914: # ----------------------------------------------------------------- Assign Role
8915:
8916: sub assignrole {
1.957 raeburn 8917: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8918: $context)=@_;
1.21 www 8919: my $mrole;
8920: if ($role =~ /^cr\//) {
1.393 www 8921: my $cwosec=$url;
1.811 albertel 8922: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8923: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8924: my $refused = 1;
8925: if ($context eq 'requestcourses') {
8926: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8927: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8928: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8929: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8930: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8931: if ($crsenv{'internal.courseowner'} eq
8932: $env{'user.name'}.':'.$env{'user.domain'}) {
8933: $refused = '';
8934: }
8935: }
8936: }
8937: }
8938: }
8939: if ($refused) {
8940: &logthis('Refused custom assignrole: '.
8941: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8942: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8943: return 'refused';
8944: }
1.104 www 8945: }
1.21 www 8946: $mrole='cr';
1.678 raeburn 8947: } elsif ($role =~ /^gr\//) {
8948: my $cwogrp=$url;
1.811 albertel 8949: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8950: unless (&allowed('mdg',$cwogrp)) {
8951: &logthis('Refused group assignrole: '.
8952: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8953: $env{'user.name'}.' at '.$env{'user.domain'});
8954: return 'refused';
8955: }
8956: $mrole='gr';
1.21 www 8957: } else {
1.82 www 8958: my $cwosec=$url;
1.811 albertel 8959: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8960: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8961: my $refused;
8962: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8963: if (!(&allowed('c'.$role,$url))) {
8964: $refused = 1;
8965: }
8966: } else {
8967: $refused = 1;
8968: }
1.947 raeburn 8969: if ($refused) {
1.1045 raeburn 8970: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8971: if (!$selfenroll && $context eq 'course') {
8972: my %crsenv;
8973: if ($role eq 'cc' || $role eq 'co') {
8974: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8975: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8976: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8977: if ($crsenv{'internal.courseowner'} eq
8978: $env{'user.name'}.':'.$env{'user.domain'}) {
8979: $refused = '';
8980: }
8981: }
8982: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8983: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8984: if ($crsenv{'internal.courseowner'} eq
8985: $env{'user.name'}.':'.$env{'user.domain'}) {
8986: $refused = '';
8987: }
8988: }
8989: }
8990: }
8991: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8992: $refused = '';
1.1017 raeburn 8993: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8994: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8995: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8996: my $wrongcc;
8997: if ($cnum =~ /^$match_community$/) {
8998: $wrongcc = 1 if ($role eq 'cc');
8999: } else {
9000: $wrongcc = 1 if ($role eq 'co');
9001: }
9002: unless ($wrongcc) {
9003: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9004: if ($crsenv{'internal.courseowner'} eq
9005: $env{'user.name'}.':'.$env{'user.domain'}) {
9006: $refused = '';
9007: }
1.1017 raeburn 9008: }
9009: }
1.1172.2.9 raeburn 9010: } elsif ($context eq 'requestauthor') {
9011: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9012: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9013: if ($env{'environment.requestauthor'} eq 'automatic') {
9014: $refused = '';
9015: } else {
9016: my %domdefaults = &get_domain_defaults($udom);
9017: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9018: my $checkbystatus;
9019: if ($env{'user.adv'}) {
9020: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9021: if ($disposition eq 'automatic') {
9022: $refused = '';
9023: } elsif ($disposition eq '') {
9024: $checkbystatus = 1;
9025: }
9026: } else {
9027: $checkbystatus = 1;
9028: }
9029: if ($checkbystatus) {
9030: if ($env{'environment.inststatus'}) {
9031: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9032: foreach my $type (@inststatuses) {
9033: if (($type ne '') &&
9034: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9035: $refused = '';
9036: }
9037: }
9038: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9039: $refused = '';
9040: }
9041: }
9042: }
9043: }
9044: }
1.1017 raeburn 9045: }
9046: if ($refused) {
1.947 raeburn 9047: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9048: ' '.$role.' '.$end.' '.$start.' by '.
9049: $env{'user.name'}.' at '.$env{'user.domain'});
9050: return 'refused';
9051: }
1.932 raeburn 9052: }
1.1131 raeburn 9053: } elsif ($role eq 'au') {
9054: if ($url ne '/'.$udom.'/') {
9055: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9056: ' to assign author role for '.$uname.':'.$udom.
9057: ' in domain: '.$url.' refused (wrong domain).');
9058: return 'refused';
9059: }
1.104 www 9060: }
1.21 www 9061: $mrole=$role;
9062: }
1.620 albertel 9063: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9064: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9065: if ($end) { $command.='_'.$end; }
1.21 www 9066: if ($start) {
9067: if ($end) {
1.81 www 9068: $command.='_'.$start;
1.21 www 9069: } else {
1.81 www 9070: $command.='_0_'.$start;
1.21 www 9071: }
9072: }
1.739 raeburn 9073: my $origstart = $start;
9074: my $origend = $end;
1.957 raeburn 9075: my $delflag;
1.357 www 9076: # actually delete
9077: if ($deleteflag) {
1.373 www 9078: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9079: # modify command to delete the role
1.620 albertel 9080: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9081: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9082: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9083: # set start and finish to negative values for userrolelog
9084: $start=-1;
9085: $end=-1;
1.957 raeburn 9086: $delflag = 1;
1.357 www 9087: }
9088: }
9089: # send command
1.349 www 9090: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9091: # log new user role if status is ok
1.349 www 9092: if ($answer eq 'ok') {
1.663 raeburn 9093: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9094: if (($role eq 'cc') || ($role eq 'in') ||
9095: ($role eq 'ep') || ($role eq 'ad') ||
9096: ($role eq 'ta') || ($role eq 'st') ||
9097: ($role=~/^cr/) || ($role eq 'gr') ||
9098: ($role eq 'co')) {
1.1172.2.13 raeburn 9099: # for course roles, perform group memberships changes triggered by role change.
9100: unless ($role =~ /^gr/) {
9101: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9102: $origstart,$selfenroll,$context);
9103: }
1.1172.2.9 raeburn 9104: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9105: $selfenroll,$context);
9106: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9107: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9108: ($role eq 'da')) {
1.1172.2.9 raeburn 9109: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9110: $context);
9111: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9112: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9113: $context);
9114: }
1.1053 raeburn 9115: if ($role eq 'cc') {
9116: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9117: }
1.349 www 9118: }
9119: return $answer;
1.169 harris41 9120: }
9121:
1.1053 raeburn 9122: sub autoupdate_coowners {
9123: my ($url,$end,$start,$uname,$udom) = @_;
9124: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9125: if (($cdom ne '') && ($cnum ne '')) {
9126: my $now = time;
9127: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9128: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9129: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9130: my $instcode = $coursehash{'internal.coursecode'};
9131: if ($instcode ne '') {
1.1056 raeburn 9132: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9133: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9134: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9135: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9136: if ($result eq 'valid') {
9137: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9138: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9139: push(@newcoowners,$coowner);
9140: }
9141: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9142: push(@newcoowners,$uname.':'.$udom);
9143: }
9144: @newcoowners = sort(@newcoowners);
9145: } else {
9146: push(@newcoowners,$uname.':'.$udom);
9147: }
9148: } else {
9149: if ($coursehash{'internal.co-owners'}) {
9150: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9151: unless ($coowner eq $uname.':'.$udom) {
9152: push(@newcoowners,$coowner);
9153: }
9154: }
9155: unless (@newcoowners > 0) {
9156: $delcoowners = 1;
9157: $coowners = '';
9158: }
9159: }
9160: }
9161: if (@newcoowners || $delcoowners) {
9162: &store_coowners($cdom,$cnum,$coursehash{'home'},
9163: $delcoowners,@newcoowners);
9164: }
9165: }
9166: }
9167: }
9168: }
9169: }
9170: }
9171:
9172: sub store_coowners {
9173: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9174: my $cid = $cdom.'_'.$cnum;
9175: my ($coowners,$delresult,$putresult);
9176: if (@newcoowners) {
9177: $coowners = join(',',@newcoowners);
9178: my %coownershash = (
9179: 'internal.co-owners' => $coowners,
9180: );
9181: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9182: if ($putresult eq 'ok') {
9183: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9184: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9185: }
9186: }
9187: }
9188: if ($delcoowners) {
9189: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9190: if ($delresult eq 'ok') {
9191: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9192: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9193: }
9194: }
9195: }
9196: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9197: my %crsinfo =
9198: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9199: if (ref($crsinfo{$cid}) eq 'HASH') {
9200: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9201: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9202: }
9203: }
9204: }
9205:
1.169 harris41 9206: # -------------------------------------------------- Modify user authentication
1.197 www 9207: # Overrides without validation
9208:
1.169 harris41 9209: sub modifyuserauth {
9210: my ($udom,$uname,$umode,$upass)=@_;
9211: my $uhome=&homeserver($uname,$udom);
1.197 www 9212: unless (&allowed('mau',$udom)) { return 'refused'; }
9213: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9214: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9215: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9216: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9217: &escape($upass),$uhome);
1.620 albertel 9218: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9219: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9220: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9221: &log($udom,,$uname,$uhome,
1.620 albertel 9222: 'Authentication changed by '.$env{'user.domain'}.', '.
9223: $env{'user.name'}.', '.$umode.
1.197 www 9224: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9225: unless ($reply eq 'ok') {
1.197 www 9226: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9227: return 'error: '.$reply;
9228: }
1.170 harris41 9229: return 'ok';
1.80 www 9230: }
9231:
1.81 www 9232: # --------------------------------------------------------------- Modify a user
1.80 www 9233:
1.81 www 9234: sub modifyuser {
1.206 matthew 9235: my ($udom, $uname, $uid,
9236: $umode, $upass, $first,
9237: $middle, $last, $gene,
1.1058 raeburn 9238: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9239: $udom= &LONCAPA::clean_domain($udom);
9240: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9241: my $showcandelete = 'none';
9242: if (ref($candelete) eq 'ARRAY') {
9243: if (@{$candelete} > 0) {
9244: $showcandelete = join(', ',@{$candelete});
9245: }
9246: }
1.81 www 9247: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9248: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9249: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9250: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9251: ' desiredhome not specified').
1.620 albertel 9252: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9253: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9254: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9255: my $newuser;
9256: if ($uhome eq 'no_host') {
9257: $newuser = 1;
9258: }
1.80 www 9259: # ----------------------------------------------------------------- Create User
1.406 albertel 9260: if (($uhome eq 'no_host') &&
9261: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9262: my $unhome='';
1.844 albertel 9263: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9264: $unhome = $desiredhome;
1.620 albertel 9265: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9266: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9267: } else { # load balancing routine for determining $unhome
1.81 www 9268: my $loadm=10000000;
1.841 albertel 9269: my %servers = &get_servers($udom,'library');
9270: foreach my $tryserver (keys(%servers)) {
9271: my $answer=reply('load',$tryserver);
9272: if (($answer=~/\d+/) && ($answer<$loadm)) {
9273: $loadm=$answer;
9274: $unhome=$tryserver;
9275: }
1.80 www 9276: }
9277: }
9278: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9279: return 'error: unable to find a home server for '.$uname.
9280: ' in domain '.$udom;
1.80 www 9281: }
9282: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9283: &escape($upass),$unhome);
9284: unless ($reply eq 'ok') {
9285: return 'error: '.$reply;
9286: }
1.230 stredwic 9287: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9288: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9289: return 'error: unable verify users home machine.';
1.80 www 9290: }
1.209 matthew 9291: } # End of creation of new user
1.80 www 9292: # ---------------------------------------------------------------------- Add ID
9293: if ($uid) {
9294: $uid=~tr/A-Z/a-z/;
9295: my %uidhash=&idrget($udom,$uname);
1.196 www 9296: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9297: && (!$forceid)) {
1.80 www 9298: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9299: return 'error: user id "'.$uid.'" does not match '.
9300: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9301: }
9302: } else {
9303: &idput($udom,($uname => $uid));
9304: }
9305: }
9306: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9307: my @tmp=&get('environment',
1.899 raeburn 9308: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9309: 'permanentemail','inststatus'],
1.134 albertel 9310: $udom,$uname);
1.1075 raeburn 9311: my (%names,%oldnames);
1.313 matthew 9312: if ($tmp[0] =~ m/^error:.*/) {
9313: %names=();
9314: } else {
9315: %names = @tmp;
1.1075 raeburn 9316: %oldnames = %names;
1.313 matthew 9317: }
1.388 www 9318: #
1.1058 raeburn 9319: # If name, email and/or uid are blank (e.g., because an uploaded file
9320: # of users did not contain them), do not overwrite existing values
9321: # unless field is in $candelete array ref.
9322: #
9323:
9324: my @fields = ('firstname','middlename','lastname','generation',
9325: 'permanentemail','id');
9326: my %newvalues;
9327: if (ref($candelete) eq 'ARRAY') {
9328: foreach my $field (@fields) {
9329: if (grep(/^\Q$field\E$/,@{$candelete})) {
9330: if ($field eq 'firstname') {
9331: $names{$field} = $first;
9332: } elsif ($field eq 'middlename') {
9333: $names{$field} = $middle;
9334: } elsif ($field eq 'lastname') {
9335: $names{$field} = $last;
9336: } elsif ($field eq 'generation') {
9337: $names{$field} = $gene;
9338: } elsif ($field eq 'permanentemail') {
9339: $names{$field} = $email;
9340: } elsif ($field eq 'id') {
9341: $names{$field} = $uid;
9342: }
9343: }
9344: }
9345: }
1.388 www 9346: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9347: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9348: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9349: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9350: if ($email) {
9351: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9352: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9353: }
1.899 raeburn 9354: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9355: if (defined($inststatus)) {
9356: $names{'inststatus'} = '';
9357: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9358: if (ref($usertypes) eq 'HASH') {
9359: my @okstatuses;
9360: foreach my $item (split(/:/,$inststatus)) {
9361: if (defined($usertypes->{$item})) {
9362: push(@okstatuses,$item);
9363: }
9364: }
9365: if (@okstatuses) {
9366: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9367: }
9368: }
9369: }
1.1075 raeburn 9370: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9371: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9372: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9373: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9374: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9375: } else {
9376: $logmsg .= ' during self creation';
9377: }
1.1075 raeburn 9378: my $changed;
9379: if ($newuser) {
9380: $changed = 1;
9381: } else {
9382: foreach my $field (@fields) {
9383: if ($names{$field} ne $oldnames{$field}) {
9384: $changed = 1;
9385: last;
9386: }
9387: }
9388: }
9389: unless ($changed) {
9390: $logmsg = 'No changes in user information needed for: '.$logmsg;
9391: &logthis($logmsg);
9392: return 'ok';
9393: }
9394: my $reply = &put('environment', \%names, $udom,$uname);
9395: if ($reply ne 'ok') {
9396: return 'error: '.$reply;
9397: }
1.1087 raeburn 9398: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9399: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9400: }
1.1075 raeburn 9401: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9402: &devalidate_cache_new('namescache',$uname.':'.$udom);
9403: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9404: &logthis($logmsg);
1.134 albertel 9405: return 'ok';
1.80 www 9406: }
9407:
1.81 www 9408: # -------------------------------------------------------------- Modify student
1.80 www 9409:
1.81 www 9410: sub modifystudent {
9411: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9412: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9413: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9414: if (!$cid) {
1.620 albertel 9415: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9416: return 'not_in_class';
9417: }
1.80 www 9418: }
9419: # --------------------------------------------------------------- Make the user
1.81 www 9420: my $reply=&modifyuser
1.209 matthew 9421: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9422: $desiredhome,$email,$inststatus);
1.80 www 9423: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9424: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9425: # student's environment
1.297 matthew 9426: $uid = undef if (!$forceid);
1.455 albertel 9427: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9428: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9429: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9430: return $reply;
9431: }
9432:
9433: sub modify_student_enrollment {
1.1172.2.23 raeburn 9434: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9435: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9436: my ($cdom,$cnum,$chome);
9437: if (!$cid) {
1.620 albertel 9438: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9439: return 'not_in_class';
9440: }
1.620 albertel 9441: $cdom=$env{'course.'.$cid.'.domain'};
9442: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9443: } else {
9444: ($cdom,$cnum)=split(/_/,$cid);
9445: }
1.620 albertel 9446: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9447: if (!$chome) {
1.457 raeburn 9448: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9449: }
1.455 albertel 9450: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9451: # Make sure the user exists
1.81 www 9452: my $uhome=&homeserver($uname,$udom);
9453: if (($uhome eq '') || ($uhome eq 'no_host')) {
9454: return 'error: no such user';
9455: }
1.297 matthew 9456: # Get student data if we were not given enough information
9457: if (!defined($first) || $first eq '' ||
9458: !defined($last) || $last eq '' ||
9459: !defined($uid) || $uid eq '' ||
9460: !defined($middle) || $middle eq '' ||
9461: !defined($gene) || $gene eq '') {
1.294 matthew 9462: # They did not supply us with enough data to enroll the student, so
9463: # we need to pick up more information.
1.297 matthew 9464: my %tmp = &get('environment',
1.294 matthew 9465: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9466: ,$udom,$uname);
9467:
1.800 albertel 9468: #foreach my $key (keys(%tmp)) {
9469: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9470: #}
1.294 matthew 9471: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9472: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9473: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9474: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9475: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9476: }
1.556 albertel 9477: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9478: my $user = "$uname:$udom";
9479: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9480: my $reply=cput('classlist',
1.1148 raeburn 9481: {$user =>
1.1172.2.76 raeburn 9482: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9483: $cdom,$cnum);
1.1148 raeburn 9484: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9485: &devalidate_getsection_cache($udom,$uname,$cid);
9486: } else {
1.81 www 9487: return 'error: '.$reply;
9488: }
1.297 matthew 9489: # Add student role to user
1.83 www 9490: my $uurl='/'.$cid;
1.81 www 9491: $uurl=~s/\_/\//g;
9492: if ($usec) {
9493: $uurl.='/'.$usec;
9494: }
1.1148 raeburn 9495: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9496: $selfenroll,$context);
9497: if ($result ne 'ok') {
9498: if ($old_entry{$user} ne '') {
9499: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9500: } else {
9501: $reply = &del('classlist',[$user],$cdom,$cnum);
9502: }
9503: }
9504: return $result;
1.21 www 9505: }
9506:
1.556 albertel 9507: sub format_name {
9508: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9509: my $name;
9510: if ($first ne 'lastname') {
9511: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9512: } else {
9513: if ($lastname=~/\S/) {
9514: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9515: $name=~s/\s+,/,/;
9516: } else {
9517: $name.= $firstname.' '.$middlename.' '.$generation;
9518: }
9519: }
9520: $name=~s/^\s+//;
9521: $name=~s/\s+$//;
9522: $name=~s/\s+/ /g;
9523: return $name;
9524: }
9525:
1.84 www 9526: # ------------------------------------------------- Write to course preferences
9527:
9528: sub writecoursepref {
9529: my ($courseid,%prefs)=@_;
9530: $courseid=~s/^\///;
9531: $courseid=~s/\_/\//g;
9532: my ($cdomain,$cnum)=split(/\//,$courseid);
9533: my $chome=homeserver($cnum,$cdomain);
9534: if (($chome eq '') || ($chome eq 'no_host')) {
9535: return 'error: no such course';
9536: }
9537: my $cstring='';
1.800 albertel 9538: foreach my $pref (keys(%prefs)) {
9539: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9540: }
1.84 www 9541: $cstring=~s/\&$//;
9542: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9543: }
9544:
9545: # ---------------------------------------------------------- Make/modify course
9546:
9547: sub createcourse {
1.741 raeburn 9548: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9549: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9550: $url=&declutter($url);
9551: my $cid='';
1.1028 raeburn 9552: if ($context eq 'requestcourses') {
9553: my $can_create = 0;
9554: my ($ownername,$ownerdom) = split(':',$course_owner);
9555: if ($udom eq $ownerdom) {
9556: if (&usertools_access($ownername,$ownerdom,$category,undef,
9557: $context)) {
9558: $can_create = 1;
9559: }
9560: } else {
9561: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9562: $category);
9563: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9564: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9565: if (@curr > 0) {
9566: my @options = qw(approval validate autolimit);
9567: my $optregex = join('|',@options);
9568: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9569: $can_create = 1;
9570: }
9571: }
9572: }
9573: }
9574: if ($can_create) {
9575: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9576: unless (&allowed('ccc',$udom)) {
9577: return 'refused';
9578: }
1.1017 raeburn 9579: }
9580: } else {
9581: return 'refused';
9582: }
1.1028 raeburn 9583: } elsif (!&allowed('ccc',$udom)) {
9584: return 'refused';
1.84 www 9585: }
1.1011 raeburn 9586: # --------------------------------------------------------------- Get Unique ID
9587: my $uname;
9588: if ($cnum =~ /^$match_courseid$/) {
9589: my $chome=&homeserver($cnum,$udom,'true');
9590: if (($chome eq '') || ($chome eq 'no_host')) {
9591: $uname = $cnum;
9592: } else {
1.1038 raeburn 9593: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9594: }
9595: } else {
1.1038 raeburn 9596: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9597: }
9598: return $uname if ($uname =~ /^error/);
9599: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9600: if (!defined($course_server)) {
9601: if (defined(&domain($udom,'primary'))) {
9602: $course_server = &domain($udom,'primary');
9603: } else {
9604: $course_server = $env{'user.home'};
9605: }
9606: }
9607: my %host_servers =
9608: &Apache::lonnet::get_servers($udom,'library');
9609: unless ($host_servers{$course_server}) {
9610: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9611: }
1.84 www 9612: # ------------------------------------------------------------- Make the course
9613: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9614: $course_server);
1.84 www 9615: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9616: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9617: if (($uhome eq '') || ($uhome eq 'no_host')) {
9618: return 'error: no such course';
9619: }
1.271 www 9620: # ----------------------------------------------------------------- Course made
1.516 raeburn 9621: # log existence
1.1029 raeburn 9622: my $now = time;
1.918 raeburn 9623: my $newcourse = {
9624: $udom.'_'.$uname => {
1.921 raeburn 9625: description => $description,
9626: inst_code => $inst_code,
9627: owner => $course_owner,
9628: type => $crstype,
1.1029 raeburn 9629: creator => $env{'user.name'}.':'.
9630: $env{'user.domain'},
9631: created => $now,
9632: context => $context,
1.918 raeburn 9633: },
9634: };
1.921 raeburn 9635: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9636: # set toplevel url
1.271 www 9637: my $topurl=$url;
9638: unless ($nonstandard) {
9639: # ------------------------------------------ For standard courses, make top url
9640: my $mapurl=&clutter($url);
1.278 www 9641: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9642: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9643: <map>
9644: <resource id="1" type="start"></resource>
9645: <resource id="2" src="$mapurl"></resource>
9646: <resource id="3" type="finish"></resource>
9647: <link index="1" from="1" to="2"></link>
9648: <link index="2" from="2" to="3"></link>
9649: </map>
9650: ENDINITMAP
9651: $topurl=&declutter(
1.638 albertel 9652: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9653: );
9654: }
9655: # ----------------------------------------------------------- Write preferences
1.84 www 9656: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9657: ('description' => $description,
9658: 'url' => $topurl,
9659: 'internal.creator' => $env{'user.name'}.':'.
9660: $env{'user.domain'},
9661: 'internal.created' => $now,
9662: 'internal.creationcontext' => $context)
9663: );
1.84 www 9664: return '/'.$udom.'/'.$uname;
9665: }
9666:
1.1011 raeburn 9667: # ------------------------------------------------------------------- Create ID
9668: sub generate_coursenum {
1.1038 raeburn 9669: my ($udom,$crstype) = @_;
1.1011 raeburn 9670: my $domdesc = &domain($udom);
9671: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9672: my $first;
9673: if ($crstype eq 'Community') {
9674: $first = '0';
9675: } else {
9676: $first = int(1+rand(9));
9677: }
9678: my $uname=$first.
1.1011 raeburn 9679: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9680: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9681: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9682: # ----------------------------------------------- Make sure that does not exist
9683: my $uhome=&homeserver($uname,$udom,'true');
9684: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9685: if ($crstype eq 'Community') {
9686: $first = '0';
9687: } else {
9688: $first = int(1+rand(9));
9689: }
9690: $uname=$first.
1.1011 raeburn 9691: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9692: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9693: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9694: $uhome=&homeserver($uname,$udom,'true');
9695: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9696: return 'error: unable to generate unique course-ID';
9697: }
9698: }
9699: return $uname;
9700: }
9701:
1.813 albertel 9702: sub is_course {
1.1167 droeschl 9703: my ($cdom, $cnum) = scalar(@_) == 1 ?
9704: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9705:
9706: return unless $cdom and $cnum;
9707:
9708: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9709: '.');
9710:
1.1172.2.23 raeburn 9711: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9712: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9713: }
9714:
1.1015 raeburn 9715: sub store_userdata {
9716: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9717: my $result;
1.1016 raeburn 9718: if ($datakey ne '') {
1.1013 raeburn 9719: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9720: if ($udom eq '' || $uname eq '') {
9721: $udom = $env{'user.domain'};
9722: $uname = $env{'user.name'};
9723: }
9724: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9725: if (($uhome eq '') || ($uhome eq 'no_host')) {
9726: $result = 'error: no_host';
9727: } else {
9728: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9729: $storehash->{'host'} = $perlvar{'lonHostID'};
9730:
9731: my $namevalue='';
9732: foreach my $key (keys(%{$storehash})) {
9733: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9734: }
9735: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9736: unless ($namespace eq 'courserequests') {
9737: $datakey = &escape($datakey);
9738: }
1.1105 raeburn 9739: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9740: $namevalue,$uhome);
1.1013 raeburn 9741: }
9742: } else {
9743: $result = 'error: data to store was not a hash reference';
9744: }
9745: } else {
9746: $result= 'error: invalid requestkey';
9747: }
9748: return $result;
9749: }
9750:
1.21 www 9751: # ---------------------------------------------------------- Assign Custom Role
9752:
9753: sub assigncustomrole {
1.957 raeburn 9754: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9755: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9756: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9757: }
9758:
9759: # ----------------------------------------------------------------- Revoke Role
9760:
9761: sub revokerole {
1.957 raeburn 9762: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9763: my $now=time;
1.965 raeburn 9764: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9765: }
9766:
9767: # ---------------------------------------------------------- Revoke Custom Role
9768:
9769: sub revokecustomrole {
1.957 raeburn 9770: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9771: my $now=time;
1.357 www 9772: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9773: $deleteflag,$selfenroll,$context);
1.17 www 9774: }
9775:
1.533 banghart 9776: # ------------------------------------------------------------ Disk usage
1.535 albertel 9777: sub diskusage {
1.955 raeburn 9778: my ($udom,$uname,$directorypath,$getpropath)=@_;
9779: $directorypath =~ s/\/$//;
9780: my $listing=&reply('du2:'.&escape($directorypath).':'
9781: .&escape($getpropath).':'.&escape($uname).':'
9782: .&escape($udom),homeserver($uname,$udom));
9783: if ($listing eq 'unknown_cmd') {
9784: if ($getpropath) {
9785: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9786: }
9787: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9788: }
1.514 albertel 9789: return $listing;
1.512 banghart 9790: }
9791:
1.566 banghart 9792: sub is_locked {
1.1096 raeburn 9793: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9794: my @check;
9795: my $is_locked;
1.1093 raeburn 9796: push (@check,$file_name);
1.613 albertel 9797: my %locked = &get('file_permissions',\@check,
1.620 albertel 9798: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9799: my ($tmp)=keys(%locked);
9800: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9801:
1.566 banghart 9802: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9803: $is_locked = 'false';
9804: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9805: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9806: $is_locked = 'true';
1.1096 raeburn 9807: if (ref($which) eq 'ARRAY') {
9808: push(@{$which},$entry);
9809: } else {
9810: last;
9811: }
1.745 raeburn 9812: }
9813: }
1.566 banghart 9814: } else {
9815: $is_locked = 'false';
9816: }
1.1093 raeburn 9817: return $is_locked;
1.566 banghart 9818: }
9819:
1.759 albertel 9820: sub declutter_portfile {
9821: my ($file) = @_;
1.833 albertel 9822: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9823: return $file;
9824: }
9825:
1.559 banghart 9826: # ------------------------------------------------------------- Mark as Read Only
9827:
9828: sub mark_as_readonly {
9829: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9830: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9831: my ($tmp)=keys(%current_permissions);
9832: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9833: foreach my $file (@{$files}) {
1.759 albertel 9834: $file = &declutter_portfile($file);
1.561 banghart 9835: push(@{$current_permissions{$file}},$what);
1.559 banghart 9836: }
1.613 albertel 9837: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9838: return;
9839: }
9840:
1.572 banghart 9841: # ------------------------------------------------------------Save Selected Files
9842:
9843: sub save_selected_files {
9844: my ($user, $path, @files) = @_;
9845: my $filename = $user."savedfiles";
1.573 banghart 9846: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9847: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9848: foreach my $file (@files) {
1.620 albertel 9849: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9850: }
9851: foreach my $file (@other_files) {
1.574 banghart 9852: print (OUT $file."\n");
1.572 banghart 9853: }
1.574 banghart 9854: close (OUT);
1.572 banghart 9855: return 'ok';
9856: }
9857:
1.574 banghart 9858: sub clear_selected_files {
9859: my ($user) = @_;
9860: my $filename = $user."savedfiles";
1.1117 foxr 9861: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9862: print (OUT undef);
9863: close (OUT);
9864: return ("ok");
9865: }
9866:
1.572 banghart 9867: sub files_in_path {
9868: my ($user, $path) = @_;
9869: my $filename = $user."savedfiles";
9870: my %return_files;
1.1117 foxr 9871: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9872: while (my $line_in = <IN>) {
1.574 banghart 9873: chomp ($line_in);
9874: my @paths_and_file = split (m!/!, $line_in);
9875: my $file_part = pop (@paths_and_file);
9876: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9877: $path_part.='/';
9878: my $path_and_file = $path_part.$file_part;
9879: if ($path_part eq $path) {
9880: $return_files{$file_part}= 'selected';
9881: }
9882: }
1.574 banghart 9883: close (IN);
9884: return (\%return_files);
1.572 banghart 9885: }
9886:
9887: # called in portfolio select mode, to show files selected NOT in current directory
9888: sub files_not_in_path {
9889: my ($user, $path) = @_;
9890: my $filename = $user."savedfiles";
9891: my @return_files;
9892: my $path_part;
1.1117 foxr 9893: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9894: while (my $line = <IN>) {
1.572 banghart 9895: #ok, I know it's clunky, but I want it to work
1.800 albertel 9896: my @paths_and_file = split(m|/|, $line);
9897: my $file_part = pop(@paths_and_file);
9898: chomp($file_part);
9899: my $path_part = join('/', @paths_and_file);
1.572 banghart 9900: $path_part .= '/';
9901: my $path_and_file = $path_part.$file_part;
9902: if ($path_part ne $path) {
1.800 albertel 9903: push(@return_files, ($path_and_file));
1.572 banghart 9904: }
9905: }
1.800 albertel 9906: close(OUT);
1.574 banghart 9907: return (@return_files);
1.572 banghart 9908: }
9909:
1.745 raeburn 9910: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9911:
1.745 raeburn 9912: sub get_portfile_permissions {
9913: my ($domain,$user) = @_;
1.613 albertel 9914: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9915: my ($tmp)=keys(%current_permissions);
9916: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9917: return \%current_permissions;
9918: }
9919:
9920: #---------------------------------------------Get portfolio file access controls
9921:
1.749 raeburn 9922: sub get_access_controls {
1.745 raeburn 9923: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9924: my %access;
9925: my $real_file = $file;
9926: $file =~ s/\.meta$//;
1.745 raeburn 9927: if (defined($file)) {
1.749 raeburn 9928: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9929: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9930: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9931: }
9932: }
1.745 raeburn 9933: } else {
1.749 raeburn 9934: foreach my $key (keys(%{$current_permissions})) {
9935: if ($key =~ /\0accesscontrol$/) {
9936: if (defined($group)) {
9937: if ($key !~ m-^\Q$group\E/-) {
9938: next;
9939: }
9940: }
9941: my ($fullpath) = split(/\0/,$key);
9942: if (ref($$current_permissions{$key}) eq 'HASH') {
9943: foreach my $control (keys(%{$$current_permissions{$key}})) {
9944: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9945: }
9946: }
9947: }
9948: }
9949: }
9950: return %access;
9951: }
9952:
9953: sub modify_access_controls {
9954: my ($file_name,$changes,$domain,$user)=@_;
9955: my ($outcome,$deloutcome);
9956: my %store_permissions;
9957: my %new_values;
9958: my %new_control;
9959: my %translation;
9960: my @deletions = ();
9961: my $now = time;
9962: if (exists($$changes{'activate'})) {
9963: if (ref($$changes{'activate'}) eq 'HASH') {
9964: my @newitems = sort(keys(%{$$changes{'activate'}}));
9965: my $numnew = scalar(@newitems);
9966: for (my $i=0; $i<$numnew; $i++) {
9967: my $newkey = $newitems[$i];
9968: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9969: if ($newkey =~ /^\d+:/) {
9970: $newkey =~ s/^(\d+)/$newid/;
9971: $translation{$1} = $newid;
9972: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9973: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9974: $translation{$1} = $newid;
9975: }
1.749 raeburn 9976: $new_values{$file_name."\0".$newkey} =
9977: $$changes{'activate'}{$newitems[$i]};
9978: $new_control{$newkey} = $now;
9979: }
9980: }
9981: }
9982: my %todelete;
9983: my %changed_items;
9984: foreach my $action ('delete','update') {
9985: if (exists($$changes{$action})) {
9986: if (ref($$changes{$action}) eq 'HASH') {
9987: foreach my $key (keys(%{$$changes{$action}})) {
9988: my ($itemnum) = ($key =~ /^([^:]+):/);
9989: if ($action eq 'delete') {
9990: $todelete{$itemnum} = 1;
9991: } else {
9992: $changed_items{$itemnum} = $key;
9993: }
9994: }
1.745 raeburn 9995: }
9996: }
1.749 raeburn 9997: }
9998: # get lock on access controls for file.
9999: my $lockhash = {
10000: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10001: ':'.$env{'user.domain'},
10002: };
10003: my $tries = 0;
10004: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10005:
1.1172.2.79 raeburn 10006: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10007: $tries ++;
1.1172.2.79 raeburn 10008: sleep(0.1);
1.749 raeburn 10009: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10010: }
10011: if ($gotlock eq 'ok') {
10012: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10013: my ($tmp)=keys(%curr_permissions);
10014: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10015: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10016: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10017: if (ref($curr_controls) eq 'HASH') {
10018: foreach my $control_item (keys(%{$curr_controls})) {
10019: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10020: if (defined($todelete{$itemnum})) {
10021: push(@deletions,$file_name."\0".$control_item);
10022: } else {
10023: if (defined($changed_items{$itemnum})) {
10024: $new_control{$changed_items{$itemnum}} = $now;
10025: push(@deletions,$file_name."\0".$control_item);
10026: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10027: } else {
10028: $new_control{$control_item} = $$curr_controls{$control_item};
10029: }
10030: }
1.745 raeburn 10031: }
10032: }
10033: }
1.970 raeburn 10034: my ($group);
10035: if (&is_course($domain,$user)) {
10036: ($group,my $file) = split(/\//,$file_name,2);
10037: }
1.749 raeburn 10038: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10039: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10040: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10041: # remove lock
10042: my @del_lock = ($file_name."\0".'locked_access_records');
10043: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10044: my $sqlresult =
1.970 raeburn 10045: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10046: $group);
1.749 raeburn 10047: } else {
10048: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10049: }
1.749 raeburn 10050: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10051: }
10052:
1.827 raeburn 10053: sub make_public_indefinitely {
10054: my ($requrl) = @_;
10055: my $now = time;
10056: my $action = 'activate';
10057: my $aclnum = 0;
10058: if (&is_portfolio_url($requrl)) {
10059: my (undef,$udom,$unum,$file_name,$group) =
10060: &parse_portfolio_url($requrl);
10061: my $current_perms = &get_portfile_permissions($udom,$unum);
10062: my %access_controls = &get_access_controls($current_perms,
10063: $group,$file_name);
10064: foreach my $key (keys(%{$access_controls{$file_name}})) {
10065: my ($num,$scope,$end,$start) =
10066: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10067: if ($scope eq 'public') {
10068: if ($start <= $now && $end == 0) {
10069: $action = 'none';
10070: } else {
10071: $action = 'update';
10072: $aclnum = $num;
10073: }
10074: last;
10075: }
10076: }
10077: if ($action eq 'none') {
10078: return 'ok';
10079: } else {
10080: my %changes;
10081: my $newend = 0;
10082: my $newstart = $now;
10083: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10084: $changes{$action}{$newkey} = {
10085: type => 'public',
10086: time => {
10087: start => $newstart,
10088: end => $newend,
10089: },
10090: };
10091: my ($outcome,$deloutcome,$new_values,$translation) =
10092: &modify_access_controls($file_name,\%changes,$udom,$unum);
10093: return $outcome;
10094: }
10095: } else {
10096: return 'invalid';
10097: }
10098: }
10099:
1.745 raeburn 10100: #------------------------------------------------------Get Marked as Read Only
10101:
10102: sub get_marked_as_readonly {
10103: my ($domain,$user,$what,$group) = @_;
10104: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10105: my @readonly_files;
1.629 banghart 10106: my $cmp1=$what;
10107: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10108: while (my ($file_name,$value) = each(%{$current_permissions})) {
10109: if (defined($group)) {
10110: if ($file_name !~ m-^\Q$group\E/-) {
10111: next;
10112: }
10113: }
1.561 banghart 10114: if (ref($value) eq "ARRAY"){
10115: foreach my $stored_what (@{$value}) {
1.629 banghart 10116: my $cmp2=$stored_what;
1.759 albertel 10117: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10118: $cmp2=join('',@{$stored_what});
1.745 raeburn 10119: }
1.629 banghart 10120: if ($cmp1 eq $cmp2) {
1.561 banghart 10121: push(@readonly_files, $file_name);
1.745 raeburn 10122: last;
1.563 banghart 10123: } elsif (!defined($what)) {
10124: push(@readonly_files, $file_name);
1.745 raeburn 10125: last;
1.561 banghart 10126: }
10127: }
1.745 raeburn 10128: }
1.561 banghart 10129: }
10130: return @readonly_files;
10131: }
1.577 banghart 10132: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10133:
1.577 banghart 10134: sub get_marked_as_readonly_hash {
1.745 raeburn 10135: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10136: my %readonly_files;
1.745 raeburn 10137: while (my ($file_name,$value) = each(%{$current_permissions})) {
10138: if (defined($group)) {
10139: if ($file_name !~ m-^\Q$group\E/-) {
10140: next;
10141: }
10142: }
1.577 banghart 10143: if (ref($value) eq "ARRAY"){
10144: foreach my $stored_what (@{$value}) {
1.745 raeburn 10145: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10146: foreach my $lock_descriptor(@{$stored_what}) {
10147: if ($lock_descriptor eq 'graded') {
10148: $readonly_files{$file_name} = 'graded';
10149: } elsif ($lock_descriptor eq 'handback') {
10150: $readonly_files{$file_name} = 'handback';
10151: } else {
10152: if (!exists($readonly_files{$file_name})) {
10153: $readonly_files{$file_name} = 'locked';
10154: }
10155: }
1.745 raeburn 10156: }
1.750 banghart 10157: }
1.577 banghart 10158: }
10159: }
10160: }
10161: return %readonly_files;
10162: }
1.559 banghart 10163: # ------------------------------------------------------------ Unmark as Read Only
10164:
10165: sub unmark_as_readonly {
1.629 banghart 10166: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10167: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10168: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10169: $file_name = &declutter_portfile($file_name);
1.634 albertel 10170: my $symb_crs = $what;
10171: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10172: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10173: my ($tmp)=keys(%current_permissions);
10174: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10175: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10176: foreach my $file (@readonly_files) {
1.759 albertel 10177: my $clean_file = &declutter_portfile($file);
10178: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10179: my $current_locks = $current_permissions{$file};
1.563 banghart 10180: my @new_locks;
10181: my @del_keys;
10182: if (ref($current_locks) eq "ARRAY"){
10183: foreach my $locker (@{$current_locks}) {
1.632 albertel 10184: my $compare=$locker;
1.749 raeburn 10185: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10186: $compare=join('',@{$locker});
1.746 raeburn 10187: if ($compare ne $symb_crs) {
10188: push(@new_locks, $locker);
10189: }
1.563 banghart 10190: }
10191: }
1.650 albertel 10192: if (scalar(@new_locks) > 0) {
1.563 banghart 10193: $current_permissions{$file} = \@new_locks;
10194: } else {
10195: push(@del_keys, $file);
1.613 albertel 10196: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10197: delete($current_permissions{$file});
1.563 banghart 10198: }
10199: }
1.561 banghart 10200: }
1.613 albertel 10201: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10202: return;
10203: }
1.512 banghart 10204:
1.17 www 10205: # ------------------------------------------------------------ Directory lister
10206:
10207: sub dirlist {
1.955 raeburn 10208: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10209: $uri=~s/^\///;
10210: $uri=~s/\/$//;
1.253 stredwic 10211: my ($udom, $uname);
1.955 raeburn 10212: if ($getuserdir) {
1.253 stredwic 10213: $udom = $userdomain;
10214: $uname = $username;
1.955 raeburn 10215: } else {
10216: (undef,$udom,$uname)=split(/\//,$uri);
10217: if(defined($userdomain)) {
10218: $udom = $userdomain;
10219: }
10220: if(defined($username)) {
10221: $uname = $username;
10222: }
1.253 stredwic 10223: }
1.955 raeburn 10224: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10225:
1.955 raeburn 10226: $dirRoot = $perlvar{'lonDocRoot'};
10227: if (defined($getpropath)) {
10228: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10229: $dirRoot =~ s/\/$//;
1.955 raeburn 10230: } elsif (defined($getuserdir)) {
10231: my $subdir=$uname.'__';
10232: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10233: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10234: ."/$udom/$subdir/$uname";
10235: } elsif (defined($alternateRoot)) {
10236: $dirRoot = $alternateRoot;
1.751 banghart 10237: }
1.253 stredwic 10238:
10239: if($udom) {
10240: if($uname) {
1.1135 raeburn 10241: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10242: if ($uhome eq 'no_host') {
10243: return ([],'no_host');
10244: }
1.955 raeburn 10245: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10246: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10247: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10248: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10249: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10250: } else {
10251: @listing_results = map { &unescape($_); } split(/:/,$listing);
10252: }
1.605 matthew 10253: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10254: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10255: @listing_results = split(/:/,$listing);
10256: } else {
10257: @listing_results = map { &unescape($_); } split(/:/,$listing);
10258: }
1.1135 raeburn 10259: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10260: ($listing eq 'rejected') || ($listing eq 'refused') ||
10261: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10262: return ([],$listing);
10263: } else {
10264: return (\@listing_results);
1.1135 raeburn 10265: }
1.955 raeburn 10266: } elsif(!$alternateRoot) {
1.1136 raeburn 10267: my (%allusers,%listerror);
1.841 albertel 10268: my %servers = &get_servers($udom,'library');
1.955 raeburn 10269: foreach my $tryserver (keys(%servers)) {
10270: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10271: &escape($udom),$tryserver);
10272: if ($listing eq 'unknown_cmd') {
10273: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10274: $udom, $tryserver);
10275: } else {
10276: @listing_results = map { &unescape($_); } split(/:/,$listing);
10277: }
1.841 albertel 10278: if ($listing eq 'unknown_cmd') {
10279: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10280: $udom, $tryserver);
10281: @listing_results = split(/:/,$listing);
10282: } else {
10283: @listing_results =
10284: map { &unescape($_); } split(/:/,$listing);
10285: }
1.1136 raeburn 10286: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10287: ($listing eq 'rejected') || ($listing eq 'refused') ||
10288: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10289: $listerror{$tryserver} = $listing;
10290: } else {
1.841 albertel 10291: foreach my $line (@listing_results) {
10292: my ($entry) = split(/&/,$line,2);
10293: $allusers{$entry} = 1;
10294: }
10295: }
1.253 stredwic 10296: }
1.1136 raeburn 10297: my @alluserslist=();
1.800 albertel 10298: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10299: push(@alluserslist,$user.'&user');
1.253 stredwic 10300: }
1.1172.2.80 raeburn 10301: if (!%listerror) {
10302: # no errors
10303: return (\@alluserslist);
10304: } elsif (scalar(keys(%servers)) == 1) {
10305: # one library server, one error
10306: my ($key) = keys(%listerror);
10307: return (\@alluserslist, $listerror{$key});
10308: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10309: # con_lost indicates that we might miss data from at least one
10310: # library server
10311: return (\@alluserslist, 'con_lost');
10312: } else {
10313: # multiple library servers and no con_lost -> data should be
10314: # complete.
10315: return (\@alluserslist);
10316: }
10317:
1.253 stredwic 10318: } else {
1.1136 raeburn 10319: return ([],'missing username');
1.253 stredwic 10320: }
1.955 raeburn 10321: } elsif(!defined($getpropath)) {
1.1136 raeburn 10322: my $path = $perlvar{'lonDocRoot'}.'/res/';
10323: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10324: return (\@all_domains);
1.955 raeburn 10325: } else {
1.1136 raeburn 10326: return ([],'missing domain');
1.275 stredwic 10327: }
10328: }
10329:
10330: # --------------------------------------------- GetFileTimestamp
10331: # This function utilizes dirlist and returns the date stamp for
10332: # when it was last modified. It will also return an error of -1
10333: # if an error occurs
10334:
10335: sub GetFileTimestamp {
1.955 raeburn 10336: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10337: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10338: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10339: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10340: undef,$getuserdir);
10341: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10342: return -1;
10343: }
10344: if (ref($fileref) eq 'ARRAY') {
10345: my @stats = split('&',$fileref->[0]);
1.375 matthew 10346: # @stats contains first the filename, then the stat output
10347: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10348: } else {
10349: return -1;
1.253 stredwic 10350: }
1.26 www 10351: }
10352:
1.712 albertel 10353: sub stat_file {
10354: my ($uri) = @_;
1.787 albertel 10355: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10356:
1.955 raeburn 10357: my ($udom,$uname,$file);
1.712 albertel 10358: if ($uri =~ m-^/(uploaded|editupload)/-) {
10359: ($udom,$uname,$file) =
1.811 albertel 10360: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10361: $file = 'userfiles/'.$file;
10362: }
10363: if ($uri =~ m-^/res/-) {
10364: ($udom,$uname) =
1.807 albertel 10365: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10366: $file = $uri;
10367: }
10368:
10369: if (!$udom || !$uname || !$file) {
10370: # unable to handle the uri
10371: return ();
10372: }
1.956 raeburn 10373: my $getpropath;
10374: if ($file =~ /^userfiles\//) {
10375: $getpropath = 1;
10376: }
1.1136 raeburn 10377: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10378: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10379: return ();
10380: } else {
10381: if (ref($listref) eq 'ARRAY') {
10382: my @stats = split('&',$listref->[0]);
10383: shift(@stats); #filename is first
10384: return @stats;
10385: }
1.712 albertel 10386: }
10387: return ();
10388: }
10389:
1.26 www 10390: # -------------------------------------------------------- Value of a Condition
10391:
1.713 albertel 10392: # gets the value of a specific preevaluated condition
10393: # stored in the string $env{user.state.<cid>}
10394: # or looks up a condition reference in the bighash and if if hasn't
10395: # already been evaluated recurses into docondval to get the value of
10396: # the condition, then memoizing it to
10397: # $env{user.state.<cid>.<condition>}
1.40 www 10398: sub directcondval {
10399: my $number=shift;
1.620 albertel 10400: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10401: &Apache::lonuserstate::evalstate();
10402: }
1.713 albertel 10403: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10404: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10405: } elsif ($number =~ /^_/) {
10406: my $sub_condition;
10407: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10408: &GDBM_READER(),0640)) {
10409: $sub_condition=$bighash{'conditions'.$number};
10410: untie(%bighash);
10411: }
10412: my $value = &docondval($sub_condition);
1.949 raeburn 10413: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10414: return $value;
10415: }
1.620 albertel 10416: if ($env{'user.state.'.$env{'request.course.id'}}) {
10417: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10418: } else {
10419: return 2;
10420: }
10421: }
10422:
1.713 albertel 10423: # get the collection of conditions for this resource
1.26 www 10424: sub condval {
10425: my $condidx=shift;
1.54 www 10426: my $allpathcond='';
1.713 albertel 10427: foreach my $cond (split(/\|/,$condidx)) {
10428: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10429: $allpathcond.=
10430: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10431: }
1.191 harris41 10432: }
1.54 www 10433: $allpathcond=~s/\|$//;
1.713 albertel 10434: return &docondval($allpathcond);
10435: }
10436:
10437: #evaluates an expression of conditions
10438: sub docondval {
10439: my ($allpathcond) = @_;
10440: my $result=0;
10441: if ($env{'request.course.id'}
10442: && defined($allpathcond)) {
10443: my $operand='|';
10444: my @stack;
10445: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10446: if ($chunk eq '(') {
10447: push @stack,($operand,$result);
10448: } elsif ($chunk eq ')') {
10449: my $before=pop @stack;
10450: if (pop @stack eq '&') {
10451: $result=$result>$before?$before:$result;
10452: } else {
10453: $result=$result>$before?$result:$before;
10454: }
10455: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10456: $operand=$chunk;
10457: } else {
10458: my $new=directcondval($chunk);
10459: if ($operand eq '&') {
10460: $result=$result>$new?$new:$result;
10461: } else {
10462: $result=$result>$new?$result:$new;
10463: }
10464: }
10465: }
1.26 www 10466: }
10467: return $result;
1.421 albertel 10468: }
10469:
10470: # ---------------------------------------------------- Devalidate courseresdata
10471:
10472: sub devalidatecourseresdata {
10473: my ($coursenum,$coursedomain)=@_;
10474: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10475: &devalidate_cache_new('courseres',$hashid);
1.28 www 10476: }
10477:
1.763 www 10478:
1.200 www 10479: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10480: #
10481: # Parameters:
10482: # $coursenum - Number of the course.
10483: # $coursedomain - Domain at which the course was created.
10484: # Returns:
10485: # A hash of the course parameters along (I think) with timestamps
10486: # and version info.
1.877 foxr 10487:
1.624 albertel 10488: sub get_courseresdata {
10489: my ($coursenum,$coursedomain)=@_;
1.200 www 10490: my $coursehom=&homeserver($coursenum,$coursedomain);
10491: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10492: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10493: my %dumpreply;
1.417 albertel 10494: unless (defined($cached)) {
1.624 albertel 10495: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10496: $result=\%dumpreply;
1.251 albertel 10497: my ($tmp) = keys(%dumpreply);
10498: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10499: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10500: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10501: return $tmp;
1.416 albertel 10502: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10503: $result=undef;
1.599 albertel 10504: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10505: }
10506: }
1.624 albertel 10507: return $result;
10508: }
10509:
1.633 albertel 10510: sub devalidateuserresdata {
10511: my ($uname,$udom)=@_;
10512: my $hashid="$udom:$uname";
10513: &devalidate_cache_new('userres',$hashid);
10514: }
10515:
1.624 albertel 10516: sub get_userresdata {
10517: my ($uname,$udom)=@_;
10518: #most student don\'t have any data set, check if there is some data
10519: if (&EXT_cache_status($udom,$uname)) { return undef; }
10520:
10521: my $hashid="$udom:$uname";
10522: my ($result,$cached)=&is_cached_new('userres',$hashid);
10523: if (!defined($cached)) {
10524: my %resourcedata=&dump('resourcedata',$udom,$uname);
10525: $result=\%resourcedata;
10526: &do_cache_new('userres',$hashid,$result,600);
10527: }
10528: my ($tmp)=keys(%$result);
10529: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10530: return $result;
10531: }
10532: #error 2 occurs when the .db doesn't exist
10533: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10534: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10535: &logthis("<font color=\"blue\">WARNING:".
10536: " Trying to get resource data for ".
10537: $uname." at ".$udom.": ".
10538: $tmp."</font>");
10539: }
1.624 albertel 10540: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10541: #&EXT_cache_set($udom,$uname);
10542: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10543: undef($tmp); # not really an error so don't send it back
1.624 albertel 10544: }
10545: return $tmp;
10546: }
1.879 foxr 10547: #----------------------------------------------- resdata - return resource data
10548: # Purpose:
10549: # Return resource data for either users or for a course.
10550: # Parameters:
10551: # $name - Course/user name.
10552: # $domain - Name of the domain the user/course is registered on.
1.1172.2.93.4 1(raebur 10553:7): # $type - Type of thing $name is (must be 'course' or 'user')
1.879 foxr 10554: # @which - Array of names of resources desired.
10555: # Returns:
10556: # The value of the first reasource in @which that is found in the
10557: # resource hash.
10558: # Exceptional Conditions:
10559: # If the $type passed in is not valid (not the string 'course' or
10560: # 'user', an undefined reference is returned.
10561: # If none of the resources are found, an undef is returned
1.624 albertel 10562: sub resdata {
10563: my ($name,$domain,$type,@which)=@_;
10564: my $result;
10565: if ($type eq 'course') {
10566: $result=&get_courseresdata($name,$domain);
10567: } elsif ($type eq 'user') {
10568: $result=&get_userresdata($name,$domain);
10569: }
10570: if (!ref($result)) { return $result; }
1.251 albertel 10571: foreach my $item (@which) {
1.1172.2.93.4 1(raebur 10572:7): if (ref($item) eq 'ARRAY') {
10573:7): if (defined($result->{$item->[0]})) {
10574:7): return [$result->{$item->[0]},$item->[1]];
10575:7): }
10576:7): }
1.250 albertel 10577: }
1.291 albertel 10578: return undef;
1.200 www 10579: }
10580:
1.1172.2.93.4 2(raebur 10581:7): sub get_domain_ltitools {
10582:7): my ($cdom) = @_;
10583:7): my %ltitools;
10584:7): my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10585:7): if (defined($cached)) {
10586:7): if (ref($result) eq 'HASH') {
10587:7): %ltitools = %{$result};
10588:7): }
10589:7): } else {
10590:7): my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10591:7): if (ref($domconfig{'ltitools'}) eq 'HASH') {
10592:7): %ltitools = %{$domconfig{'ltitools'}};
10593:7): my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
10594:7): if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
10595:7): foreach my $id (keys(%ltitools)) {
10596:7): if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
10597:7): foreach my $item ('key','secret') {
10598:7): $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
10599:7): }
10600:7): }
10601:7): }
10602:7): }
10603:7): }
10604:7): my $cachetime = 24*60*60;
10605:7): &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10606:7): }
10607:7): return %ltitools;
10608:7): }
10609:7):
1.1172.2.31 raeburn 10610: sub get_numsuppfiles {
10611: my ($cnum,$cdom,$ignorecache)=@_;
10612: my $hashid=$cnum.':'.$cdom;
10613: my ($suppcount,$cached);
10614: unless ($ignorecache) {
10615: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10616: }
10617: unless (defined($cached)) {
10618: my $chome=&homeserver($cnum,$cdom);
10619: unless ($chome eq 'no_host') {
10620: ($suppcount,my $errors) = (0,0);
10621: my $suppmap = 'supplemental.sequence';
10622: ($suppcount,$errors) =
10623: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10624: }
10625: &do_cache_new('suppcount',$hashid,$suppcount,600);
10626: }
10627: return $suppcount;
10628: }
10629:
1.379 matthew 10630: #
10631: # EXT resource caching routines
10632: #
10633:
10634: sub clear_EXT_cache_status {
1.383 albertel 10635: &delenv('cache.EXT.');
1.379 matthew 10636: }
10637:
10638: sub EXT_cache_status {
10639: my ($target_domain,$target_user) = @_;
1.383 albertel 10640: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10641: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10642: # We know already the user has no data
10643: return 1;
10644: } else {
10645: return 0;
10646: }
10647: }
10648:
10649: sub EXT_cache_set {
10650: my ($target_domain,$target_user) = @_;
1.383 albertel 10651: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10652: #&appenv({$cachename => time});
1.379 matthew 10653: }
10654:
1.28 www 10655: # --------------------------------------------------------- Value of a Variable
1.58 www 10656: sub EXT {
1.715 albertel 10657:
1.1172.2.28 raeburn 10658: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10659: unless ($varname) { return ''; }
1.218 albertel 10660: #get real user name/domain, courseid and symb
10661: my $courseid;
1.359 albertel 10662: my $publicuser;
1.427 www 10663: if ($symbparm) {
10664: $symbparm=&get_symb_from_alias($symbparm);
10665: }
1.218 albertel 10666: if (!($uname && $udom)) {
1.790 albertel 10667: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10668: if (!$symbparm) { $symbparm=$cursymb; }
10669: } else {
1.620 albertel 10670: $courseid=$env{'request.course.id'};
1.218 albertel 10671: }
1.48 www 10672: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10673: my $rest;
1.320 albertel 10674: if (defined($therest[0])) {
1.48 www 10675: $rest=join('.',@therest);
10676: } else {
10677: $rest='';
10678: }
1.320 albertel 10679:
1.57 www 10680: my $qualifierrest=$qualifier;
10681: if ($rest) { $qualifierrest.='.'.$rest; }
10682: my $spacequalifierrest=$space;
10683: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10684: if ($realm eq 'user') {
1.48 www 10685: # --------------------------------------------------------------- user.resource
10686: if ($space eq 'resource') {
1.651 albertel 10687: if ( (defined($Apache::lonhomework::parsing_a_problem)
10688: || defined($Apache::lonhomework::parsing_a_task))
10689: &&
1.744 albertel 10690: ($symbparm eq &symbread()) ) {
10691: # if we are in the middle of processing the resource the
10692: # get the value we are planning on committing
10693: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10694: return $Apache::lonhomework::results{$qualifierrest};
10695: } else {
10696: return $Apache::lonhomework::history{$qualifierrest};
10697: }
1.335 albertel 10698: } else {
1.359 albertel 10699: my %restored;
1.620 albertel 10700: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10701: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10702: } else {
10703: %restored=&restore($symbparm,$courseid,$udom,$uname);
10704: }
1.335 albertel 10705: return $restored{$qualifierrest};
10706: }
1.48 www 10707: # ----------------------------------------------------------------- user.access
10708: } elsif ($space eq 'access') {
1.218 albertel 10709: # FIXME - not supporting calls for a specific user
1.48 www 10710: return &allowed($qualifier,$rest);
10711: # ------------------------------------------ user.preferences, user.environment
10712: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10713: if (($uname eq $env{'user.name'}) &&
10714: ($udom eq $env{'user.domain'})) {
10715: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10716: } else {
1.359 albertel 10717: my %returnhash;
10718: if (!$publicuser) {
10719: %returnhash=&userenvironment($udom,$uname,
10720: $qualifierrest);
10721: }
1.218 albertel 10722: return $returnhash{$qualifierrest};
10723: }
1.48 www 10724: # ----------------------------------------------------------------- user.course
10725: } elsif ($space eq 'course') {
1.218 albertel 10726: # FIXME - not supporting calls for a specific user
1.620 albertel 10727: return $env{join('.',('request.course',$qualifier))};
1.48 www 10728: # ------------------------------------------------------------------- user.role
10729: } elsif ($space eq 'role') {
1.218 albertel 10730: # FIXME - not supporting calls for a specific user
1.620 albertel 10731: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10732: if ($qualifier eq 'value') {
10733: return $role;
10734: } elsif ($qualifier eq 'extent') {
10735: return $where;
10736: }
10737: # ----------------------------------------------------------------- user.domain
10738: } elsif ($space eq 'domain') {
1.218 albertel 10739: return $udom;
1.48 www 10740: # ------------------------------------------------------------------- user.name
10741: } elsif ($space eq 'name') {
1.218 albertel 10742: return $uname;
1.48 www 10743: # ---------------------------------------------------- Any other user namespace
1.29 www 10744: } else {
1.359 albertel 10745: my %reply;
10746: if (!$publicuser) {
10747: %reply=&get($space,[$qualifierrest],$udom,$uname);
10748: }
10749: return $reply{$qualifierrest};
1.48 www 10750: }
1.236 www 10751: } elsif ($realm eq 'query') {
10752: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10753: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10754: [$spacequalifierrest]);
1.620 albertel 10755: return $env{'form.'.$spacequalifierrest};
1.236 www 10756: } elsif ($realm eq 'request') {
1.48 www 10757: # ------------------------------------------------------------- request.browser
10758: if ($space eq 'browser') {
1.1145 bisitz 10759: return $env{'browser.'.$qualifier};
1.57 www 10760: # ------------------------------------------------------------ request.filename
10761: } else {
1.620 albertel 10762: return $env{'request.'.$spacequalifierrest};
1.29 www 10763: }
1.28 www 10764: } elsif ($realm eq 'course') {
1.48 www 10765: # ---------------------------------------------------------- course.description
1.620 albertel 10766: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10767: } elsif ($realm eq 'resource') {
1.165 www 10768:
1.620 albertel 10769: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10770: if (!$symbparm) { $symbparm=&symbread(); }
10771: }
1.693 albertel 10772:
1.1172.2.30 raeburn 10773: if ($qualifier eq '') {
10774: if ($space eq 'title') {
10775: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10776: return &gettitle($symbparm);
10777: }
1.693 albertel 10778:
1.1172.2.30 raeburn 10779: if ($space eq 'map') {
10780: my ($map) = &decode_symb($symbparm);
10781: return &symbread($map);
10782: }
10783: if ($space eq 'maptitle') {
10784: my ($map) = &decode_symb($symbparm);
10785: return &gettitle($map);
10786: }
10787: if ($space eq 'filename') {
10788: if ($symbparm) {
10789: return &clutter((&decode_symb($symbparm))[2]);
10790: }
10791: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10792: }
1.1172.2.30 raeburn 10793:
10794: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10795: if ($space eq 'visibleparts') {
10796: my $navmap = Apache::lonnavmaps::navmap->new();
10797: my $item;
10798: if (ref($navmap)) {
10799: my $res = $navmap->getBySymb($symbparm);
10800: my $parts = $res->parts();
10801: if (ref($parts) eq 'ARRAY') {
10802: $item = join(',',@{$parts});
10803: }
10804: undef($navmap);
10805: }
10806: return $item;
10807: }
10808: }
10809: }
1.693 albertel 10810:
10811: my ($section, $group, @groups);
1.593 albertel 10812: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10813: if (($courseid eq '') && ($cid)) {
10814: $courseid = $cid;
10815: }
10816: if (($symbparm && $courseid) &&
10817: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10818:
1.218 albertel 10819: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10820:
1.60 www 10821: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10822: my $symbp=$symbparm;
1.735 albertel 10823: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10824:
10825: my $symbparm=$symbp.'.'.$spacequalifierrest;
10826: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10827:
1.620 albertel 10828: if (($env{'user.name'} eq $uname) &&
10829: ($env{'user.domain'} eq $udom)) {
10830: $section=$env{'request.course.sec'};
1.733 raeburn 10831: @groups = split(/:/,$env{'request.course.groups'});
10832: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10833: } else {
1.539 albertel 10834: if (! defined($usection)) {
1.551 albertel 10835: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10836: } else {
10837: $section = $usection;
10838: }
1.733 raeburn 10839: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10840: }
10841:
10842: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10843: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10844: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10845:
1.593 albertel 10846: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10847: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10848: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10849:
1.60 www 10850: # ----------------------------------------------------------- first, check user
1.624 albertel 10851:
10852: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10853: ([$courselevelr,'resource'],
10854: [$courselevelm,'map' ],
10855: [$courselevel, 'course' ]));
1.931 albertel 10856: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10857:
1.594 albertel 10858: # ------------------------------------------------ second, check some of course
1.684 raeburn 10859: my $coursereply;
1.691 raeburn 10860: if (@groups > 0) {
10861: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10862: $mapparm,$spacequalifierrest);
1.927 albertel 10863: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10864: }
1.96 www 10865:
1.684 raeburn 10866: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10867: $env{'course.'.$courseid.'.domain'},
10868: 'course',
10869: ([$seclevelr, 'resource'],
10870: [$seclevelm, 'map' ],
10871: [$seclevel, 'course' ],
10872: [$courselevelr,'resource']));
10873: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10874:
1.60 www 10875: # ------------------------------------------------------ third, check map parms
1.218 albertel 10876: my %parmhash=();
10877: my $thisparm='';
10878: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10879: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10880: &GDBM_READER(),0640)) {
1.218 albertel 10881: $thisparm=$parmhash{$symbparm};
10882: untie(%parmhash);
10883: }
1.927 albertel 10884: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10885: }
1.594 albertel 10886: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10887:
1.218 albertel 10888: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10889: my $filename;
10890: if (!$symbparm) { $symbparm=&symbread(); }
10891: if ($symbparm) {
1.409 www 10892: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10893: } else {
1.620 albertel 10894: $filename=$env{'request.filename'};
1.282 albertel 10895: }
10896: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10897: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10898: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10899: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10900:
1.927 albertel 10901: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10902: if ($symbparm && defined($courseid) &&
1.620 albertel 10903: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10904: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10905: $env{'course.'.$courseid.'.domain'},
10906: 'course',
1.927 albertel 10907: ([$courselevelm,'map' ],
10908: [$courselevel, 'course']));
10909: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10910: }
1.145 www 10911: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10912: unless ($space eq '0') {
1.336 albertel 10913: my @parts=split(/_/,$space);
10914: my $id=pop(@parts);
10915: my $part=join('_',@parts);
10916: if ($part eq '') { $part='0'; }
1.927 albertel 10917: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10918: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10919: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10920: }
1.395 albertel 10921: if ($recurse) { return undef; }
10922: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10923: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10924: # ---------------------------------------------------- Any other user namespace
10925: } elsif ($realm eq 'environment') {
10926: # ----------------------------------------------------------------- environment
1.620 albertel 10927: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10928: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10929: } else {
1.770 albertel 10930: if ($uname eq 'anonymous' && $udom eq '') {
10931: return '';
10932: }
1.219 albertel 10933: my %returnhash=&userenvironment($udom,$uname,
10934: $spacequalifierrest);
10935: return $returnhash{$spacequalifierrest};
10936: }
1.28 www 10937: } elsif ($realm eq 'system') {
1.48 www 10938: # ----------------------------------------------------------------- system.time
10939: if ($space eq 'time') {
10940: return time;
10941: }
1.696 albertel 10942: } elsif ($realm eq 'server') {
10943: # ----------------------------------------------------------------- system.time
10944: if ($space eq 'name') {
10945: return $ENV{'SERVER_NAME'};
10946: }
1.28 www 10947: }
1.48 www 10948: return '';
1.61 www 10949: }
10950:
1.927 albertel 10951: sub get_reply {
10952: my ($reply_value) = @_;
1.940 raeburn 10953: if (ref($reply_value) eq 'ARRAY') {
10954: if (wantarray) {
10955: return @$reply_value;
10956: }
10957: return $reply_value->[0];
10958: } else {
10959: return $reply_value;
1.927 albertel 10960: }
10961: }
10962:
1.691 raeburn 10963: sub check_group_parms {
10964: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10965: my @groupitems = ();
10966: my $resultitem;
1.927 albertel 10967: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10968: foreach my $group (@{$groups}) {
10969: foreach my $level (@levels) {
1.927 albertel 10970: my $item = $courseid.'.['.$group.'].'.$level->[0];
10971: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10972: }
10973: }
10974: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10975: $env{'course.'.$courseid.'.domain'},
10976: 'course',@groupitems);
10977: return $coursereply;
10978: }
10979:
10980: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10981: my ($courseid,@groups) = @_;
10982: @groups = sort(@groups);
1.691 raeburn 10983: return @groups;
10984: }
10985:
1.395 albertel 10986: sub packages_tab_default {
10987: my ($uri,$varname)=@_;
10988: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10989:
10990: my (@extension,@specifics,$do_default);
10991: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10992: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10993: if ($pack_type eq 'default') {
10994: $do_default=1;
10995: } elsif ($pack_type eq 'extension') {
10996: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10997: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10998: # only look at packages defaults for packages that this id is
1.738 albertel 10999: push(@specifics,[$package,$pack_type,$pack_part]);
11000: }
11001: }
11002: # first look for a package that matches the requested part id
11003: foreach my $package (@specifics) {
11004: my (undef,$pack_type,$pack_part)=@{$package};
11005: next if ($pack_part ne $part);
11006: if (defined($packagetab{"$pack_type&$name&default"})) {
11007: return $packagetab{"$pack_type&$name&default"};
11008: }
11009: }
11010: # look for any possible matching non extension_ package
11011: foreach my $package (@specifics) {
11012: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11013: if (defined($packagetab{"$pack_type&$name&default"})) {
11014: return $packagetab{"$pack_type&$name&default"};
11015: }
1.585 albertel 11016: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11017: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11018: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11019: }
11020: }
1.738 albertel 11021: # look for any posible extension_ match
11022: foreach my $package (@extension) {
11023: my ($package,$pack_type)=@{$package};
11024: if (defined($packagetab{"$pack_type&$name&default"})) {
11025: return $packagetab{"$pack_type&$name&default"};
11026: }
11027: if (defined($packagetab{$package."&$name&default"})) {
11028: return $packagetab{$package."&$name&default"};
11029: }
11030: }
11031: # look for a global default setting
11032: if ($do_default && defined($packagetab{"default&$name&default"})) {
11033: return $packagetab{"default&$name&default"};
11034: }
1.395 albertel 11035: return undef;
11036: }
11037:
1.334 albertel 11038: sub add_prefix_and_part {
11039: my ($prefix,$part)=@_;
11040: my $keyroot;
11041: if (defined($prefix) && $prefix !~ /^__/) {
11042: # prefix that has a part already
11043: $keyroot=$prefix;
11044: } elsif (defined($prefix)) {
11045: # prefix that is missing a part
11046: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11047: } else {
11048: # no prefix at all
11049: if (defined($part)) { $keyroot='_'.$part; }
11050: }
11051: return $keyroot;
11052: }
11053:
1.71 www 11054: # ---------------------------------------------------------------- Get metadata
11055:
1.599 albertel 11056: my %metaentry;
1.1070 www 11057: my %importedpartids;
1.71 www 11058: sub metadata {
1.176 www 11059: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11060: $uri=&declutter($uri);
1.288 albertel 11061: # if it is a non metadata possible uri return quickly
1.529 albertel 11062: if (($uri eq '') ||
11063: (($uri =~ m|^/*adm/|) &&
1.1172.2.93.4 2(raebur 11064:7): ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11065: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11066: return undef;
11067: }
1.1172.2.49 raeburn 11068: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11069: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11070: return undef;
1.288 albertel 11071: }
1.73 www 11072: my $filename=$uri;
11073: $uri=~s/\.meta$//;
1.172 www 11074: #
11075: # Is the metadata already cached?
1.177 www 11076: # Look at timestamp of caching
1.172 www 11077: # Everything is cached by the main uri, libraries are never directly cached
11078: #
1.428 albertel 11079: if (!defined($liburi)) {
1.599 albertel 11080: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11081: if (defined($cached)) { return $result->{':'.$what}; }
11082: }
11083: {
1.1069 www 11084: # Imported parts would go here
1.1070 www 11085: my %importedids=();
11086: my @origfileimportpartids=();
1.1069 www 11087: my $importedparts=0;
1.172 www 11088: #
11089: # Is this a recursive call for a library?
11090: #
1.599 albertel 11091: # if (! exists($metacache{$uri})) {
11092: # $metacache{$uri}={};
11093: # }
1.924 albertel 11094: my $cachetime = 60*60;
1.171 www 11095: if ($liburi) {
11096: $liburi=&declutter($liburi);
11097: $filename=$liburi;
1.401 bowersj2 11098: } else {
1.599 albertel 11099: &devalidate_cache_new('meta',$uri);
11100: undef(%metaentry);
1.401 bowersj2 11101: }
1.140 www 11102: my %metathesekeys=();
1.73 www 11103: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11104: my $metastring;
1.1140 www 11105: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11106: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11107: $metastring =
1.929 albertel 11108: &Apache::lonnet::ssi_body($which,
1.924 albertel 11109: ('grade_target' => 'meta'));
11110: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11111: } elsif (($uri !~ m -^(editupload)/-) &&
11112: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11113: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11114: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11115: $metastring=&getfile($file);
1.489 albertel 11116: }
1.208 albertel 11117: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11118: my $token;
1.140 www 11119: undef %metathesekeys;
1.71 www 11120: while ($token=$parser->get_token) {
1.339 albertel 11121: if ($token->[0] eq 'S') {
11122: if (defined($token->[2]->{'package'})) {
1.172 www 11123: #
11124: # This is a package - get package info
11125: #
1.339 albertel 11126: my $package=$token->[2]->{'package'};
11127: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11128: if (defined($token->[2]->{'id'})) {
11129: $keyroot.='_'.$token->[2]->{'id'};
11130: }
1.599 albertel 11131: if ($metaentry{':packages'}) {
11132: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11133: } else {
1.599 albertel 11134: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11135: }
1.736 albertel 11136: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11137: my $part=$keyroot;
11138: $part=~s/^\_//;
1.736 albertel 11139: if ($pack_entry=~/^\Q$package\E\&/ ||
11140: $pack_entry=~/^\Q$package\E_0\&/) {
11141: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11142: # ignore package.tab specified default values
11143: # here &package_tab_default() will fetch those
11144: if ($subp eq 'default') { next; }
1.736 albertel 11145: my $value=$packagetab{$pack_entry};
1.432 albertel 11146: my $unikey;
11147: if ($pack =~ /_0$/) {
11148: $unikey='parameter_0_'.$name;
11149: $part=0;
11150: } else {
11151: $unikey='parameter'.$keyroot.'_'.$name;
11152: }
1.339 albertel 11153: if ($subp eq 'display') {
11154: $value.=' [Part: '.$part.']';
11155: }
1.599 albertel 11156: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11157: $metathesekeys{$unikey}=1;
1.599 albertel 11158: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11159: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11160: }
1.599 albertel 11161: if (defined($metaentry{':'.$unikey.'.default'})) {
11162: $metaentry{':'.$unikey}=
11163: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11164: }
1.339 albertel 11165: }
11166: }
11167: } else {
1.172 www 11168: #
11169: # This is not a package - some other kind of start tag
1.339 albertel 11170: #
11171: my $entry=$token->[1];
1.1068 www 11172: my $unikey='';
1.175 www 11173:
1.339 albertel 11174: if ($entry eq 'import') {
1.175 www 11175: #
11176: # Importing a library here
1.339 albertel 11177: #
1.1067 www 11178: my $location=$parser->get_text('/import');
11179: my $dir=$filename;
11180: $dir=~s|[^/]*$||;
11181: $location=&filelocation($dir,$location);
1.1069 www 11182:
1.1068 www 11183: my $importmode=$token->[2]->{'importmode'};
11184: if ($importmode eq 'problem') {
1.1069 www 11185: # Import as problem/response
1.1068 www 11186: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11187: } elsif ($importmode eq 'part') {
11188: # Import as part(s)
1.1069 www 11189: $importedparts=1;
11190: # We need to get the original file and the imported file to get the part order correct
11191: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11192: # Load and inspect original file
1.1070 www 11193: if ($#origfileimportpartids<0) {
11194: undef(%importedpartids);
11195: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11196: my $origfile=&getfile($origfilelocation);
11197: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11198: }
11199:
1.1069 www 11200: # Load and inspect imported file
11201: my $impfile=&getfile($location);
11202: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11203: if ($#impfilepartids>=0) {
11204: # This problem had parts
1.1070 www 11205: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11206: } else {
11207: # Importing by turning a single problem into a problem part
11208: # It gets the import-tags ID as part-ID
11209: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11210: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11211: }
1.1068 www 11212: } else {
11213: # Normal import
11214: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11215: if (defined($token->[2]->{'id'})) {
11216: $unikey.='_'.$token->[2]->{'id'};
11217: }
1.1067 www 11218: }
11219:
1.339 albertel 11220: if ($depthcount<20) {
1.736 albertel 11221: my $metadata =
11222: &metadata($uri,'keys', $location,$unikey,
11223: $depthcount+1);
11224: foreach my $meta (split(',',$metadata)) {
11225: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11226: $metathesekeys{$meta}=1;
1.339 albertel 11227: }
1.1068 www 11228:
11229: }
1.1067 www 11230: } else {
11231: #
11232: # Not importing, some other kind of non-package, non-library start tag
11233: #
11234: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11235: if (defined($token->[2]->{'id'})) {
11236: $unikey.='_'.$token->[2]->{'id'};
11237: }
1.339 albertel 11238: if (defined($token->[2]->{'name'})) {
11239: $unikey.='_'.$token->[2]->{'name'};
11240: }
11241: $metathesekeys{$unikey}=1;
1.736 albertel 11242: foreach my $param (@{$token->[3]}) {
11243: $metaentry{':'.$unikey.'.'.$param} =
11244: $token->[2]->{$param};
1.339 albertel 11245: }
11246: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11247: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11248: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11249: # only ws inside the tag, and not in default, so use default
11250: # as value
1.599 albertel 11251: $metaentry{':'.$unikey}=$default;
1.908 albertel 11252: } elsif ( $internaltext =~ /\S/ ) {
11253: # something interesting inside the tag
11254: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11255: } else {
1.908 albertel 11256: # no interesting values, don't set a default
1.339 albertel 11257: }
1.172 www 11258: # end of not-a-package not-a-library import
1.339 albertel 11259: }
1.172 www 11260: # end of not-a-package start tag
1.339 albertel 11261: }
1.172 www 11262: # the next is the end of "start tag"
1.339 albertel 11263: }
11264: }
1.483 albertel 11265: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11266: $extension = lc($extension);
11267: if ($extension eq 'htm') { $extension='html'; }
11268:
1.737 albertel 11269: foreach my $key (keys(%packagetab)) {
1.483 albertel 11270: #no specific packages #how's our extension
11271: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11272: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11273: \%metathesekeys);
11274: }
1.883 albertel 11275:
11276: if (!exists($metaentry{':packages'})
11277: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11278: foreach my $key (keys(%packagetab)) {
1.483 albertel 11279: #no specific packages well let's get default then
11280: if ($key!~/^default&/) { next; }
1.488 albertel 11281: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11282: \%metathesekeys);
11283: }
11284: }
1.338 www 11285: # are there custom rights to evaluate
1.599 albertel 11286: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11287:
1.338 www 11288: #
11289: # Importing a rights file here
1.339 albertel 11290: #
11291: unless ($depthcount) {
1.599 albertel 11292: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11293: my $dir=$filename;
11294: $dir=~s|[^/]*$||;
11295: $location=&filelocation($dir,$location);
1.736 albertel 11296: my $rights_metadata =
11297: &metadata($uri,'keys',$location,'_rights',
11298: $depthcount+1);
11299: foreach my $rights (split(',',$rights_metadata)) {
11300: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11301: $metathesekeys{$rights}=1;
1.339 albertel 11302: }
11303: }
11304: }
1.737 albertel 11305: # uniqifiy package listing
11306: my %seen;
11307: my @uniq_packages =
11308: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11309: $metaentry{':packages'} = join(',',@uniq_packages);
11310:
1.1070 www 11311: if ($importedparts) {
11312: # We had imported parts and need to rebuild partorder
11313: $metaentry{':partorder'}='';
11314: $metathesekeys{'partorder'}=1;
11315: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11316: if ($origfileimportpartids[$index] eq 'part') {
11317: # original part, part of the problem
11318: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11319: } else {
11320: # we have imported parts at this position
11321: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11322: }
11323: }
11324: $metaentry{':partorder'}=~s/^\,//;
11325: }
11326:
1.737 albertel 11327: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11328: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11329: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11330: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11331: # this is the end of "was not already recently cached
1.71 www 11332: }
1.599 albertel 11333: return $metaentry{':'.$what};
1.261 albertel 11334: }
11335:
1.488 albertel 11336: sub metadata_create_package_def {
1.483 albertel 11337: my ($uri,$key,$package,$metathesekeys)=@_;
11338: my ($pack,$name,$subp)=split(/\&/,$key);
11339: if ($subp eq 'default') { next; }
11340:
1.599 albertel 11341: if (defined($metaentry{':packages'})) {
11342: $metaentry{':packages'}.=','.$package;
1.483 albertel 11343: } else {
1.599 albertel 11344: $metaentry{':packages'}=$package;
1.483 albertel 11345: }
11346: my $value=$packagetab{$key};
11347: my $unikey;
11348: $unikey='parameter_0_'.$name;
1.599 albertel 11349: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11350: $$metathesekeys{$unikey}=1;
1.599 albertel 11351: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11352: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11353: }
1.599 albertel 11354: if (defined($metaentry{':'.$unikey.'.default'})) {
11355: $metaentry{':'.$unikey}=
11356: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11357: }
11358: }
11359:
1.261 albertel 11360: sub metadata_generate_part0 {
11361: my ($metadata,$metacache,$uri) = @_;
11362: my %allnames;
1.737 albertel 11363: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11364: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11365: my $part=$$metacache{':'.$metakey.'.part'};
11366: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11367: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11368: $allnames{$name}=$part;
11369: }
11370: }
11371: }
11372: foreach my $name (keys(%allnames)) {
11373: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11374: my $key=":parameter_0_$name";
1.261 albertel 11375: $$metacache{"$key.part"}='0';
11376: $$metacache{"$key.name"}=$name;
1.428 albertel 11377: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11378: $allnames{$name}.'_'.$name.
11379: '.type'};
1.428 albertel 11380: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11381: '.display'};
1.644 www 11382: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11383: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11384: $$metacache{"$key.display"}=$olddis;
11385: }
1.71 www 11386: }
11387:
1.764 albertel 11388: # ------------------------------------------------------ Devalidate title cache
11389:
11390: sub devalidate_title_cache {
11391: my ($url)=@_;
11392: if (!$env{'request.course.id'}) { return; }
11393: my $symb=&symbread($url);
11394: if (!$symb) { return; }
11395: my $key=$env{'request.course.id'}."\0".$symb;
11396: &devalidate_cache_new('title',$key);
11397: }
11398:
1.1014 droeschl 11399: # ------------------------------------------------- Get the title of a course
11400:
11401: sub current_course_title {
11402: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11403: }
1.301 www 11404: # ------------------------------------------------- Get the title of a resource
11405:
11406: sub gettitle {
11407: my $urlsymb=shift;
11408: my $symb=&symbread($urlsymb);
1.534 albertel 11409: if ($symb) {
1.620 albertel 11410: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11411: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11412: if (defined($cached)) {
11413: return $result;
11414: }
1.534 albertel 11415: my ($map,$resid,$url)=&decode_symb($symb);
11416: my $title='';
1.907 albertel 11417: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11418: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11419: } else {
11420: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11421: &GDBM_READER(),0640)) {
11422: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11423: $title=$bighash{'title_'.$mapid.'.'.$resid};
11424: untie(%bighash);
11425: }
1.534 albertel 11426: }
11427: $title=~s/\&colon\;/\:/gs;
11428: if ($title) {
1.1159 www 11429: # Remember both $symb and $title for dynamic metadata
11430: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11431: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11432: # Cache this title and then return it
1.599 albertel 11433: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11434: }
11435: $urlsymb=$url;
11436: }
11437: my $title=&metadata($urlsymb,'title');
11438: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11439: return $title;
1.301 www 11440: }
1.613 albertel 11441:
1.614 albertel 11442: sub get_slot {
11443: my ($which,$cnum,$cdom)=@_;
11444: if (!$cnum || !$cdom) {
1.790 albertel 11445: (undef,my $courseid)=&whichuser();
1.620 albertel 11446: $cdom=$env{'course.'.$courseid.'.domain'};
11447: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11448: }
1.703 albertel 11449: my $key=join("\0",'slots',$cdom,$cnum,$which);
11450: my %slotinfo;
11451: if (exists($remembered{$key})) {
11452: $slotinfo{$which} = $remembered{$key};
11453: } else {
11454: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11455: &Apache::lonhomework::showhash(%slotinfo);
11456: my ($tmp)=keys(%slotinfo);
11457: if ($tmp=~/^error:/) { return (); }
11458: $remembered{$key} = $slotinfo{$which};
11459: }
1.616 albertel 11460: if (ref($slotinfo{$which}) eq 'HASH') {
11461: return %{$slotinfo{$which}};
11462: }
11463: return $slotinfo{$which};
1.614 albertel 11464: }
1.1150 raeburn 11465:
11466: sub get_reservable_slots {
11467: my ($cnum,$cdom,$uname,$udom) = @_;
11468: my $now = time;
11469: my $reservable_info;
11470: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11471: if (exists($remembered{$key})) {
11472: $reservable_info = $remembered{$key};
11473: } else {
11474: my %resv;
11475: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11476: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11477: $reservable_info = \%resv;
11478: $remembered{$key} = $reservable_info;
11479: }
11480: return $reservable_info;
11481: }
11482:
11483: sub get_course_slots {
11484: my ($cnum,$cdom) = @_;
11485: my $hashid=$cnum.':'.$cdom;
11486: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11487: if (defined($cached)) {
11488: if (ref($result) eq 'HASH') {
11489: return %{$result};
11490: }
11491: } else {
11492: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11493: my ($tmp) = keys(%slots);
11494: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11495: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11496: return %slots;
11497: }
11498: }
11499: return;
11500: }
11501:
11502: sub devalidate_slots_cache {
11503: my ($cnum,$cdom)=@_;
11504: my $hashid=$cnum.':'.$cdom;
11505: &devalidate_cache_new('allslots',$hashid);
11506: }
11507:
1.1172.2.8 raeburn 11508: sub get_coursechange {
11509: my ($cdom,$cnum) = @_;
11510: if ($cdom eq '' || $cnum eq '') {
11511: return unless ($env{'request.course.id'});
11512: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11513: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11514: }
11515: my $hashid=$cdom.'_'.$cnum;
11516: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11517: if ((defined($cached)) && ($change ne '')) {
11518: return $change;
11519: } else {
11520: my %crshash;
11521: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11522: if ($crshash{'internal.contentchange'} eq '') {
11523: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11524: if ($change eq '') {
11525: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11526: $change = $crshash{'internal.created'};
11527: }
11528: } else {
11529: $change = $crshash{'internal.contentchange'};
11530: }
11531: my $cachetime = 600;
11532: &do_cache_new('crschange',$hashid,$change,$cachetime);
11533: }
11534: return $change;
11535: }
11536:
11537: sub devalidate_coursechange_cache {
11538: my ($cnum,$cdom)=@_;
11539: my $hashid=$cnum.':'.$cdom;
11540: &devalidate_cache_new('crschange',$hashid);
11541: }
11542:
1.31 www 11543: # ------------------------------------------------- Update symbolic store links
11544:
11545: sub symblist {
11546: my ($mapname,%newhash)=@_;
1.438 www 11547: $mapname=&deversion(&declutter($mapname));
1.31 www 11548: my %hash;
1.620 albertel 11549: if (($env{'request.course.fn'}) && (%newhash)) {
11550: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11551: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11552: foreach my $url (keys(%newhash)) {
1.711 albertel 11553: next if ($url eq 'last_known'
11554: && $env{'form.no_update_last_known'});
11555: $hash{declutter($url)}=&encode_symb($mapname,
11556: $newhash{$url}->[1],
11557: $newhash{$url}->[0]);
1.191 harris41 11558: }
1.31 www 11559: if (untie(%hash)) {
11560: return 'ok';
11561: }
11562: }
11563: }
11564: return 'error';
1.212 www 11565: }
11566:
11567: # --------------------------------------------------------------- Verify a symb
11568:
11569: sub symbverify {
1.1172.2.11 raeburn 11570: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11571: my $thisfn=$thisurl;
1.439 www 11572: $thisfn=&declutter($thisfn);
1.215 www 11573: # direct jump to resource in page or to a sequence - will construct own symbs
11574: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11575: # check URL part
1.409 www 11576: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11577:
1.431 www 11578: unless ($url eq $thisfn) { return 0; }
1.213 www 11579:
1.216 www 11580: $symb=&symbclean($symb);
1.510 www 11581: $thisurl=&deversion($thisurl);
1.439 www 11582: $thisfn=&deversion($thisfn);
1.213 www 11583:
11584: my %bighash;
11585: my $okay=0;
1.431 www 11586:
1.620 albertel 11587: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11588: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11589: my $noclutter;
1.1032 raeburn 11590: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11591: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11592: if ($map =~ m{^uploaded/.+\.page$}) {
11593: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11594: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11595: $noclutter = 1;
11596: }
11597: }
11598: my $ids;
11599: if ($noclutter) {
11600: $ids=$bighash{'ids_'.$thisurl};
11601: } else {
11602: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11603: }
1.1102 raeburn 11604: unless ($ids) {
1.1172.2.13 raeburn 11605: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11606: $ids=$bighash{$idkey};
1.216 www 11607: }
11608: if ($ids) {
11609: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11610: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11611: $symb =~ s/\?.+$//;
11612: }
1.800 albertel 11613: foreach my $id (split(/\,/,$ids)) {
11614: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11615: if (
11616: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11617: eq $symb) {
1.1172.2.11 raeburn 11618: if (ref($encstate)) {
11619: $$encstate = $bighash{'encrypted_'.$id};
11620: }
1.1172.2.13 raeburn 11621: if (($env{'request.role.adv'}) ||
11622: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11623: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11624: $okay=1;
11625: last;
11626: }
11627: }
11628: }
1.216 www 11629: }
1.213 www 11630: untie(%bighash);
11631: }
11632: return $okay;
1.31 www 11633: }
11634:
1.210 www 11635: # --------------------------------------------------------------- Clean-up symb
11636:
11637: sub symbclean {
11638: my $symb=shift;
1.568 albertel 11639: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11640: # remove version from map
11641: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11642:
1.210 www 11643: # remove version from URL
11644: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11645:
1.507 www 11646: # remove wrapper
11647:
1.510 www 11648: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11649: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11650: return $symb;
1.409 www 11651: }
11652:
11653: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11654:
11655: sub encode_symb {
11656: my ($map,$resid,$url)=@_;
11657: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11658: }
1.409 www 11659:
11660: sub decode_symb {
1.568 albertel 11661: my $symb=shift;
11662: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11663: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11664: return (&fixversion($map),$resid,&fixversion($url));
11665: }
11666:
11667: sub fixversion {
11668: my $fn=shift;
1.609 banghart 11669: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11670: my %bighash;
11671: my $uri=&clutter($fn);
1.620 albertel 11672: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11673: # is this cached?
1.599 albertel 11674: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11675: if (defined($cached)) { return $result; }
11676: # unfortunately not cached, or expired
1.620 albertel 11677: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11678: &GDBM_READER(),0640)) {
11679: if ($bighash{'version_'.$uri}) {
11680: my $version=$bighash{'version_'.$uri};
1.444 www 11681: unless (($version eq 'mostrecent') ||
11682: ($version==&getversion($uri))) {
1.440 www 11683: $uri=~s/\.(\w+)$/\.$version\.$1/;
11684: }
11685: }
11686: untie %bighash;
1.413 www 11687: }
1.599 albertel 11688: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11689: }
11690:
11691: sub deversion {
11692: my $url=shift;
11693: $url=~s/\.\d+\.(\w+)$/\.$1/;
11694: return $url;
1.210 www 11695: }
11696:
1.31 www 11697: # ------------------------------------------------------ Return symb list entry
11698:
11699: sub symbread {
1.1172.2.66 raeburn 11700: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11701: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11702: if (defined($env{$cache_str})) {
11703: if ($ignorecachednull) {
11704: return $env{$cache_str} unless ($env{$cache_str} eq '');
11705: } else {
11706: return $env{$cache_str};
11707: }
11708: }
1.242 www 11709: # no filename provided? try from environment
1.1172.2.54 raeburn 11710: unless ($thisfn) {
1.620 albertel 11711: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11712: return $env{$cache_str}=&symbclean($env{'request.symb'});
11713: }
11714: $thisfn=$env{'request.filename'};
1.44 www 11715: }
1.569 albertel 11716: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11717: # is that filename actually a symb? Verify, clean, and return
11718: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11719: if (&symbverify($thisfn,$1)) {
1.620 albertel 11720: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11721: }
1.242 www 11722: }
1.44 www 11723: $thisfn=declutter($thisfn);
1.31 www 11724: my %hash;
1.37 www 11725: my %bighash;
11726: my $syval='';
1.620 albertel 11727: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11728: my $targetfn = $thisfn;
1.609 banghart 11729: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11730: $targetfn = 'adm/wrapper/'.$thisfn;
11731: }
1.687 albertel 11732: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11733: $targetfn=$1;
11734: }
1.620 albertel 11735: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11736: &GDBM_READER(),0640)) {
1.481 raeburn 11737: $syval=$hash{$targetfn};
1.37 www 11738: untie(%hash);
11739: }
11740: # ---------------------------------------------------------- There was an entry
11741: if ($syval) {
1.601 albertel 11742: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11743: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11744: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11745: #return $env{$cache_str}='';
1.601 albertel 11746: #}
11747: #$syval.=$1;
11748: #}
1.37 www 11749: } else {
11750: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11751: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11752: &GDBM_READER(),0640)) {
1.37 www 11753: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11754: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11755: unless ($ids) {
11756: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11757: }
11758: unless ($ids) {
11759: # alias?
11760: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11761: }
1.37 www 11762: if ($ids) {
11763: # ------------------------------------------------------------------- Has ID(s)
11764: my @possibilities=split(/\,/,$ids);
1.39 www 11765: if ($#possibilities==0) {
11766: # ----------------------------------------------- There is only one possibility
1.37 www 11767: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11768: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11769: $resid,$thisfn);
1.1172.2.66 raeburn 11770: if (ref($possibles) eq 'HASH') {
11771: $possibles->{$syval} = 1;
11772: }
11773: if ($checkforblock) {
11774: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11775: if (@blockers) {
11776: $syval = '';
11777: return;
11778: }
11779: }
11780: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11781: # ------------------------------------------ There is more than one possibility
11782: my $realpossible=0;
1.800 albertel 11783: foreach my $id (@possibilities) {
11784: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11785: my $canaccess;
11786: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11787: $canaccess = 1;
11788: } else {
11789: $canaccess = &allowed('bre',$file);
11790: }
11791: if ($canaccess) {
11792: my ($mapid,$resid)=split(/\./,$id);
11793: if ($bighash{'map_type_'.$mapid} ne 'page') {
11794: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11795: $resid,$thisfn);
11796: if (ref($possibles) eq 'HASH') {
11797: $possibles->{$syval} = 1;
11798: }
11799: if ($checkforblock) {
11800: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11801: unless (@blockers > 0) {
11802: $syval = $poss_syval;
11803: $realpossible++;
11804: }
11805: } else {
11806: $syval = $poss_syval;
11807: $realpossible++;
11808: }
11809: }
1.39 www 11810: }
1.191 harris41 11811: }
1.39 www 11812: if ($realpossible!=1) { $syval=''; }
1.249 www 11813: } else {
11814: $syval='';
1.37 www 11815: }
11816: }
1.1172.2.66 raeburn 11817: untie(%bighash);
1.481 raeburn 11818: }
1.31 www 11819: }
1.62 www 11820: if ($syval) {
1.620 albertel 11821: return $env{$cache_str}=$syval;
1.62 www 11822: }
1.31 www 11823: }
1.949 raeburn 11824: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11825: return $env{$cache_str}='';
1.31 www 11826: }
11827:
11828: # ---------------------------------------------------------- Return random seed
11829:
1.32 www 11830: sub numval {
11831: my $txt=shift;
11832: $txt=~tr/A-J/0-9/;
11833: $txt=~tr/a-j/0-9/;
11834: $txt=~tr/K-T/0-9/;
11835: $txt=~tr/k-t/0-9/;
11836: $txt=~tr/U-Z/0-5/;
11837: $txt=~tr/u-z/0-5/;
11838: $txt=~s/\D//g;
1.564 albertel 11839: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11840: return int($txt);
1.368 albertel 11841: }
11842:
1.484 albertel 11843: sub numval2 {
11844: my $txt=shift;
11845: $txt=~tr/A-J/0-9/;
11846: $txt=~tr/a-j/0-9/;
11847: $txt=~tr/K-T/0-9/;
11848: $txt=~tr/k-t/0-9/;
11849: $txt=~tr/U-Z/0-5/;
11850: $txt=~tr/u-z/0-5/;
11851: $txt=~s/\D//g;
11852: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11853: my $total;
11854: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11855: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11856: return int($total);
11857: }
11858:
1.575 albertel 11859: sub numval3 {
11860: use integer;
11861: my $txt=shift;
11862: $txt=~tr/A-J/0-9/;
11863: $txt=~tr/a-j/0-9/;
11864: $txt=~tr/K-T/0-9/;
11865: $txt=~tr/k-t/0-9/;
11866: $txt=~tr/U-Z/0-5/;
11867: $txt=~tr/u-z/0-5/;
11868: $txt=~s/\D//g;
11869: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11870: my $total;
11871: foreach my $val (@txts) { $total+=$val; }
11872: if ($_64bit) { $total=(($total<<32)>>32); }
11873: return $total;
11874: }
11875:
1.675 albertel 11876: sub digest {
11877: my ($data)=@_;
11878: my $digest=&Digest::MD5::md5($data);
11879: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11880: my ($e,$f);
11881: {
11882: use integer;
11883: $e=($a+$b);
11884: $f=($c+$d);
11885: if ($_64bit) {
11886: $e=(($e<<32)>>32);
11887: $f=(($f<<32)>>32);
11888: }
11889: }
11890: if (wantarray) {
11891: return ($e,$f);
11892: } else {
11893: my $g;
11894: {
11895: use integer;
11896: $g=($e+$f);
11897: if ($_64bit) {
11898: $g=(($g<<32)>>32);
11899: }
11900: }
11901: return $g;
11902: }
11903: }
11904:
1.368 albertel 11905: sub latest_rnd_algorithm_id {
1.675 albertel 11906: return '64bit5';
1.366 albertel 11907: }
1.32 www 11908:
1.503 albertel 11909: sub get_rand_alg {
11910: my ($courseid)=@_;
1.790 albertel 11911: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11912: if ($courseid) {
1.620 albertel 11913: return $env{"course.$courseid.rndseed"};
1.503 albertel 11914: }
11915: return &latest_rnd_algorithm_id();
11916: }
11917:
1.562 albertel 11918: sub validCODE {
11919: my ($CODE)=@_;
11920: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11921: return 0;
11922: }
11923:
1.491 albertel 11924: sub getCODE {
1.620 albertel 11925: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11926: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11927: defined($Apache::lonhomework::parsing_a_task) ) &&
11928: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11929: return $Apache::lonhomework::history{'resource.CODE'};
11930: }
11931: return undef;
11932: }
1.1133 foxr 11933: #
11934: # Determines the random seed for a specific context:
11935: #
11936: # parameters:
11937: # symb - in course context the symb for the seed.
11938: # course_id - The course id of the form domain_coursenum.
11939: # domain - Domain for the user.
11940: # course - Course for the user.
11941: # cenv - environment of the course.
11942: #
11943: # NOTE:
11944: # All parameters are picked out of the environment if missing
11945: # or not defined.
11946: # If a symb cannot be determined the current time is used instead.
11947: #
11948: # For a given well defined symb, courside, domain, username,
11949: # and course environment, the seed is reproducible.
11950: #
1.31 www 11951: sub rndseed {
1.1133 foxr 11952: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11953: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11954: if (!defined($symb)) {
1.366 albertel 11955: unless ($symb=$wsymb) { return time; }
11956: }
1.1146 foxr 11957: if (!defined $courseid) {
11958: $courseid=$wcourseid;
11959: }
11960: if (!defined $domain) { $domain=$wdomain; }
11961: if (!defined $username) { $username=$wusername }
1.1133 foxr 11962:
11963: my $which;
11964: if (defined($cenv->{'rndseed'})) {
11965: $which = $cenv->{'rndseed'};
11966: } else {
11967: $which =&get_rand_alg($courseid);
11968: }
1.491 albertel 11969: if (defined(&getCODE())) {
1.675 albertel 11970: if ($which eq '64bit5') {
11971: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11972: } elsif ($which eq '64bit4') {
1.575 albertel 11973: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11974: } else {
11975: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11976: }
1.675 albertel 11977: } elsif ($which eq '64bit5') {
11978: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11979: } elsif ($which eq '64bit4') {
11980: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11981: } elsif ($which eq '64bit3') {
11982: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11983: } elsif ($which eq '64bit2') {
11984: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11985: } elsif ($which eq '64bit') {
11986: return &rndseed_64bit($symb,$courseid,$domain,$username);
11987: }
11988: return &rndseed_32bit($symb,$courseid,$domain,$username);
11989: }
11990:
11991: sub rndseed_32bit {
11992: my ($symb,$courseid,$domain,$username)=@_;
11993: {
11994: use integer;
11995: my $symbchck=unpack("%32C*",$symb) << 27;
11996: my $symbseed=numval($symb) << 22;
11997: my $namechck=unpack("%32C*",$username) << 17;
11998: my $nameseed=numval($username) << 12;
11999: my $domainseed=unpack("%32C*",$domain) << 7;
12000: my $courseseed=unpack("%32C*",$courseid);
12001: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12002: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12003: #&logthis("rndseed :$num:$symb");
1.564 albertel 12004: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12005: return $num;
12006: }
12007: }
12008:
12009: sub rndseed_64bit {
12010: my ($symb,$courseid,$domain,$username)=@_;
12011: {
12012: use integer;
12013: my $symbchck=unpack("%32S*",$symb) << 21;
12014: my $symbseed=numval($symb) << 10;
12015: my $namechck=unpack("%32S*",$username);
12016:
12017: my $nameseed=numval($username) << 21;
12018: my $domainseed=unpack("%32S*",$domain) << 10;
12019: my $courseseed=unpack("%32S*",$courseid);
12020:
12021: my $num1=$symbchck+$symbseed+$namechck;
12022: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12023: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12024: #&logthis("rndseed :$num:$symb");
1.564 albertel 12025: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12026: return "$num1,$num2";
1.155 albertel 12027: }
1.366 albertel 12028: }
12029:
1.443 albertel 12030: sub rndseed_64bit2 {
12031: my ($symb,$courseid,$domain,$username)=@_;
12032: {
12033: use integer;
12034: # strings need to be an even # of cahracters long, it it is odd the
12035: # last characters gets thrown away
12036: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12037: my $symbseed=numval($symb) << 10;
12038: my $namechck=unpack("%32S*",$username.' ');
12039:
12040: my $nameseed=numval($username) << 21;
1.501 albertel 12041: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12042: my $courseseed=unpack("%32S*",$courseid.' ');
12043:
12044: my $num1=$symbchck+$symbseed+$namechck;
12045: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12046: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12047: #&logthis("rndseed :$num:$symb");
1.803 albertel 12048: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12049: return "$num1,$num2";
12050: }
12051: }
12052:
12053: sub rndseed_64bit3 {
12054: my ($symb,$courseid,$domain,$username)=@_;
12055: {
12056: use integer;
12057: # strings need to be an even # of cahracters long, it it is odd the
12058: # last characters gets thrown away
12059: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12060: my $symbseed=numval2($symb) << 10;
12061: my $namechck=unpack("%32S*",$username.' ');
12062:
12063: my $nameseed=numval2($username) << 21;
1.443 albertel 12064: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12065: my $courseseed=unpack("%32S*",$courseid.' ');
12066:
12067: my $num1=$symbchck+$symbseed+$namechck;
12068: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12069: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12070: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12071: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12072:
1.503 albertel 12073: return "$num1:$num2";
1.443 albertel 12074: }
12075: }
12076:
1.575 albertel 12077: sub rndseed_64bit4 {
12078: my ($symb,$courseid,$domain,$username)=@_;
12079: {
12080: use integer;
12081: # strings need to be an even # of cahracters long, it it is odd the
12082: # last characters gets thrown away
12083: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12084: my $symbseed=numval3($symb) << 10;
12085: my $namechck=unpack("%32S*",$username.' ');
12086:
12087: my $nameseed=numval3($username) << 21;
12088: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12089: my $courseseed=unpack("%32S*",$courseid.' ');
12090:
12091: my $num1=$symbchck+$symbseed+$namechck;
12092: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12093: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12094: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12095: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12096:
1.575 albertel 12097: return "$num1:$num2";
12098: }
12099: }
12100:
1.675 albertel 12101: sub rndseed_64bit5 {
12102: my ($symb,$courseid,$domain,$username)=@_;
12103: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12104: return "$num1:$num2";
12105: }
12106:
1.366 albertel 12107: sub rndseed_CODE_64bit {
12108: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12109: {
1.366 albertel 12110: use integer;
1.443 albertel 12111: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12112: my $symbseed=numval2($symb);
1.491 albertel 12113: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12114: my $CODEseed=numval(&getCODE());
1.443 albertel 12115: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12116: my $num1=$symbseed+$CODEchck;
12117: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12118: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12119: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12120: if ($_64bit) { $num1=(($num1<<32)>>32); }
12121: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12122: return "$num1:$num2";
1.366 albertel 12123: }
12124: }
12125:
1.575 albertel 12126: sub rndseed_CODE_64bit4 {
12127: my ($symb,$courseid,$domain,$username)=@_;
12128: {
12129: use integer;
12130: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12131: my $symbseed=numval3($symb);
12132: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12133: my $CODEseed=numval3(&getCODE());
12134: my $courseseed=unpack("%32S*",$courseid.' ');
12135: my $num1=$symbseed+$CODEchck;
12136: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12137: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12138: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12139: if ($_64bit) { $num1=(($num1<<32)>>32); }
12140: if ($_64bit) { $num2=(($num2<<32)>>32); }
12141: return "$num1:$num2";
12142: }
12143: }
12144:
1.675 albertel 12145: sub rndseed_CODE_64bit5 {
12146: my ($symb,$courseid,$domain,$username)=@_;
12147: my $code = &getCODE();
12148: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12149: return "$num1:$num2";
12150: }
12151:
1.366 albertel 12152: sub setup_random_from_rndseed {
12153: my ($rndseed)=@_;
1.503 albertel 12154: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12155: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12156: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12157: &Math::Random::random_set_seed_from_phrase($rndseed);
12158: } else {
12159: &Math::Random::random_set_seed($num1,$num2);
12160: }
1.366 albertel 12161: } else {
12162: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12163: }
1.36 albertel 12164: }
12165:
1.474 albertel 12166: sub latest_receipt_algorithm_id {
1.835 albertel 12167: return 'receipt3';
1.474 albertel 12168: }
12169:
1.480 www 12170: sub recunique {
12171: my $fucourseid=shift;
12172: my $unique;
1.835 albertel 12173: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12174: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12175: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12176: } else {
12177: $unique=$perlvar{'lonReceipt'};
12178: }
12179: return unpack("%32C*",$unique);
12180: }
12181:
12182: sub recprefix {
12183: my $fucourseid=shift;
12184: my $prefix;
1.835 albertel 12185: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12186: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12187: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12188: } else {
12189: $prefix=$perlvar{'lonHostID'};
12190: }
12191: return unpack("%32C*",$prefix);
12192: }
12193:
1.76 www 12194: sub ireceipt {
1.474 albertel 12195: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12196:
12197: my $return =&recprefix($fucourseid).'-';
12198:
12199: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12200: $env{'request.state'} eq 'construct') {
12201: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12202: return $return;
12203: }
12204:
1.76 www 12205: my $cuname=unpack("%32C*",$funame);
12206: my $cudom=unpack("%32C*",$fudom);
12207: my $cucourseid=unpack("%32C*",$fucourseid);
12208: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12209: my $cunique=&recunique($fucourseid);
1.474 albertel 12210: my $cpart=unpack("%32S*",$part);
1.835 albertel 12211: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12212:
1.790 albertel 12213: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12214:
12215: $return.= ($cunique%$cuname+
12216: $cunique%$cudom+
12217: $cusymb%$cuname+
12218: $cusymb%$cudom+
12219: $cucourseid%$cuname+
12220: $cucourseid%$cudom+
12221: $cpart%$cuname+
12222: $cpart%$cudom);
12223: } else {
12224: $return.= ($cunique%$cuname+
12225: $cunique%$cudom+
12226: $cusymb%$cuname+
12227: $cusymb%$cudom+
12228: $cucourseid%$cuname+
12229: $cucourseid%$cudom);
12230: }
12231: return $return;
1.76 www 12232: }
12233:
12234: sub receipt {
1.474 albertel 12235: my ($part)=@_;
1.790 albertel 12236: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12237: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12238: }
1.260 ng 12239:
1.790 albertel 12240: sub whichuser {
12241: my ($passedsymb)=@_;
12242: my ($symb,$courseid,$domain,$name,$publicuser);
12243: if (defined($env{'form.grade_symb'})) {
12244: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12245: my $allowed=&allowed('vgr',$tmp_courseid);
12246: if (!$allowed &&
12247: exists($env{'request.course.sec'}) &&
12248: $env{'request.course.sec'} !~ /^\s*$/) {
12249: $allowed=&allowed('vgr',$tmp_courseid.
12250: '/'.$env{'request.course.sec'});
12251: }
12252: if ($allowed) {
12253: ($symb)=&get_env_multiple('form.grade_symb');
12254: $courseid=$tmp_courseid;
12255: ($domain)=&get_env_multiple('form.grade_domain');
12256: ($name)=&get_env_multiple('form.grade_username');
12257: return ($symb,$courseid,$domain,$name,$publicuser);
12258: }
12259: }
12260: if (!$passedsymb) {
12261: $symb=&symbread();
12262: } else {
12263: $symb=$passedsymb;
12264: }
12265: $courseid=$env{'request.course.id'};
12266: $domain=$env{'user.domain'};
12267: $name=$env{'user.name'};
12268: if ($name eq 'public' && $domain eq 'public') {
12269: if (!defined($env{'form.username'})) {
12270: $env{'form.username'}.=time.rand(10000000);
12271: }
12272: $name.=$env{'form.username'};
12273: }
12274: return ($symb,$courseid,$domain,$name,$publicuser);
12275:
12276: }
12277:
1.36 albertel 12278: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12279: # returns either the contents of the file or
12280: # -1 if the file doesn't exist
1.481 raeburn 12281: #
12282: # if the target is a file that was uploaded via DOCS,
12283: # a check will be made to see if a current copy exists on the local server,
12284: # if it does this will be served, otherwise a copy will be retrieved from
12285: # the home server for the course and stored in /home/httpd/html/userfiles on
12286: # the local server.
1.472 albertel 12287:
1.36 albertel 12288: sub getfile {
1.538 albertel 12289: my ($file) = @_;
1.609 banghart 12290: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12291: &repcopy($file);
12292: return &readfile($file);
12293: }
12294:
12295: sub repcopy_userfile {
12296: my ($file)=@_;
1.1142 raeburn 12297: my $londocroot = $perlvar{'lonDocRoot'};
12298: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12299: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12300: my ($cdom,$cnum,$filename) =
1.811 albertel 12301: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12302: my $uri="/uploaded/$cdom/$cnum/$filename";
12303: if (-e "$file") {
1.828 www 12304: # we already have a local copy, check it out
1.538 albertel 12305: my @fileinfo = stat($file);
1.828 www 12306: my $rtncode;
12307: my $info;
1.538 albertel 12308: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12309: if ($lwpresp ne 'ok') {
1.828 www 12310: # there is no such file anymore, even though we had a local copy
1.482 albertel 12311: if ($rtncode eq '404') {
1.538 albertel 12312: unlink($file);
1.482 albertel 12313: }
12314: return -1;
12315: }
12316: if ($info < $fileinfo[9]) {
1.828 www 12317: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12318: return 'ok';
1.828 www 12319: } else {
12320: # the file is outdated, get rid of it
12321: unlink($file);
1.482 albertel 12322: }
1.828 www 12323: }
12324: # one way or the other, at this point, we don't have the file
12325: # construct the correct path for the file
12326: my @parts = ($cdom,$cnum);
12327: if ($filename =~ m|^(.+)/[^/]+$|) {
12328: push @parts, split(/\//,$1);
12329: }
12330: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12331: foreach my $part (@parts) {
12332: $path .= '/'.$part;
12333: if (!-e $path) {
12334: mkdir($path,0770);
1.482 albertel 12335: }
12336: }
1.828 www 12337: # now the path exists for sure
12338: # get a user agent
12339: my $ua=new LWP::UserAgent;
12340: my $transferfile=$file.'.in.transfer';
12341: # FIXME: this should flock
12342: if (-e $transferfile) { return 'ok'; }
12343: my $request;
12344: $uri=~s/^\///;
1.980 raeburn 12345: my $homeserver = &homeserver($cnum,$cdom);
12346: my $protocol = $protocol{$homeserver};
12347: $protocol = 'http' if ($protocol ne 'https');
12348: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12349: my $response=$ua->request($request,$transferfile);
12350: # did it work?
12351: if ($response->is_error()) {
12352: unlink($transferfile);
12353: &logthis("Userfile repcopy failed for $uri");
12354: return -1;
12355: }
12356: # worked, rename the transfer file
12357: rename($transferfile,$file);
1.607 raeburn 12358: return 'ok';
1.481 raeburn 12359: }
12360:
1.517 albertel 12361: sub tokenwrapper {
12362: my $uri=shift;
1.980 raeburn 12363: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12364: $uri=~s|^/||;
1.620 albertel 12365: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12366: my $token=$1;
1.552 albertel 12367: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12368: if ($udom && $uname && $file) {
12369: $file=~s|(\?\.*)*$||;
1.949 raeburn 12370: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12371: my $homeserver = &homeserver($uname,$udom);
12372: my $protocol = $protocol{$homeserver};
12373: $protocol = 'http' if ($protocol ne 'https');
12374: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12375: (($uri=~/\?/)?'&':'?').'token='.$token.
12376: '&tokenissued='.$perlvar{'lonHostID'};
12377: } else {
12378: return '/adm/notfound.html';
12379: }
12380: }
12381:
1.828 www 12382: # call with reqtype HEAD: get last modification time
12383: # call with reqtype GET: get the file contents
12384: # Do not call this with reqtype GET for large files! It loads everything into memory
12385: #
1.481 raeburn 12386: sub getuploaded {
12387: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12388: $uri=~s/^\///;
1.980 raeburn 12389: my $homeserver = &homeserver($cnum,$cdom);
12390: my $protocol = $protocol{$homeserver};
12391: $protocol = 'http' if ($protocol ne 'https');
12392: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12393: my $ua=new LWP::UserAgent;
12394: my $request=new HTTP::Request($reqtype,$uri);
12395: my $response=$ua->request($request);
12396: $$rtncode = $response->code;
1.482 albertel 12397: if (! $response->is_success()) {
12398: return 'failed';
12399: }
12400: if ($reqtype eq 'HEAD') {
1.486 www 12401: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12402: } elsif ($reqtype eq 'GET') {
12403: $$info = $response->content;
1.472 albertel 12404: }
1.482 albertel 12405: return 'ok';
1.36 albertel 12406: }
12407:
1.481 raeburn 12408: sub readfile {
12409: my $file = shift;
12410: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12411: my $fh;
12412: open($fh,"<$file");
12413: my $a='';
1.800 albertel 12414: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12415: return $a;
12416: }
12417:
1.36 albertel 12418: sub filelocation {
1.590 banghart 12419: my ($dir,$file) = @_;
12420: my $location;
12421: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12422:
12423: if ($file =~ m-^/adm/-) {
12424: $file=~s-^/adm/wrapper/-/-;
12425: $file=~s-^/adm/coursedocs/showdoc/-/-;
12426: }
1.882 albertel 12427:
1.1139 www 12428: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12429: $location = $file;
1.609 banghart 12430: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12431: my ($udom,$uname,$filename)=
1.811 albertel 12432: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12433: my $home=&homeserver($uname,$udom);
12434: my $is_me=0;
12435: my @ids=¤t_machine_ids();
12436: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12437: if ($is_me) {
1.1117 foxr 12438: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12439: } else {
12440: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12441: $udom.'/'.$uname.'/'.$filename;
12442: }
1.882 albertel 12443: } elsif ($file =~ m-^/adm/-) {
12444: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12445: } else {
12446: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12447: $file=~s:^/(res|priv)/:/:;
12448: my $space=$1;
1.590 banghart 12449: if ( !( $file =~ m:^/:) ) {
12450: $location = $dir. '/'.$file;
12451: } else {
1.1142 raeburn 12452: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12453: }
1.59 albertel 12454: }
1.590 banghart 12455: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12456: while ($location=~m{/\.\./}) {
12457: if ($location =~ m{/[^/]+/\.\./}) {
12458: $location=~ s{/[^/]+/\.\./}{/}g;
12459: } else {
12460: $location=~ s{/\.\./}{/}g;
12461: }
12462: } #remove dir/..
1.590 banghart 12463: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12464: return $location;
1.46 www 12465: }
1.36 albertel 12466:
1.46 www 12467: sub hreflocation {
12468: my ($dir,$file)=@_;
1.980 raeburn 12469: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12470: $file=filelocation($dir,$file);
1.700 albertel 12471: } elsif ($file=~m-^/adm/-) {
12472: $file=~s-^/adm/wrapper/-/-;
12473: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12474: }
12475: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12476: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12477: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12478: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12479: {/uploaded/$1/$2/}x;
1.46 www 12480: }
1.913 albertel 12481: if ($file=~ m{^/userfiles/}) {
12482: $file =~ s{^/userfiles/}{/uploaded/};
12483: }
1.462 albertel 12484: return $file;
1.465 albertel 12485: }
12486:
1.1139 www 12487:
12488:
12489:
12490:
1.465 albertel 12491: sub current_machine_domains {
1.853 albertel 12492: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12493: }
12494:
12495: sub machine_domains {
12496: my ($hostname) = @_;
1.465 albertel 12497: my @domains;
1.838 albertel 12498: my %hostname = &all_hostnames();
1.465 albertel 12499: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12500: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12501: if ($hostname eq $name) {
1.844 albertel 12502: push(@domains,&host_domain($id));
1.465 albertel 12503: }
12504: }
12505: return @domains;
12506: }
12507:
12508: sub current_machine_ids {
1.853 albertel 12509: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12510: }
12511:
12512: sub machine_ids {
12513: my ($hostname) = @_;
12514: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12515: my @ids;
1.888 albertel 12516: my %name_to_host = &all_names();
1.889 albertel 12517: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12518: return @{ $name_to_host{$hostname} };
12519: }
12520: return;
1.31 www 12521: }
12522:
1.824 raeburn 12523: sub additional_machine_domains {
12524: my @domains;
12525: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12526: while( my $line = <$fh>) {
12527: $line =~ s/\s//g;
12528: push(@domains,$line);
12529: }
12530: return @domains;
12531: }
12532:
12533: sub default_login_domain {
12534: my $domain = $perlvar{'lonDefDomain'};
12535: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12536: foreach my $posdom (¤t_machine_domains(),
12537: &additional_machine_domains()) {
12538: if (lc($posdom) eq lc($testdomain)) {
12539: $domain=$posdom;
12540: last;
12541: }
12542: }
12543: return $domain;
12544: }
12545:
1.31 www 12546: # ------------------------------------------------------------- Declutters URLs
12547:
12548: sub declutter {
12549: my $thisfn=shift;
1.569 albertel 12550: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12551: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12552: $thisfn=~s{^/home/httpd/html}{};
12553: }
1.31 www 12554: $thisfn=~s/^\///;
1.697 albertel 12555: $thisfn=~s|^adm/wrapper/||;
12556: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12557: $thisfn=~s/^res\///;
1.1172 bisitz 12558: $thisfn=~s/^priv\///;
1.1032 raeburn 12559: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12560: $thisfn=~s/\?.+$//;
12561: }
1.268 www 12562: return $thisfn;
12563: }
12564:
12565: # ------------------------------------------------------------- Clutter up URLs
12566:
12567: sub clutter {
12568: my $thisfn='/'.&declutter(shift);
1.887 albertel 12569: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12570: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12571: $thisfn='/res'.$thisfn;
12572: }
1.1031 raeburn 12573: if ($thisfn !~m|^/adm|) {
12574: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12575: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12576: } else {
12577: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12578: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12579: if ($embstyle eq 'ssi'
12580: || ($embstyle eq 'hdn')
12581: || ($embstyle eq 'rat')
12582: || ($embstyle eq 'prv')
12583: || ($embstyle eq 'ign')) {
12584: #do nothing with these
12585: } elsif (($embstyle eq 'img')
1.695 albertel 12586: || ($embstyle eq 'emb')
12587: || ($embstyle eq 'wrp')) {
12588: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12589: } elsif ($embstyle eq 'unk'
12590: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12591: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12592: } else {
1.718 www 12593: # &logthis("Got a blank emb style");
1.695 albertel 12594: }
1.694 albertel 12595: }
1.1172.2.93.4 2(raebur 12596:7): } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
12597:7): $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12598: }
1.31 www 12599: return $thisfn;
1.12 www 12600: }
12601:
1.787 albertel 12602: sub clutter_with_no_wrapper {
12603: my $uri = &clutter(shift);
12604: if ($uri =~ m-^/adm/-) {
12605: $uri =~ s-^/adm/wrapper/-/-;
12606: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12607: }
12608: return $uri;
12609: }
12610:
1.557 albertel 12611: sub freeze_escape {
12612: my ($value)=@_;
12613: if (ref($value)) {
12614: $value=&nfreeze($value);
12615: return '__FROZEN__'.&escape($value);
12616: }
12617: return &escape($value);
12618: }
12619:
1.11 www 12620:
1.557 albertel 12621: sub thaw_unescape {
12622: my ($value)=@_;
12623: if ($value =~ /^__FROZEN__/) {
12624: substr($value,0,10,undef);
12625: $value=&unescape($value);
12626: return &thaw($value);
12627: }
12628: return &unescape($value);
12629: }
12630:
1.436 albertel 12631: sub correct_line_ends {
12632: my ($result)=@_;
12633: $$result =~s/\r\n/\n/mg;
12634: $$result =~s/\r/\n/mg;
1.415 albertel 12635: }
1.1 albertel 12636: # ================================================================ Main Program
12637:
1.184 www 12638: sub goodbye {
1.204 albertel 12639: &logthis("Starting Shut down");
1.443 albertel 12640: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12641: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12642: #converted
1.599 albertel 12643: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12644: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12645: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12646: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12647: #1.1 only
1.870 albertel 12648: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12649: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12650: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12651: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12652: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12653: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12654: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12655: &flushcourselogs();
12656: &logthis("Shutting down");
12657: }
12658:
1.852 albertel 12659: sub get_dns {
1.1172.2.17 raeburn 12660: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12661: if (!$ignore_cache) {
12662: my ($content,$cached)=
12663: &Apache::lonnet::is_cached_new('dns',$url);
12664: if ($cached) {
1.1172.2.17 raeburn 12665: &$func($content,$hashref);
1.869 albertel 12666: return;
12667: }
12668: }
12669:
12670: my %alldns;
1.852 albertel 12671: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12672: foreach my $dns (<$config>) {
12673: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12674: my $line = $1;
12675: my ($host,$protocol) = split(/:/,$line);
12676: if ($protocol ne 'https') {
12677: $protocol = 'http';
12678: }
12679: $alldns{$host} = $protocol;
1.869 albertel 12680: }
12681: while (%alldns) {
1.1172.2.52 raeburn 12682: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12683: my $ua=new LWP::UserAgent;
1.1134 raeburn 12684: $ua->timeout(30);
1.979 raeburn 12685: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12686: my $response=$ua->request($request);
1.979 raeburn 12687: delete($alldns{$dns});
1.852 albertel 12688: next if ($response->is_error());
12689: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12690: unless ($nocache) {
1.1172.2.23 raeburn 12691: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12692: }
12693: &$func(\@content,$hashref);
1.869 albertel 12694: return;
1.852 albertel 12695: }
12696: close($config);
1.871 albertel 12697: my $which = (split('/',$url))[3];
12698: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12699: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12700: my @content = <$config>;
1.1172.2.17 raeburn 12701: &$func(\@content,$hashref);
12702: return;
12703: }
12704:
12705: # ------------------------------------------------------Get DNS checksums file
12706: sub parse_dns_checksums_tab {
12707: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12708: my $lonhost = $perlvar{'lonHostID'};
12709: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12710: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12711: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12712: my $webconfdir = '/etc/httpd/conf';
12713: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12714: $webconfdir = '/etc/apache2';
12715: } elsif ($distro =~ /^sles(\d+)$/) {
12716: if ($1 >= 10) {
12717: $webconfdir = '/etc/apache2';
12718: }
12719: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12720: if ($1 >= 10.0) {
12721: $webconfdir = '/etc/apache2';
12722: }
12723: }
1.1172.2.17 raeburn 12724: my ($release,$timestamp) = split(/\-/,$loncaparev);
12725: my (%chksum,%revnum);
12726: if (ref($lines) eq 'ARRAY') {
12727: chomp(@{$lines});
1.1172.2.34 raeburn 12728: my $version = shift(@{$lines});
12729: if ($version eq $release) {
1.1172.2.17 raeburn 12730: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12731: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12732: if ($file =~ m{^/etc/httpd/conf}) {
12733: if ($webconfdir eq '/etc/apache2') {
12734: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12735: }
12736: }
1.1172.2.34 raeburn 12737: $chksum{$file} = $shasum;
12738: $revnum{$file} = $version;
1.1172.2.17 raeburn 12739: }
12740: if (ref($hashref) eq 'HASH') {
12741: %{$hashref} = (
12742: sums => \%chksum,
12743: versions => \%revnum,
12744: );
12745: }
12746: }
12747: }
1.869 albertel 12748: return;
1.852 albertel 12749: }
1.1172.2.17 raeburn 12750:
12751: sub fetch_dns_checksums {
12752: my %checksums;
1.1172.2.34 raeburn 12753: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12754: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12755: my ($release,$timestamp) = split(/\-/,$loncaparev);
12756: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12757: \%checksums);
12758: return \%checksums;
12759: }
12760:
1.327 albertel 12761: # ------------------------------------------------------------ Read domain file
12762: {
1.852 albertel 12763: my $loaded;
1.846 albertel 12764: my %domain;
12765:
1.852 albertel 12766: sub parse_domain_tab {
12767: my ($lines) = @_;
12768: foreach my $line (@$lines) {
12769: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12770:
1.846 albertel 12771: chomp($line);
1.852 albertel 12772: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12773: my %this_domain;
12774: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12775: 'lang_def', 'city', 'longi', 'lati',
12776: 'primary') {
12777: $this_domain{$field} = shift(@elements);
12778: }
12779: $domain{$name} = \%this_domain;
1.852 albertel 12780: }
12781: }
1.864 albertel 12782:
12783: sub reset_domain_info {
12784: undef($loaded);
12785: undef(%domain);
12786: }
12787:
1.852 albertel 12788: sub load_domain_tab {
1.1172.2.70 raeburn 12789: my ($ignore_cache,$nocache) = @_;
12790: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12791: my $fh;
12792: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12793: my @lines = <$fh>;
12794: &parse_domain_tab(\@lines);
1.448 albertel 12795: }
1.852 albertel 12796: close($fh);
12797: $loaded = 1;
1.327 albertel 12798: }
1.846 albertel 12799:
12800: sub domain {
1.852 albertel 12801: &load_domain_tab() if (!$loaded);
12802:
1.846 albertel 12803: my ($name,$what) = @_;
12804: return if ( !exists($domain{$name}) );
12805:
12806: if (!$what) {
12807: return $domain{$name}{'description'};
12808: }
12809: return $domain{$name}{$what};
12810: }
1.974 raeburn 12811:
12812: sub domain_info {
12813: &load_domain_tab() if (!$loaded);
12814: return %domain;
12815: }
12816:
1.327 albertel 12817: }
12818:
12819:
1.1 albertel 12820: # ------------------------------------------------------------- Read hosts file
12821: {
1.838 albertel 12822: my %hostname;
1.844 albertel 12823: my %hostdom;
1.845 albertel 12824: my %libserv;
1.852 albertel 12825: my $loaded;
1.888 albertel 12826: my %name_to_host;
1.1074 raeburn 12827: my %internetdom;
1.1107 raeburn 12828: my %LC_dns_serv;
1.852 albertel 12829:
12830: sub parse_hosts_tab {
12831: my ($file) = @_;
12832: foreach my $configline (@$file) {
12833: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12834: chomp($configline);
12835: if ($configline =~ /^\^/) {
12836: if ($configline =~ /^\^([\w.\-]+)/) {
12837: $LC_dns_serv{$1} = 1;
12838: }
12839: next;
12840: }
1.1074 raeburn 12841: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12842: $name=~s/\s//g;
12843: if ($id && $domain && $role && $name) {
1.1172.2.93.4 3(raebur 12844:7): if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
12845:7): my $curr = $hostname{$id};
12846:7): my $skip;
12847:7): if (ref($name_to_host{$curr}) eq 'ARRAY') {
12848:7): if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
12849:7): $skip = 1;
12850:7): } else {
12851:7): @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
12852:7): }
12853:7): }
12854:7): unless ($skip) {
12855:7): push(@{$name_to_host{$name}},$id);
12856:7): }
12857:7): } else {
12858:7): push(@{$name_to_host{$name}},$id);
12859:7): }
1.852 albertel 12860: $hostname{$id}=$name;
12861: $hostdom{$id}=$domain;
12862: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12863: if (defined($protocol)) {
12864: if ($protocol eq 'https') {
12865: $protocol{$id} = $protocol;
12866: } else {
12867: $protocol{$id} = 'http';
12868: }
1.968 raeburn 12869: } else {
1.969 raeburn 12870: $protocol{$id} = 'http';
1.968 raeburn 12871: }
1.1074 raeburn 12872: if (defined($intdom)) {
12873: $internetdom{$id} = $intdom;
12874: }
1.852 albertel 12875: }
12876: }
12877: }
1.864 albertel 12878:
12879: sub reset_hosts_info {
1.897 albertel 12880: &purge_remembered();
1.864 albertel 12881: &reset_domain_info();
12882: &reset_hosts_ip_info();
1.892 albertel 12883: undef(%name_to_host);
1.864 albertel 12884: undef(%hostname);
12885: undef(%hostdom);
12886: undef(%libserv);
12887: undef($loaded);
12888: }
1.1 albertel 12889:
1.852 albertel 12890: sub load_hosts_tab {
1.1172.2.70 raeburn 12891: my ($ignore_cache,$nocache) = @_;
12892: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12893: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12894: my @config = <$config>;
12895: &parse_hosts_tab(\@config);
12896: close($config);
12897: $loaded=1;
1.1 albertel 12898: }
1.852 albertel 12899:
1.838 albertel 12900: sub hostname {
1.852 albertel 12901: &load_hosts_tab() if (!$loaded);
12902:
1.838 albertel 12903: my ($lonid) = @_;
12904: return $hostname{$lonid};
12905: }
1.845 albertel 12906:
1.838 albertel 12907: sub all_hostnames {
1.852 albertel 12908: &load_hosts_tab() if (!$loaded);
12909:
1.838 albertel 12910: return %hostname;
12911: }
1.845 albertel 12912:
1.888 albertel 12913: sub all_names {
1.1172.2.70 raeburn 12914: my ($ignore_cache,$nocache) = @_;
12915: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12916:
12917: return %name_to_host;
12918: }
12919:
1.974 raeburn 12920: sub all_host_domain {
12921: &load_hosts_tab() if (!$loaded);
12922: return %hostdom;
12923: }
12924:
1.845 albertel 12925: sub is_library {
1.852 albertel 12926: &load_hosts_tab() if (!$loaded);
12927:
1.845 albertel 12928: return exists($libserv{$_[0]});
12929: }
12930:
12931: sub all_library {
1.852 albertel 12932: &load_hosts_tab() if (!$loaded);
12933:
1.845 albertel 12934: return %libserv;
12935: }
12936:
1.1062 droeschl 12937: sub unique_library {
12938: #2x reverse removes all hostnames that appear more than once
12939: my %unique = reverse &all_library();
12940: return reverse %unique;
12941: }
12942:
1.841 albertel 12943: sub get_servers {
1.852 albertel 12944: &load_hosts_tab() if (!$loaded);
12945:
1.841 albertel 12946: my ($domain,$type) = @_;
12947: my %possible_hosts = ($type eq 'library') ? %libserv
12948: : %hostname;
12949: my %result;
1.842 albertel 12950: if (ref($domain) eq 'ARRAY') {
12951: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12952: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12953: $result{$host} = $hostname;
12954: }
12955: }
12956: } else {
12957: while ( my ($host,$hostname) = each(%possible_hosts)) {
12958: if ($hostdom{$host} eq $domain) {
12959: $result{$host} = $hostname;
12960: }
1.841 albertel 12961: }
12962: }
12963: return %result;
12964: }
1.845 albertel 12965:
1.1062 droeschl 12966: sub get_unique_servers {
12967: my %unique = reverse &get_servers(@_);
12968: return reverse %unique;
12969: }
12970:
1.844 albertel 12971: sub host_domain {
1.852 albertel 12972: &load_hosts_tab() if (!$loaded);
12973:
1.844 albertel 12974: my ($lonid) = @_;
12975: return $hostdom{$lonid};
12976: }
12977:
1.841 albertel 12978: sub all_domains {
1.852 albertel 12979: &load_hosts_tab() if (!$loaded);
12980:
1.841 albertel 12981: my %seen;
12982: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12983: return @uniq;
12984: }
1.1074 raeburn 12985:
12986: sub internet_dom {
12987: &load_hosts_tab() if (!$loaded);
12988:
12989: my ($lonid) = @_;
12990: return $internetdom{$lonid};
12991: }
1.1107 raeburn 12992:
12993: sub is_LC_dns {
12994: &load_hosts_tab() if (!$loaded);
12995:
12996: my ($hostname) = @_;
12997: return exists($LC_dns_serv{$hostname});
12998: }
12999:
1.1 albertel 13000: }
13001:
1.847 albertel 13002: {
13003: my %iphost;
1.856 albertel 13004: my %name_to_ip;
13005: my %lonid_to_ip;
1.869 albertel 13006:
1.847 albertel 13007: sub get_hosts_from_ip {
13008: my ($ip) = @_;
13009: my %iphosts = &get_iphost();
13010: if (ref($iphosts{$ip})) {
13011: return @{$iphosts{$ip}};
13012: }
13013: return;
1.839 albertel 13014: }
1.864 albertel 13015:
13016: sub reset_hosts_ip_info {
13017: undef(%iphost);
13018: undef(%name_to_ip);
13019: undef(%lonid_to_ip);
13020: }
1.856 albertel 13021:
13022: sub get_host_ip {
13023: my ($lonid) = @_;
13024: if (exists($lonid_to_ip{$lonid})) {
13025: return $lonid_to_ip{$lonid};
13026: }
13027: my $name=&hostname($lonid);
13028: my $ip = gethostbyname($name);
13029: return if (!$ip || length($ip) ne 4);
13030: $ip=inet_ntoa($ip);
13031: $name_to_ip{$name} = $ip;
13032: $lonid_to_ip{$lonid} = $ip;
13033: return $ip;
13034: }
1.847 albertel 13035:
13036: sub get_iphost {
1.1172.2.70 raeburn 13037: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13038:
1.869 albertel 13039: if (!$ignore_cache) {
13040: if (%iphost) {
13041: return %iphost;
13042: }
13043: my ($ip_info,$cached)=
13044: &Apache::lonnet::is_cached_new('iphost','iphost');
13045: if ($cached) {
13046: %iphost = %{$ip_info->[0]};
13047: %name_to_ip = %{$ip_info->[1]};
13048: %lonid_to_ip = %{$ip_info->[2]};
13049: return %iphost;
13050: }
13051: }
1.894 albertel 13052:
13053: # get yesterday's info for fallback
13054: my %old_name_to_ip;
13055: my ($ip_info,$cached)=
13056: &Apache::lonnet::is_cached_new('iphost','iphost');
13057: if ($cached) {
13058: %old_name_to_ip = %{$ip_info->[1]};
13059: }
13060:
1.1172.2.70 raeburn 13061: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13062: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13063: my $ip;
13064: if (!exists($name_to_ip{$name})) {
13065: $ip = gethostbyname($name);
13066: if (!$ip || length($ip) ne 4) {
1.894 albertel 13067: if (defined($old_name_to_ip{$name})) {
13068: $ip = $old_name_to_ip{$name};
13069: &logthis("Can't find $name defaulting to old $ip");
13070: } else {
13071: &logthis("Name $name no IP found");
13072: next;
13073: }
13074: } else {
13075: $ip=inet_ntoa($ip);
1.847 albertel 13076: }
13077: $name_to_ip{$name} = $ip;
13078: } else {
13079: $ip = $name_to_ip{$name};
1.653 albertel 13080: }
1.888 albertel 13081: foreach my $id (@{ $name_to_host{$name} }) {
13082: $lonid_to_ip{$id} = $ip;
13083: }
13084: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13085: }
1.1172.2.70 raeburn 13086: unless ($nocache) {
13087: &do_cache_new('iphost','iphost',
13088: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13089: 48*60*60);
13090: }
1.869 albertel 13091:
1.847 albertel 13092: return %iphost;
1.598 albertel 13093: }
13094:
1.992 raeburn 13095: #
13096: # Given a DNS returns the loncapa host name for that DNS
13097: #
13098: sub host_from_dns {
13099: my ($dns) = @_;
13100: my @hosts;
13101: my $ip;
13102:
1.993 raeburn 13103: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13104: $ip = $name_to_ip{$dns};
13105: }
13106: if (!$ip) {
13107: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13108: if (length($ip) == 4) {
13109: $ip = &IO::Socket::inet_ntoa($ip);
13110: }
13111: }
13112: if ($ip) {
13113: @hosts = get_hosts_from_ip($ip);
13114: return $hosts[0];
13115: }
13116: return undef;
1.986 foxr 13117: }
1.992 raeburn 13118:
1.1074 raeburn 13119: sub get_internet_names {
13120: my ($lonid) = @_;
13121: return if ($lonid eq '');
13122: my ($idnref,$cached)=
13123: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13124: if ($cached) {
13125: return $idnref;
13126: }
13127: my $ip = &get_host_ip($lonid);
13128: my @hosts = &get_hosts_from_ip($ip);
13129: my %iphost = &get_iphost();
13130: my (@idns,%seen);
13131: foreach my $id (@hosts) {
13132: my $dom = &host_domain($id);
13133: my $prim_id = &domain($dom,'primary');
13134: my $prim_ip = &get_host_ip($prim_id);
13135: next if ($seen{$prim_ip});
13136: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13137: foreach my $id (@{$iphost{$prim_ip}}) {
13138: my $intdom = &internet_dom($id);
13139: unless (grep(/^\Q$intdom\E$/,@idns)) {
13140: push(@idns,$intdom);
13141: }
13142: }
13143: }
13144: $seen{$prim_ip} = 1;
13145: }
1.1172.2.23 raeburn 13146: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13147: }
13148:
1.986 foxr 13149: }
13150:
1.1079 raeburn 13151: sub all_loncaparevs {
1.1172.2.39 raeburn 13152: 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 13153: }
13154:
1.1172.2.27 raeburn 13155: # ------------------------------------------------------- Read loncaparev table
13156: {
13157: sub load_loncaparevs {
13158: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13159: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13160: while (my $configline=<$config>) {
13161: chomp($configline);
13162: my ($hostid,$loncaparev)=split(/:/,$configline);
13163: $loncaparevs{$hostid}=$loncaparev;
13164: }
13165: close($config);
13166: }
13167: }
13168: }
13169: }
13170:
13171: # ----------------------------------------------------- Read serverhostID table
13172: {
13173: sub load_serverhomeIDs {
13174: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13175: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13176: while (my $configline=<$config>) {
13177: chomp($configline);
13178: my ($name,$id)=split(/:/,$configline);
13179: $serverhomeIDs{$name}=$id;
13180: }
13181: close($config);
13182: }
13183: }
13184: }
13185: }
13186:
13187:
1.862 albertel 13188: BEGIN {
13189:
13190: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13191: unless ($readit) {
13192: {
13193: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13194: %perlvar = (%perlvar,%{$configvars});
13195: }
13196:
13197:
1.1 albertel 13198: # ------------------------------------------------------ Read spare server file
13199: {
1.448 albertel 13200: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13201:
13202: while (my $configline=<$config>) {
13203: chomp($configline);
1.284 matthew 13204: if ($configline) {
1.784 albertel 13205: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13206: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13207: push(@{ $spareid{$type} }, $host);
1.1 albertel 13208: }
13209: }
1.448 albertel 13210: close($config);
1.1 albertel 13211: }
1.11 www 13212: # ------------------------------------------------------------ Read permissions
13213: {
1.448 albertel 13214: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13215:
13216: while (my $configline=<$config>) {
1.448 albertel 13217: chomp($configline);
13218: if ($configline) {
13219: my ($role,$perm)=split(/ /,$configline);
13220: if ($perm ne '') { $pr{$role}=$perm; }
13221: }
1.11 www 13222: }
1.448 albertel 13223: close($config);
1.11 www 13224: }
13225:
13226: # -------------------------------------------- Read plain texts for permissions
13227: {
1.448 albertel 13228: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13229:
13230: while (my $configline=<$config>) {
1.448 albertel 13231: chomp($configline);
13232: if ($configline) {
1.742 raeburn 13233: my ($short,@plain)=split(/:/,$configline);
13234: %{$prp{$short}} = ();
13235: if (@plain > 0) {
13236: $prp{$short}{'std'} = $plain[0];
13237: for (my $i=1; $i<@plain; $i++) {
13238: $prp{$short}{'alt'.$i} = $plain[$i];
13239: }
13240: }
1.448 albertel 13241: }
1.135 www 13242: }
1.448 albertel 13243: close($config);
1.135 www 13244: }
13245:
13246: # ---------------------------------------------------------- Read package table
13247: {
1.448 albertel 13248: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13249:
13250: while (my $configline=<$config>) {
1.483 albertel 13251: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13252: chomp($configline);
13253: my ($short,$plain)=split(/:/,$configline);
13254: my ($pack,$name)=split(/\&/,$short);
13255: if ($plain ne '') {
13256: $packagetab{$pack.'&'.$name.'&name'}=$name;
13257: $packagetab{$short}=$plain;
13258: }
1.11 www 13259: }
1.448 albertel 13260: close($config);
1.329 matthew 13261: }
13262:
1.1172.2.27 raeburn 13263: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13264:
1.1172.2.27 raeburn 13265: &load_loncaparevs();
13266:
13267: # ------------------------------------------------------- Read serverhostID table
13268:
13269: &load_serverhomeIDs();
1.1074 raeburn 13270:
1.1172.2.27 raeburn 13271: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13272: {
13273: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13274: if (-e $file) {
13275: my $parser = HTML::LCParser->new($file);
13276: while (my $token = $parser->get_token()) {
13277: if ($token->[0] eq 'S') {
13278: my $item = $token->[1];
13279: my $name = $token->[2]{'name'};
13280: my $value = $token->[2]{'value'};
13281: if ($item ne '' && $name ne '' && $value ne '') {
13282: my $release = $parser->get_text();
13283: $release =~ s/(^\s*|\s*$ )//gx;
13284: $needsrelease{$item.':'.$name.':'.$value} = $release;
13285: }
13286: }
13287: }
13288: }
1.1073 raeburn 13289: }
13290:
1.1138 raeburn 13291: # ---------------------------------------------------------- Read managers table
13292: {
13293: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13294: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13295: while (my $configline=<$config>) {
13296: chomp($configline);
13297: next if ($configline =~ /^\#/);
13298: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13299: $managerstab{$configline} = 1;
13300: }
13301: }
13302: close($config);
13303: }
13304: }
13305: }
13306:
1.329 matthew 13307: # ------------- set up temporary directory
13308: {
1.1117 foxr 13309: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13310:
1.11 www 13311: }
13312:
1.794 albertel 13313: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13314: 'compress_threshold'=> 20_000,
13315: });
1.185 www 13316:
1.281 www 13317: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13318: $dumpcount=0;
1.958 www 13319: $locknum=0;
1.22 www 13320:
1.163 harris41 13321: &logtouch();
1.672 albertel 13322: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13323: $readit=1;
1.564 albertel 13324: {
13325: use integer;
13326: my $test=(2**32)+1;
1.568 albertel 13327: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13328: &logthis(" Detected 64bit platform ($_64bit)");
13329: }
1.195 www 13330: }
1.1 albertel 13331: }
1.179 www 13332:
1.1 albertel 13333: 1;
1.191 harris41 13334: __END__
13335:
1.243 albertel 13336: =pod
13337:
1.191 harris41 13338: =head1 NAME
13339:
1.243 albertel 13340: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13341:
13342: =head1 SYNOPSIS
13343:
1.243 albertel 13344: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13345:
13346: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13347:
1.243 albertel 13348: Common parameters:
13349:
13350: =over 4
13351:
13352: =item *
13353:
13354: $uname : an internal username (if $cname expecting a course Id specifically)
13355:
13356: =item *
13357:
13358: $udom : a domain (if $cdom expecting a course's domain specifically)
13359:
13360: =item *
13361:
13362: $symb : a resource instance identifier
13363:
13364: =item *
13365:
13366: $namespace : the name of a .db file that contains the data needed or
13367: being set.
13368:
13369: =back
13370:
1.394 bowersj2 13371: =head1 OVERVIEW
1.191 harris41 13372:
1.394 bowersj2 13373: lonnet provides subroutines which interact with the
13374: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13375: about classes, users, and resources.
1.243 albertel 13376:
13377: For many of these objects you can also use this to store data about
13378: them or modify them in various ways.
1.191 harris41 13379:
1.394 bowersj2 13380: =head2 Symbs
1.191 harris41 13381:
1.394 bowersj2 13382: To identify a specific instance of a resource, LON-CAPA uses symbols
13383: or "symbs"X<symb>. These identifiers are built from the URL of the
13384: map, the resource number of the resource in the map, and the URL of
13385: the resource itself. The latter is somewhat redundant, but might help
13386: if maps change.
13387:
13388: An example is
13389:
13390: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13391:
13392: The respective map entry is
13393:
13394: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13395: title="Problem 2">
13396: </resource>
13397:
13398: Symbs are used by the random number generator, as well as to store and
13399: restore data specific to a certain instance of for example a problem.
13400:
13401: =head2 Storing And Retrieving Data
13402:
13403: X<store()>X<cstore()>X<restore()>Three of the most important functions
13404: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13405: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13406: is is the non-critical message twin of cstore. These functions are for
13407: handlers to store a perl hash to a user's permanent data space in an
13408: easy manner, and to retrieve it again on another call. It is expected
13409: that a handler would use this once at the beginning to retrieve data,
13410: and then again once at the end to send only the new data back.
13411:
13412: The data is stored in the user's data directory on the user's
13413: homeserver under the ID of the course.
13414:
13415: The hash that is returned by restore will have all of the previous
13416: value for all of the elements of the hash.
13417:
13418: Example:
13419:
13420: #creating a hash
13421: my %hash;
13422: $hash{'foo'}='bar';
13423:
13424: #storing it
13425: &Apache::lonnet::cstore(\%hash);
13426:
13427: #changing a value
13428: $hash{'foo'}='notbar';
13429:
13430: #adding a new value
13431: $hash{'bar'}='foo';
13432: &Apache::lonnet::cstore(\%hash);
13433:
13434: #retrieving the hash
13435: my %history=&Apache::lonnet::restore();
13436:
13437: #print the hash
13438: foreach my $key (sort(keys(%history))) {
13439: print("\%history{$key} = $history{$key}");
13440: }
13441:
13442: Will print out:
1.191 harris41 13443:
1.394 bowersj2 13444: %history{1:foo} = bar
13445: %history{1:keys} = foo:timestamp
13446: %history{1:timestamp} = 990455579
13447: %history{2:bar} = foo
13448: %history{2:foo} = notbar
13449: %history{2:keys} = foo:bar:timestamp
13450: %history{2:timestamp} = 990455580
13451: %history{bar} = foo
13452: %history{foo} = notbar
13453: %history{timestamp} = 990455580
13454: %history{version} = 2
13455:
13456: Note that the special hash entries C<keys>, C<version> and
13457: C<timestamp> were added to the hash. C<version> will be equal to the
13458: total number of versions of the data that have been stored. The
13459: C<timestamp> attribute will be the UNIX time the hash was
13460: stored. C<keys> is available in every historical section to list which
13461: keys were added or changed at a specific historical revision of a
13462: hash.
13463:
13464: B<Warning>: do not store the hash that restore returns directly. This
13465: will cause a mess since it will restore the historical keys as if the
13466: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13467:
1.394 bowersj2 13468: Calling convention:
1.191 harris41 13469:
1.1172.2.27 raeburn 13470: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13471: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13472:
1.394 bowersj2 13473: For more detailed information, see lonnet specific documentation.
1.191 harris41 13474:
1.394 bowersj2 13475: =head1 RETURN MESSAGES
1.191 harris41 13476:
1.394 bowersj2 13477: =over 4
1.191 harris41 13478:
1.394 bowersj2 13479: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13480:
1.394 bowersj2 13481: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13482: when the connection is brought back up
1.191 harris41 13483:
1.394 bowersj2 13484: =item * B<con_failed>: unable to contact remote host and unable to save message
13485: for later delivery
1.191 harris41 13486:
1.967 bisitz 13487: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13488:
1.394 bowersj2 13489: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13490: that was requested
1.191 harris41 13491:
1.243 albertel 13492: =back
1.191 harris41 13493:
1.243 albertel 13494: =head1 PUBLIC SUBROUTINES
1.191 harris41 13495:
1.243 albertel 13496: =head2 Session Environment Functions
1.191 harris41 13497:
1.243 albertel 13498: =over 4
1.191 harris41 13499:
1.394 bowersj2 13500: =item *
13501: X<appenv()>
1.949 raeburn 13502: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13503: the user envirnoment file, and will be restored for each access this
1.620 albertel 13504: user makes during this session, also modifies the %env for the current
1.949 raeburn 13505: process. Optional rolesarrayref - if defined contains a reference to an array
13506: of roles which are exempt from the restriction on modifying user.role entries
13507: in the user's environment.db and in %env.
1.191 harris41 13508:
13509: =item *
1.394 bowersj2 13510: X<delenv()>
1.987 raeburn 13511: B<delenv($delthis,$regexp)>: removes all items from the session
13512: environment file that begin with $delthis. If the
13513: optional second arg - $regexp - is true, $delthis is treated as a
13514: regular expression, otherwise \Q$delthis\E is used.
13515: The values are also deleted from the current processes %env.
1.191 harris41 13516:
1.795 albertel 13517: =item * get_env_multiple($name)
13518:
13519: gets $name from the %env hash, it seemlessly handles the cases where multiple
13520: values may be defined and end up as an array ref.
13521:
13522: returns an array of values
13523:
1.243 albertel 13524: =back
13525:
13526: =head2 User Information
1.191 harris41 13527:
1.243 albertel 13528: =over 4
1.191 harris41 13529:
13530: =item *
1.394 bowersj2 13531: X<queryauthenticate()>
13532: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13533: authentication scheme
13534:
13535: =item *
1.394 bowersj2 13536: X<authenticate()>
1.1073 raeburn 13537: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13538: authenticate user from domain's lib servers (first use the current
13539: one). C<$upass> should be the users password.
1.1073 raeburn 13540: $checkdefauth is optional (value is 1 if a check should be made to
13541: authenticate user using default authentication method, and allow
13542: account creation if username does not have account in the domain).
13543: $clientcancheckhost is optional (value is 1 if checking whether the
13544: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13545:
13546: =item *
1.394 bowersj2 13547: X<homeserver()>
13548: B<homeserver($uname,$udom)>: find the server which has
13549: the user's directory and files (there must be only one), this caches
13550: the answer, and also caches if there is a borken connection.
1.191 harris41 13551:
13552: =item *
1.394 bowersj2 13553: X<idget()>
13554: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13555: (IDs are a unique resource in a domain, there must be only 1 ID per
13556: username, and only 1 username per ID in a specific domain) (returns
13557: hash: id=>name,id=>name)
1.191 harris41 13558:
13559: =item *
1.394 bowersj2 13560: X<idrget()>
13561: B<idrget($udom,@unames)>: find the IDs behind a list of
13562: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13563:
13564: =item *
1.394 bowersj2 13565: X<idput()>
13566: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13567:
13568: =item *
1.394 bowersj2 13569: X<rolesinit()>
1.1169 droeschl 13570: B<rolesinit($udom,$username)>: get user privileges.
13571: returns user role, first access and timer interval hashes
1.243 albertel 13572:
13573: =item *
1.1171 droeschl 13574: X<privileged()>
13575: B<privileged($username,$domain)>: returns a true if user has a
13576: privileged and active role (i.e. su or dc), false otherwise.
13577:
13578: =item *
1.551 albertel 13579: X<getsection()>
13580: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13581: course $cname, return section name/number or '' for "not in course"
13582: and '-1' for "no section"
13583:
13584: =item *
1.394 bowersj2 13585: X<userenvironment()>
13586: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13587: passed in @what from the requested user's environment, returns a hash
13588:
1.858 raeburn 13589: =item *
13590: X<userlog_query()>
1.859 albertel 13591: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13592: activity.log file. %filters defines filters applied when parsing the
13593: log file. These can be start or end timestamps, or the type of action
13594: - log to look for Login or Logout events, check for Checkin or
13595: Checkout, role for role selection. The response is in the form
13596: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13597: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13598:
1.243 albertel 13599: =back
13600:
13601: =head2 User Roles
13602:
13603: =over 4
13604:
13605: =item *
13606:
1.1172.2.65 raeburn 13607: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13608: returns codes for allowed actions.
13609:
13610: The first argument is required, all others are optional.
13611:
13612: $priv is the privilege being checked.
13613: $uri contains additional information about what is being checked for access (e.g.,
13614: URL, course ID etc.).
13615: $symb is the unique resource instance identifier in a course; if needed,
13616: but not provided, it will be retrieved via a call to &symbread().
13617: $role is the role for which a priv is being checked (only used if priv is evb).
13618: $clientip is the user's IP address (only used when checking for access to portfolio
13619: files).
13620: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13621: prevents recursive calls to &allowed.
13622:
1.243 albertel 13623: F: full access
13624: U,I,K: authentication modes (cxx only)
13625: '': forbidden
13626: 1: user needs to choose course
13627: 2: browse allowed
1.766 albertel 13628: A: passphrase authentication needed
1.1172.2.65 raeburn 13629: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13630:
13631: =item *
13632:
1.1172.2.13 raeburn 13633: constructaccess($url,$setpriv) : check for access to construction space URL
13634:
13635: See if the owner domain and name in the URL match those in the
13636: expected environment. If so, return three element list
13637: ($ownername,$ownerdomain,$ownerhome).
13638:
13639: Otherwise return the null string.
13640:
13641: If second argument 'setpriv' is true, it assigns the privileges,
13642: and returns the same three element list, unless the owner has
13643: blocked "ad hoc" Domain Coordinator access to the Author Space,
13644: in which case the null string is returned.
13645:
13646: =item *
13647:
1.1172.2.84 raeburn 13648: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13649: define a custom role rolename set privileges in format of lonTabs/roles.tab
13650: for system, domain, and course level. $uname and $udom are optional (current
13651: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13652:
13653: =item *
13654:
1.988 raeburn 13655: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13656: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13657: $type is Course (default) or Community.
1.988 raeburn 13658: If $forcedefault evaluates to true, text returned will be default
13659: text for $type. Otherwise, if this is a course, the text returned
13660: will be a custom name for the role (if defined in the course's
13661: environment). If no custom name is defined the default is returned.
13662:
1.832 raeburn 13663: =item *
13664:
1.1172.2.23 raeburn 13665: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13666: All arguments are optional. Returns a hash of a roles, either for
13667: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13668: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13669: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13670: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13671: For each key, value is set to colon-separated start and end times for
13672: the role. If no username and domain are specified, will default to
1.934 raeburn 13673: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13674: of role statuses (active, future or previous), roles
13675: (e.g., cc,in, st etc.) and domains of the roles which can be used
13676: to restrict the list of roles reported. If no array ref is
13677: provided for types, will default to return only active roles.
1.834 albertel 13678:
1.1172.2.13 raeburn 13679: =item *
13680:
13681: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13682: user: $uname:$udom has a role in the course: $cdom_$cnum.
13683:
13684: Additional optional arguments are: $type (if role checking is to be restricted
13685: to certain user status types -- previous (expired roles), active (currently
13686: available roles) or future (roles available in the future), and
13687: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13688: have active Domain Coordinator role in course's domain or in additional
13689: domains (specified in 'Domains to check for privileged users' in course
13690: environment -- set via: Course Settings -> Classlists and staff listing).
13691:
13692: =item *
13693:
13694: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13695: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13696: $possdomains and $possroles are optional array refs -- to domains to check and
13697: roles to check. If $possdomains is not specified, a dump will be done of the
13698: users' roles.db to check for a dc or su role in any domain. This can be
13699: time consuming if &privileged is called repeatedly (e.g., when displaying a
13700: classlist), so in such cases, supplying a $possdomains array is preferred, as
13701: this then allows &privileged_by_domain() to be used, which caches the identity
13702: of privileged users, eliminating the need for repeated calls to &dump().
13703:
13704: =item *
13705:
13706: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13707: where the outer hash keys are domains specified in the $possdomains array ref,
13708: next inner hash keys are privileged roles specified in the $roles array ref,
13709: and the innermost hash contains key = value pairs for username:domain = end:start
13710: for active or future "privileged" users with that role in that domain. To avoid
13711: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13712: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13713:
1.243 albertel 13714: =back
13715:
13716: =head2 User Modification
13717:
13718: =over 4
13719:
13720: =item *
13721:
1.957 raeburn 13722: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13723: user for the level given by URL. Optional start and end dates (leave empty
13724: string or zero for "no date")
1.191 harris41 13725:
13726: =item *
13727:
1.243 albertel 13728: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13729: change a users, password, possible return values are: ok,
13730: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13731: refused
1.191 harris41 13732:
13733: =item *
13734:
1.243 albertel 13735: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13736:
13737: =item *
13738:
1.1058 raeburn 13739: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13740: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13741:
13742: will update user information (firstname,middlename,lastname,generation,
13743: permanentemail), and if forceid is true, student/employee ID also.
13744: A user's institutional affiliation(s) can also be updated.
13745: User information fields will not be overwritten with empty entries
13746: unless the field is included in the $candelete array reference.
13747: This array is included when a single user is modified via "Manage Users",
13748: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13749:
13750: =item *
13751:
1.286 matthew 13752: modifystudent
13753:
1.957 raeburn 13754: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13755: The course id is resolved based on the current user's environment.
13756: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13757: associated with a course.
13758:
1.297 matthew 13759: This call is essentially a wrapper for lonnet::modifyuser and
13760: lonnet::modify_student_enrollment
1.286 matthew 13761:
13762: Inputs:
13763:
13764: =over 4
13765:
1.957 raeburn 13766: =item B<$udom> Student's loncapa domain
1.286 matthew 13767:
1.957 raeburn 13768: =item B<$uname> Student's loncapa login name
1.286 matthew 13769:
1.964 bisitz 13770: =item B<$uid> Student/Employee ID
1.286 matthew 13771:
1.957 raeburn 13772: =item B<$umode> Student's authentication mode
1.286 matthew 13773:
1.957 raeburn 13774: =item B<$upass> Student's password
1.286 matthew 13775:
1.957 raeburn 13776: =item B<$first> Student's first name
1.286 matthew 13777:
1.957 raeburn 13778: =item B<$middle> Student's middle name
1.286 matthew 13779:
1.957 raeburn 13780: =item B<$last> Student's last name
1.286 matthew 13781:
1.957 raeburn 13782: =item B<$gene> Student's generation
1.286 matthew 13783:
1.957 raeburn 13784: =item B<$usec> Student's section in course
1.286 matthew 13785:
13786: =item B<$end> Unix time of the roles expiration
13787:
13788: =item B<$start> Unix time of the roles start date
13789:
13790: =item B<$forceid> If defined, allow $uid to be changed
13791:
13792: =item B<$desiredhome> server to use as home server for student
13793:
1.957 raeburn 13794: =item B<$email> Student's permanent e-mail address
13795:
13796: =item B<$type> Type of enrollment (auto or manual)
13797:
1.963 raeburn 13798: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13799:
13800: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13801:
1.963 raeburn 13802: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13803:
1.963 raeburn 13804: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13805:
1.1172.2.19 raeburn 13806: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13807:
13808: =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 13809:
1.286 matthew 13810: =back
1.297 matthew 13811:
13812: =item *
13813:
13814: modify_student_enrollment
13815:
1.1172.2.31 raeburn 13816: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13817: 'role.request.course' must be defined for this function to proceed.
13818:
13819: Inputs:
13820:
13821: =over 4
13822:
1.1172.2.31 raeburn 13823: =item $udom, student's domain
1.297 matthew 13824:
1.1172.2.31 raeburn 13825: =item $uname, student's name
1.297 matthew 13826:
1.1172.2.31 raeburn 13827: =item $uid, student's user id
1.297 matthew 13828:
1.1172.2.31 raeburn 13829: =item $first, student's first name
1.297 matthew 13830:
13831: =item $middle
13832:
13833: =item $last
13834:
13835: =item $gene
13836:
13837: =item $usec
13838:
13839: =item $end
13840:
13841: =item $start
13842:
1.957 raeburn 13843: =item $type
13844:
13845: =item $locktype
13846:
13847: =item $cid
13848:
13849: =item $selfenroll
13850:
13851: =item $context
13852:
1.1172.2.19 raeburn 13853: =item $credits, number of credits student will earn from this class
13854:
1.1172.2.76 raeburn 13855: =item $instsec, institutional course section code for student
13856:
1.297 matthew 13857: =back
13858:
1.191 harris41 13859:
13860: =item *
13861:
1.243 albertel 13862: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13863: custom role; give a custom role to a user for the level given by URL. Specify
13864: name and domain of role author, and role name
1.191 harris41 13865:
13866: =item *
13867:
1.243 albertel 13868: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13869:
13870: =item *
13871:
1.243 albertel 13872: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13873:
13874: =back
13875:
13876: =head2 Course Infomation
13877:
13878: =over 4
1.191 harris41 13879:
13880: =item *
13881:
1.1118 foxr 13882: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13883: specified course id, including all environment settings for the
13884: course, the description of the course will be in the hash under the
13885: key 'description'
1.191 harris41 13886:
1.1118 foxr 13887: $options is an optional parameter that if supplied is a hash reference that controls
13888: what how this function works. It has the following key/values:
13889:
13890: =over 4
13891:
13892: =item freshen_cache
13893:
13894: If defined, and the environment cache for the course is valid, it is
13895: returned in the returned hash.
13896:
13897: =item one_time
13898:
13899: If defined, the last cache time is set to _now_
13900:
13901: =item user
13902:
13903: If defined, the supplied username is used instead of the current user.
13904:
13905:
13906: =back
13907:
1.191 harris41 13908: =item *
13909:
1.624 albertel 13910: resdata($name,$domain,$type,@which) : request for current parameter
13911: setting for a specific $type, where $type is either 'course' or 'user',
13912: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13913: answers for 10 minutes.
1.243 albertel 13914:
1.877 foxr 13915: =item *
13916:
13917: get_courseresdata($courseid, $domain) : dump the entire course resource
13918: data base, returning a hash that is keyed by the resource name and has
13919: values that are the resource value. I believe that the timestamps and
13920: versions are also returned.
13921:
1.1172.2.31 raeburn 13922: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13923: supplemental content area. This routine caches the number of files for
13924: 10 minutes.
13925:
1.243 albertel 13926: =back
13927:
13928: =head2 Course Modification
13929:
13930: =over 4
1.191 harris41 13931:
13932: =item *
13933:
1.243 albertel 13934: writecoursepref($courseid,%prefs) : write preferences (environment
13935: database) for a course
1.191 harris41 13936:
13937: =item *
13938:
1.1011 raeburn 13939: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13940:
13941: =item *
13942:
1.1038 raeburn 13943: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13944:
1.1167 droeschl 13945: =item *
13946:
13947: is_course($courseid), is_course($cdom, $cnum)
13948:
13949: Accepts either a combined $courseid (in the form of domain_courseid) or the
13950: two component version $cdom, $cnum. It checks if the specified course exists.
13951:
13952: Returns:
13953: undef if the course doesn't exist, otherwise
13954: in scalar context the combined courseid.
13955: in list context the two components of the course identifier, domain and
13956: courseid.
13957:
1.243 albertel 13958: =back
13959:
13960: =head2 Resource Subroutines
13961:
13962: =over 4
1.191 harris41 13963:
13964: =item *
13965:
1.243 albertel 13966: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13967:
13968: =item *
13969:
1.243 albertel 13970: repcopy($filename) : subscribes to the requested file, and attempts to
13971: replicate from the owning library server, Might return
1.607 raeburn 13972: 'unavailable', 'not_found', 'forbidden', 'ok', or
13973: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13974: resource. Expects the local filesystem pathname
13975: (/home/httpd/html/res/....)
13976:
13977: =back
13978:
13979: =head2 Resource Information
13980:
13981: =over 4
1.191 harris41 13982:
13983: =item *
13984:
1.1172.2.28 raeburn 13985: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13986: and returns the value of a variety of different possible values,
13987: $varname should be a request string, and the other parameters can be
13988: used to specify who and what one is asking about. Ordinarily, $cid
13989: does not need to be specified, as it is retrived from
13990: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13991: within lonuserstate::loadmap() when initializing a course, before
13992: $env{'request.course.id'} has been set, so it needs to be provided
13993: in that one case.
1.243 albertel 13994:
13995: Possible values for $varname are environment.lastname (or other item
13996: from the envirnment hash), user.name (or someother aspect about the
13997: user), resource.0.maxtries (or some other part and parameter of a
13998: resource)
1.204 albertel 13999:
14000: =item *
14001:
1.243 albertel 14002: directcondval($number) : get current value of a condition; reads from a state
14003: string
1.204 albertel 14004:
14005: =item *
14006:
1.243 albertel 14007: condval($condidx) : value of condition index based on state
1.204 albertel 14008:
14009: =item *
14010:
1.243 albertel 14011: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14012: resource's metadata, $what should be either a specific key, or either
14013: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14014: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14015:
14016: this function automatically caches all requests
1.191 harris41 14017:
14018: =item *
14019:
1.243 albertel 14020: metadata_query($query,$custom,$customshow) : make a metadata query against the
14021: network of library servers; returns file handle of where SQL and regex results
14022: will be stored for query
1.191 harris41 14023:
14024: =item *
14025:
1.1172.2.66 raeburn 14026: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14027: return symbolic list entry (all arguments optional).
14028:
14029: Args: filename is the filename (including path) for the file for which a symb
14030: is required; donotrecurse, if true will prevent calls to allowed() being made
14031: to check access status if more than one resource was found in the bighash
14032: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14033: a randompick); ignorecachednull, if true will prevent a symb of '' being
14034: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14035: cause possible symbs to be checked to determine if they are subject to content
14036: blocking, if so they will not be included as possible symbs; possibles is a
14037: ref to a hash, which, as a side effect, will be populated with all possible
14038: symbs (content blocking not tested).
14039:
1.243 albertel 14040: returns the data handle
1.191 harris41 14041:
14042: =item *
14043:
1.1172.2.17 raeburn 14044: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14045: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14046: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14047: on failure, user must be in a course, as it assumes the existence of
14048: the course initial hash, and uses $env('request.course.id'}. The third
14049: arg is an optional reference to a scalar. If this arg is passed in the
14050: call to symbverify, it will be set to 1 if the symb has been set to be
14051: encrypted; otherwise it will be null.
1.243 albertel 14052:
1.191 harris41 14053: =item *
14054:
1.243 albertel 14055: symbclean($symb) : removes versions numbers from a symb, returns the
14056: cleaned symb
1.191 harris41 14057:
14058: =item *
14059:
1.243 albertel 14060: is_on_map($uri) : checks if the $uri is somewhere on the current
14061: course map, user must be in a course for it to work.
1.191 harris41 14062:
14063: =item *
14064:
1.243 albertel 14065: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14066:
14067: =item *
14068:
1.243 albertel 14069: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14070: a random seed, all arguments are optional, if they aren't sent it uses the
14071: environment to derive them. Note: if symb isn't sent and it can't get one
14072: from &symbread it will use the current time as its return value
1.191 harris41 14073:
14074: =item *
14075:
1.243 albertel 14076: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14077: unfakeable, receipt
1.191 harris41 14078:
14079: =item *
14080:
1.620 albertel 14081: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14082:
14083: =item *
14084:
1.243 albertel 14085: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14086:
14087: =item *
14088:
1.243 albertel 14089: 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 14090:
14091: =item *
14092:
1.243 albertel 14093: 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 14094:
14095: =item *
14096:
1.243 albertel 14097: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14098:
14099: =item *
14100:
1.243 albertel 14101: devalidate($symb) : devalidate temporary spreadsheet calculations,
14102: forcing spreadsheet to reevaluate the resource scores next time.
14103:
1.1172.2.13 raeburn 14104: =item *
14105:
14106: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14107: when viewing in course context.
14108:
14109: input: six args -- filename (decluttered), course number, course domain,
14110: url, symb (if registered) and group (if this is a
14111: group item -- e.g., bulletin board, group page etc.).
14112:
14113: output: array of five scalars --
14114: $cfile -- url for file editing if editable on current server
14115: $home -- homeserver of resource (i.e., for author if published,
14116: or course if uploaded.).
14117: $switchserver -- 1 if server switch will be needed.
14118: $forceedit -- 1 if icon/link should be to go to edit mode
14119: $forceview -- 1 if icon/link should be to go to view mode
14120:
14121: =item *
14122:
14123: is_course_upload($file,$cnum,$cdom)
14124:
14125: Used in course context to determine if current file was uploaded to
14126: the course (i.e., would be found in /userfiles/docs on the course's
14127: homeserver.
14128:
14129: input: 3 args -- filename (decluttered), course number and course domain.
14130: output: boolean -- 1 if file was uploaded.
14131:
1.243 albertel 14132: =back
14133:
14134: =head2 Storing/Retreiving Data
14135:
14136: =over 4
1.191 harris41 14137:
14138: =item *
14139:
1.1172.2.64 raeburn 14140: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14141: permanently for this url; hashref needs to be given and should be a \%hashname;
14142: the remaining args aren't required and if they aren't passed or are '' they will
14143: be derived from the env (with the exception of $laststore, which is an
14144: optional arg used when a user's submission is stored in grading).
14145: $laststore is $version=$timestamp, where $version is the most recent version
14146: number retrieved for the corresponding $symb in the $namespace db file, and
14147: $timestamp is the timestamp for that transaction (UNIX time).
14148: $laststore is currently only passed when cstore() is called by
14149: structuretags::finalize_storage().
1.191 harris41 14150:
14151: =item *
14152:
1.1172.2.64 raeburn 14153: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14154: but uses critical subroutine
1.191 harris41 14155:
14156: =item *
14157:
1.243 albertel 14158: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14159: all args are optional
1.191 harris41 14160:
14161: =item *
14162:
1.717 albertel 14163: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14164: dumps the complete (or key matching regexp) namespace into a hash
14165: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14166: normally &store()ed into
14167:
14168: $range should be either an integer '100' (give me the first 100
14169: matching records)
14170: or be two integers sperated by a - with no spaces
14171: '30-50' (give me the 30th through the 50th matching
14172: records)
14173:
14174:
14175: =item *
14176:
1.1172.2.59 raeburn 14177: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14178: replaces a &store() version of data with a replacement set of data
14179: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14180: reference. If $tolog is true, the transaction is logged in the courselog
14181: with an action=PUTSTORE.
1.717 albertel 14182:
14183: =item *
14184:
1.243 albertel 14185: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14186: works very similar to store/cstore, but all data is stored in a
14187: temporary location and can be reset using tmpreset, $storehash should
14188: be a hash reference, returns nothing on success
1.191 harris41 14189:
14190: =item *
14191:
1.243 albertel 14192: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14193: similar to restore, but all data is stored in a temporary location and
14194: can be reset using tmpreset. Returns a hash of values on success,
14195: error string otherwise.
1.191 harris41 14196:
14197: =item *
14198:
1.243 albertel 14199: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14200: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14201:
14202: =item *
14203:
1.243 albertel 14204: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14205: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14206:
14207: =item *
14208:
1.243 albertel 14209: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14210: namesp ($udom and $uname are optional)
1.191 harris41 14211:
14212: =item *
14213:
1.702 albertel 14214: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14215: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14216: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14217:
1.702 albertel 14218: $range should be either an integer '100' (give me the first 100
14219: matching records)
14220: or be two integers sperated by a - with no spaces
14221: '30-50' (give me the 30th through the 50th matching
14222: records)
1.449 matthew 14223: =item *
14224:
14225: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14226: $store can be a scalar, an array reference, or if the amount to be
14227: incremented is > 1, a hash reference.
14228:
14229: ($udom and $uname are optional)
1.191 harris41 14230:
14231: =item *
14232:
1.243 albertel 14233: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14234: ($udom and $uname are optional)
1.191 harris41 14235:
14236: =item *
14237:
1.243 albertel 14238: cput($namespace,$storehash,$udom,$uname) : critical put
14239: ($udom and $uname are optional)
1.191 harris41 14240:
14241: =item *
14242:
1.748 albertel 14243: newput($namespace,$storehash,$udom,$uname) :
14244:
14245: Attempts to store the items in the $storehash, but only if they don't
14246: currently exist, if this succeeds you can be certain that you have
14247: successfully created a new key value pair in the $namespace db.
14248:
14249:
14250: Args:
14251: $namespace: name of database to store values to
14252: $storehash: hashref to store to the db
14253: $udom: (optional) domain of user containing the db
14254: $uname: (optional) name of user caontaining the db
14255:
14256: Returns:
14257: 'ok' -> succeeded in storing all keys of $storehash
14258: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14259: least <key> already existed in the db (other
14260: requested keys may also already exist)
1.967 bisitz 14261: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14262: 'con_lost' -> unable to contact request server
14263: 'refused' -> action was not allowed by remote machine
14264:
14265:
14266: =item *
14267:
1.243 albertel 14268: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14269: reference filled in from namesp (encrypts the return communication)
14270: ($udom and $uname are optional)
1.191 harris41 14271:
14272: =item *
14273:
1.243 albertel 14274: log($udom,$name,$home,$message) : write to permanent log for user; use
14275: critical subroutine
14276:
1.806 raeburn 14277: =item *
14278:
1.860 raeburn 14279: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14280: array reference filled in from namespace found in domain level on either
14281: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14282:
14283: =item *
14284:
1.860 raeburn 14285: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14286: domain level either on specified domain server ($uhome) or primary domain
14287: server ($udom and $uhome are optional)
1.806 raeburn 14288:
1.943 raeburn 14289: =item *
14290:
1.1172.2.35 raeburn 14291: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14292: for: authentication, language, quotas, timezone, date locale, and portal URL in
14293: the target domain.
14294:
14295: May also include additional key => value pairs for the following groups:
14296:
14297: =over
14298:
14299: =item
14300: disk quotas (MB allocated by default to portfolios and authoring spaces).
14301:
14302: =over
14303:
14304: =item defaultquota, authorquota
14305:
14306: =back
14307:
14308: =item
14309: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14310: portfolio for users).
14311:
14312: =over
14313:
14314: =item
14315: aboutme, blog, webdav, portfolio
14316:
14317: =back
14318:
14319: =item
14320: requestcourses: ability to request courses, and how requests are processed.
14321:
14322: =over
14323:
14324: =item
1.1172.2.37 raeburn 14325: official, unofficial, community, textbook
1.1172.2.35 raeburn 14326:
14327: =back
14328:
14329: =item
14330: inststatus: types of institutional affiliation, and order in which they are displayed.
14331:
14332: =over
14333:
14334: =item
1.1172.2.44 raeburn 14335: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14336:
14337: =back
14338:
14339: =item
14340: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14341: for course's uploaded content.
14342:
14343: =over
14344:
14345: =item
1.1172.2.68 raeburn 14346: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14347: communityquota, textbookquota
1.1172.2.35 raeburn 14348:
14349: =back
14350:
14351: =item
14352: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14353: on your servers.
14354:
14355: =over
14356:
14357: =item
14358: remotesessions, hostedsessions
14359:
14360: =back
14361:
14362: =back
14363:
14364: In cases where a domain coordinator has never used the "Set Domain Configuration"
14365: utility to create a configuration.db file on a domain's primary library server
14366: only the following domain defaults: auth_def, auth_arg_def, lang_def
14367: -- corresponding values are authentication type (internal, krb4, krb5,
14368: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14369: will be available. Values are retrieved from cache (if current), unless the
14370: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14371: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14372:
14373: Typical usage:
1.943 raeburn 14374:
1.1172.2.35 raeburn 14375: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14376:
1.243 albertel 14377: =back
14378:
14379: =head2 Network Status Functions
14380:
14381: =over 4
1.191 harris41 14382:
14383: =item *
14384:
1.1137 raeburn 14385: dirlist() : return directory list based on URI (first arg).
14386:
14387: Inputs: 1 required, 5 optional.
14388:
14389: =over
14390:
14391: =item
14392: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14393:
14394: =item
14395: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14396:
14397: =item
14398: $username - username of user/course to be listed. Extracted from $uri if absent.
14399:
14400: =item
14401: $getpropath - boolean: 1 if prepend path using &propath().
14402:
14403: =item
14404: $getuserdir - boolean: 1 if prepend path for "userfiles".
14405:
14406: =item
14407: $alternateRoot - path to prepend in place of path from $uri.
14408:
14409: =back
14410:
14411: Returns: Array of up to two items.
14412:
14413: =over
14414:
14415: a reference to an array of files/subdirectories
14416:
14417: =over
14418:
14419: Each element in the array of files/subdirectories is a & separated list of
14420: item name and the result of running stat on the item. If dirlist was requested
14421: for a file instead of a directory, the item name will be ''. For a directory
14422: listing, if the item is a metadata file, the element will end &N&M
14423: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14424: default copyright set (1).
14425:
14426: =back
14427:
14428: a scalar containing error condition (if encountered).
14429:
14430: =over
14431:
14432: =item
14433: no_host (no homeserver identified for $username:$domain).
14434:
14435: =item
14436: no_such_host (server contacted for listing not identified as valid host).
14437:
14438: =item
14439: con_lost (connection to remote server failed).
14440:
14441: =item
14442: refused (invalid $username:$domain received on lond side).
14443:
14444: =item
14445: no_such_dir (directory at specified path on lond side does not exist).
14446:
14447: =item
14448: empty (directory at specified path on lond side is empty).
14449:
14450: =over
14451:
14452: This is currently not encountered because the &ls3, &ls2,
14453: &ls (_handler) routines on the lond side do not filter out
14454: . and .. from a directory listing.
14455:
14456: =back
14457:
14458: =back
14459:
14460: =back
1.191 harris41 14461:
14462: =item *
14463:
1.243 albertel 14464: spareserver() : find server with least workload from spare.tab
14465:
1.986 foxr 14466:
14467: =item *
14468:
14469: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14470: if there is no corresponding loncapa host.
14471:
1.243 albertel 14472: =back
14473:
1.986 foxr 14474:
1.243 albertel 14475: =head2 Apache Request
14476:
14477: =over 4
1.191 harris41 14478:
14479: =item *
14480:
1.243 albertel 14481: ssi($url,%hash) : server side include, does a complete request cycle on url to
14482: localhost, posts hash
14483:
14484: =back
14485:
14486: =head2 Data to String to Data
14487:
14488: =over 4
1.191 harris41 14489:
14490: =item *
14491:
1.243 albertel 14492: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14493: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14494:
14495: =item *
14496:
1.243 albertel 14497: hashref2str($hashref) : convert a hashref into a string complete with
14498: escaping and '=' and '&' separators, supports elements that are
14499: arrayrefs and hashrefs
1.191 harris41 14500:
14501: =item *
14502:
1.243 albertel 14503: arrayref2str($arrayref) : convert an arrayref into a string complete
14504: with escaping and '&' separators, supports elements that are arrayrefs
14505: and hashrefs
1.191 harris41 14506:
14507: =item *
14508:
1.243 albertel 14509: str2hash($string) : convert string to hash using unescaping and
14510: splitting on '=' and '&', supports elements that are arrayrefs and
14511: hashrefs
1.191 harris41 14512:
14513: =item *
14514:
1.243 albertel 14515: str2array($string) : convert string to hash using unescaping and
14516: splitting on '&', supports elements that are arrayrefs and hashrefs
14517:
14518: =back
14519:
14520: =head2 Logging Routines
14521:
14522:
14523: These routines allow one to make log messages in the lonnet.log and
14524: lonnet.perm logfiles.
1.191 harris41 14525:
1.1119 foxr 14526: =over 4
14527:
1.191 harris41 14528: =item *
14529:
1.243 albertel 14530: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14531:
14532: =item *
14533:
1.243 albertel 14534: logthis() : append message to the normal lonnet.log file, it gets
14535: preiodically rolled over and deleted.
1.191 harris41 14536:
14537: =item *
14538:
1.243 albertel 14539: logperm() : append a permanent message to lonnet.perm.log, this log
14540: file never gets deleted by any automated portion of the system, only
14541: messages of critical importance should go in here.
14542:
1.1119 foxr 14543:
1.243 albertel 14544: =back
14545:
14546: =head2 General File Helper Routines
14547:
14548: =over 4
1.191 harris41 14549:
14550: =item *
14551:
1.481 raeburn 14552: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14553: (a) files in /uploaded
14554: (i) If a local copy of the file exists -
14555: compares modification date of local copy with last-modified date for
14556: definitive version stored on home server for course. If local copy is
14557: stale, requests a new version from the home server and stores it.
14558: If the original has been removed from the home server, then local copy
14559: is unlinked.
14560: (ii) If local copy does not exist -
14561: requests the file from the home server and stores it.
14562:
14563: If $caller is 'uploadrep':
14564: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14565: for request for files originally uploaded via DOCS.
14566: - returns 'ok' if fresh local copy now available, -1 otherwise.
14567:
14568: Otherwise:
14569: This indicates a call from the content generation phase of the request.
14570: - returns the entire contents of the file or -1.
14571:
14572: (b) files in /res
14573: - returns the entire contents of a file or -1;
14574: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14575:
1.712 albertel 14576:
14577: =item *
14578:
14579: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14580: reference
14581:
14582: returns either a stat() list of data about the file or an empty list
14583: if the file doesn't exist or couldn't find out about it (connection
14584: problems or user unknown)
14585:
1.191 harris41 14586: =item *
14587:
1.243 albertel 14588: filelocation($dir,$file) : returns file system location of a file
14589: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14590: directory that relative $file lookups are to looked in ($dir of /a/dir
14591: and a file of ../bob will become /a/bob)
1.191 harris41 14592:
14593: =item *
14594:
14595: hreflocation($dir,$file) : returns file system location or a URL; same as
14596: filelocation except for hrefs
14597:
14598: =item *
14599:
1.1172.2.49 raeburn 14600: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14601: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14602:
1.243 albertel 14603: =back
14604:
1.608 albertel 14605: =head2 Usererfile file routines (/uploaded*)
14606:
14607: =over 4
14608:
14609: =item *
14610:
14611: userfileupload(): main rotine for putting a file in a user or course's
14612: filespace, arguments are,
14613:
1.620 albertel 14614: formname - required - this is the name of the element in $env where the
1.608 albertel 14615: filename, and the contents of the file to create/modifed exist
1.620 albertel 14616: the filename is in $env{'form.'.$formname.'.filename'} and the
14617: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14618: context - if coursedoc, store the file in the course of the active role
14619: of the current user;
14620: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14621: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14622: subdir - required - subdirectory to put the file in under ../userfiles/
14623: if undefined, it will be placed in "unknown"
14624:
14625: (This routine calls clean_filename() to remove any dangerous
14626: characters from the filename, and then calls finuserfileupload() to
14627: complete the transaction)
14628:
14629: returns either the url of the uploaded file (/uploaded/....) if successful
14630: and /adm/notfound.html if unsuccessful
14631:
14632: =item *
14633:
14634: clean_filename(): routine for cleaing a filename up for storage in
14635: userfile space, argument is:
14636:
14637: filename - proposed filename
14638:
14639: returns: the new clean filename
14640:
14641: =item *
14642:
1.1090 raeburn 14643: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14644: userspace, probably shouldn't be called directly
14645:
14646: docuname: username or courseid of destination for the file
14647: docudom: domain of user/course of destination for the file
14648: formname: same as for userfileupload()
1.1090 raeburn 14649: fname: filename (including subdirectories) for the file
14650: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14651: allfiles: reference to hash used to store objects found by parser
14652: codebase: reference to hash used for codebases of java objects found by parser
14653: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14654: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14655: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14656: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14657: context: if 'overwrite', will move the uploaded file from its temporary location to
14658: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14659: mimetype: reference to scalar to accommodate mime type determined
14660: from File::MMagic if $parser = parse.
1.608 albertel 14661:
14662: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14663: and /adm/notfound.html if unsuccessful (or an error message if context
14664: was 'overwrite').
14665:
1.608 albertel 14666:
14667: =item *
14668:
14669: renameuserfile(): renames an existing userfile to a new name
14670:
14671: Args:
14672: docuname: username or courseid of destination for the file
14673: docudom: domain of user/course of destination for the file
14674: old: current file name (including any subdirs under userfiles)
14675: new: desired file name (including any subdirs under userfiles)
14676:
14677: =item *
14678:
14679: mkdiruserfile(): creates a directory is a userfiles dir
14680:
14681: Args:
14682: docuname: username or courseid of destination for the file
14683: docudom: domain of user/course of destination for the file
14684: dir: dir to create (including any subdirs under userfiles)
14685:
14686: =item *
14687:
14688: removeuserfile(): removes a file that exists in userfiles
14689:
14690: Args:
14691: docuname: username or courseid of destination for the file
14692: docudom: domain of user/course of destination for the file
14693: fname: filname to delete (including any subdirs under userfiles)
14694:
14695: =item *
14696:
14697: removeuploadedurl(): convience function for removeuserfile()
14698:
14699: Args:
14700: url: a full /uploaded/... url to delete
14701:
1.747 albertel 14702: =item *
14703:
14704: get_portfile_permissions():
14705: Args:
14706: domain: domain of user or course contain the portfolio files
14707: user: name of user or num of course contain the portfolio files
14708: Returns:
14709: hashref of a dump of the proper file_permissions.db
14710:
14711:
14712: =item *
14713:
14714: get_access_controls():
14715:
14716: Args:
14717: current_permissions: the hash ref returned from get_portfile_permissions()
14718: group: (optional) the group you want the files associated with
14719: file: (optional) the file you want access info on
14720:
14721: Returns:
1.749 raeburn 14722: a hash (keys are file names) of hashes containing
14723: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14724: values are XML containing access control settings (see below)
1.747 albertel 14725:
14726: Internal notes:
14727:
1.749 raeburn 14728: access controls are stored in file_permissions.db as key=value pairs.
14729: key -> path to file/file_name\0uniqueID:scope_end_start
14730: where scope -> public,guest,course,group,domains or users.
14731: end -> UNIX time for end of access (0 -> no end date)
14732: start -> UNIX time for start of access
14733:
14734: value -> XML description of access control
14735: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14736: <start></start>
14737: <end></end>
14738:
14739: <password></password> for scope type = guest
14740:
14741: <domain></domain> for scope type = course or group
14742: <number></number>
14743: <roles id="">
14744: <role></role>
14745: <access></access>
14746: <section></section>
14747: <group></group>
14748: </roles>
14749:
14750: <dom></dom> for scope type = domains
14751:
14752: <users> for scope type = users
14753: <user>
14754: <uname></uname>
14755: <udom></udom>
14756: </user>
14757: </users>
14758: </scope>
14759:
14760: Access data is also aggregated for each file in an additional key=value pair:
14761: key -> path to file/file_name\0accesscontrol
14762: value -> reference to hash
14763: hash contains key = value pairs
14764: where key = uniqueID:scope_end_start
14765: value = UNIX time record was last updated
14766:
14767: Used to improve speed of look-ups of access controls for each file.
14768:
14769: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14770:
1.1172.2.13 raeburn 14771: =item *
14772:
1.749 raeburn 14773: modify_access_controls():
14774:
14775: Modifies access controls for a portfolio file
14776: Args
14777: 1. file name
14778: 2. reference to hash of required changes,
14779: 3. domain
14780: 4. username
14781: where domain,username are the domain of the portfolio owner
14782: (either a user or a course)
14783:
14784: Returns:
14785: 1. result of additions or updates ('ok' or 'error', with error message).
14786: 2. result of deletions ('ok' or 'error', with error message).
14787: 3. reference to hash of any new or updated access controls.
14788: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14789: key = integer (inbound ID)
1.1172.2.13 raeburn 14790: value = uniqueID
14791:
14792: =item *
14793:
14794: get_timebased_id():
14795:
14796: Attempts to get a unique timestamp-based suffix for use with items added to a
14797: course via the Course Editor (e.g., folders, composite pages,
14798: group bulletin boards).
14799:
14800: Args: (first three required; six others optional)
14801:
14802: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14803: docssequence, or name of group
14804:
14805: 2. keyid (alphanumeric): name of temporary locking key in hash,
14806: e.g., num, boardids
14807:
14808: 3. namespace: name of gdbm file used to store suffixes already assigned;
14809: file will be named nohist_namespace.db
14810:
14811: 4. cdom: domain of course; default is current course domain from %env
14812:
14813: 5. cnum: course number; default is current course number from %env
14814:
14815: 6. idtype: set to concat if an additional digit is to be appended to the
14816: unix timestamp to form the suffix, if the plain timestamp is already
14817: in use. Default is to not do this, but simply increment the unix
14818: timestamp by 1 until a unique key is obtained.
14819:
14820: 7. who: holder of locking key; defaults to user:domain for user.
14821:
14822: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14823: retrying); default is 3.
14824:
14825: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14826:
14827: Returns:
14828:
14829: 1. suffix obtained (numeric)
14830:
14831: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14832:
14833: 3. error: contains (localized) error message if an error occurred.
14834:
1.747 albertel 14835:
1.608 albertel 14836: =back
14837:
1.243 albertel 14838: =head2 HTTP Helper Routines
14839:
14840: =over 4
14841:
1.191 harris41 14842: =item *
14843:
14844: escape() : unpack non-word characters into CGI-compatible hex codes
14845:
14846: =item *
14847:
14848: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14849:
1.243 albertel 14850: =back
14851:
14852: =head1 PRIVATE SUBROUTINES
14853:
14854: =head2 Underlying communication routines (Shouldn't call)
14855:
14856: =over 4
14857:
14858: =item *
14859:
14860: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14861:
14862: =item *
14863:
14864: reply() : uses subreply to send a message to remote machine, logs all failures
14865:
14866: =item *
14867:
14868: critical() : passes a critical message to another server; if cannot
14869: get through then place message in connection buffer directory and
14870: returns con_delayed, if incapable of saving message, returns
14871: con_failed
14872:
14873: =item *
14874:
14875: reconlonc() : tries to reconnect lonc client processes.
14876:
14877: =back
14878:
14879: =head2 Resource Access Logging
14880:
14881: =over 4
14882:
14883: =item *
14884:
14885: flushcourselogs() : flush (save) buffer logs and access logs
14886:
14887: =item *
14888:
14889: courselog($what) : save message for course in hash
14890:
14891: =item *
14892:
14893: courseacclog($what) : save message for course using &courselog(). Perform
14894: special processing for specific resource types (problems, exams, quizzes, etc).
14895:
1.191 harris41 14896: =item *
14897:
14898: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14899: as a PerlChildExitHandler
1.243 albertel 14900:
14901: =back
14902:
14903: =head2 Other
14904:
14905: =over 4
14906:
14907: =item *
14908:
14909: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14910:
14911: =back
14912:
14913: =cut
1.877 foxr 14914:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>