Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.82
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.82! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.81 2016/09/18 14:37:57 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.36 raeburn 604: my ($r,$name,$userhashref) = @_;
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.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 847: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
848: $try_server));
1.1123 raeburn 849: ($spare_server, $lowest_load) =
850: &compare_server_load($try_server, $spare_server, $lowest_load);
851: }
1.1083 raeburn 852: }
1.784 albertel 853:
1.1123 raeburn 854: my $found_server = ($spare_server ne '' && $lowest_load < 100);
855:
856: if (!$found_server) {
857: if (ref($spareshash->{'default'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,
860: $remotesessions,$try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
1.1172.2.41 raeburn 884: my ($try_server, $spare_server, $lowest_load, $required) = @_;
885:
886: if ($required) {
887: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
888: my $remoterev = &get_server_loncaparev(undef,$try_server);
889: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
890: if (($major eq '' && $minor eq '') ||
891: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
892: return ($spare_server,$lowest_load);
893: }
894: }
1.784 albertel 895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1172.2.47 raeburn 955: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1172.2.47 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
960: if ($skiploadbal) {
961: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
962: unless (defined($cached)) {
963: my $cachetime = 60*60*24;
964: my %domconfig =
965: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
966: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
967: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
968: $cachetime);
969: }
970: }
971: }
1.1076 raeburn 972: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 973: my $loginvia;
1.1172.2.47 raeburn 974: if ($skiploadbal) {
975: if (ref($balancers) eq 'HASH') {
976: next if (exists($balancers->{$lonhost}));
977: }
978: }
1.1115 raeburn 979: if ($checkloginvia) {
980: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 981: if ($loginvia) {
982: my ($server,$path) = split(/:/,$loginvia);
983: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 984: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 985: if ($login_host eq $server) {
986: $portal_path = $path;
1.1151 raeburn 987: $isredirect = 1;
1.1116 raeburn 988: }
989: } else {
990: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 992: if ($login_host eq $lonhost) {
993: $portal_path = '';
1.1151 raeburn 994: $isredirect = '';
1.1116 raeburn 995: }
996: }
997: } else {
1.1076 raeburn 998: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 999: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1000: }
1001: }
1002: if ($login_host ne '') {
1.1116 raeburn 1003: $hostname = &hostname($login_host);
1.1076 raeburn 1004: }
1.1151 raeburn 1005: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1006: }
1007:
1.202 matthew 1008: # --------------------------------------------- Try to change a user's password
1009:
1010: sub changepass {
1.799 raeburn 1011: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1012: $currentpass = &escape($currentpass);
1013: $newpass = &escape($newpass);
1.1030 raeburn 1014: my $lonhost = $perlvar{'lonHostID'};
1015: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1016: $server);
1017: if (! $answer) {
1018: &logthis("No reply on password change request to $server ".
1019: "by $uname in domain $udom.");
1020: } elsif ($answer =~ "^ok") {
1021: &logthis("$uname in $udom successfully changed their password ".
1022: "on $server.");
1023: } elsif ($answer =~ "^pwchange_failure") {
1024: &logthis("$uname in $udom was unable to change their password ".
1025: "on $server. The action was blocked by either lcpasswd ".
1026: "or pwchange");
1027: } elsif ($answer =~ "^non_authorized") {
1028: &logthis("$uname in $udom did not get their password correct when ".
1029: "attempting to change it on $server.");
1030: } elsif ($answer =~ "^auth_mode_error") {
1031: &logthis("$uname in $udom attempted to change their password despite ".
1032: "not being locally or internally authenticated on $server.");
1033: } elsif ($answer =~ "^unknown_user") {
1034: &logthis("$uname in $udom attempted to change their password ".
1035: "on $server but were unable to because $server is not ".
1036: "their home server.");
1037: } elsif ($answer =~ "^refused") {
1038: &logthis("$server refused to change $uname in $udom password because ".
1039: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1040: } elsif ($answer =~ "invalid_client") {
1041: &logthis("$server refused to change $uname in $udom password because ".
1042: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1043: }
1044: return $answer;
1.1 albertel 1045: }
1046:
1.169 harris41 1047: # ----------------------- Try to determine user's current authentication scheme
1048:
1049: sub queryauthenticate {
1050: my ($uname,$udom)=@_;
1.456 albertel 1051: my $uhome=&homeserver($uname,$udom);
1052: if (!$uhome) {
1053: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1054: return 'no_host';
1055: }
1056: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1057: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1059: }
1.456 albertel 1060: return $answer;
1.169 harris41 1061: }
1062:
1.1 albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1064:
1.1 albertel 1065: sub authenticate {
1.1073 raeburn 1066: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1067: $upass=&escape($upass);
1068: $uname= &LONCAPA::clean_username($uname);
1.836 www 1069: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1070: my $newhome;
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: # Maybe the machine was offline and only re-appeared again recently?
1073: &reconlonc();
1074: # One more
1.952 raeburn 1075: $uhome=&homeserver($uname,$udom,1);
1076: if (($uhome eq 'no_host') && $checkdefauth) {
1077: if (defined(&domain($udom,'primary'))) {
1078: $newhome=&domain($udom,'primary');
1079: }
1080: if ($newhome ne '') {
1081: $uhome = $newhome;
1082: }
1083: }
1.836 www 1084: if ((!$uhome) || ($uhome eq 'no_host')) {
1085: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1086: return 'no_host';
1087: }
1.1 albertel 1088: }
1.1073 raeburn 1089: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1090: if ($answer eq 'authorized') {
1.952 raeburn 1091: if ($newhome) {
1092: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1093: return 'no_account_on_host';
1094: } else {
1095: &logthis("User $uname at $udom authorized by $uhome");
1096: return $uhome;
1097: }
1.471 albertel 1098: }
1099: if ($answer eq 'non_authorized') {
1100: &logthis("User $uname at $udom rejected by $uhome");
1101: return 'no_host';
1.9 www 1102: }
1.471 albertel 1103: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1104: return 'no_host';
1105: }
1106:
1.1073 raeburn 1107: sub can_host_session {
1.1074 raeburn 1108: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1109: my $canhost = 1;
1.1074 raeburn 1110: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1111: if (ref($remotesessions) eq 'HASH') {
1112: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1113: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1114: $canhost = 0;
1115: } else {
1116: $canhost = 1;
1117: }
1118: }
1119: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1120: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1121: $canhost = 1;
1122: } else {
1123: $canhost = 0;
1124: }
1125: }
1126: if ($canhost) {
1127: if ($remotesessions->{'version'} ne '') {
1128: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1129: if ($reqmajor ne '' && $reqminor ne '') {
1130: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1131: my $major = $1;
1132: my $minor = $2;
1133: if (($major < $reqmajor ) ||
1134: (($major == $reqmajor) && ($minor < $reqminor))) {
1135: $canhost = 0;
1136: }
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: }
1144: if ($canhost) {
1145: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1146: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1147: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1148: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1151: $canhost = 0;
1152: } else {
1153: $canhost = 1;
1154: }
1155: }
1156: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1157: if (($uint_dom ne '') &&
1158: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1159: $canhost = 1;
1160: } else {
1161: $canhost = 0;
1162: }
1163: }
1164: }
1165: }
1166: return $canhost;
1167: }
1168:
1.1083 raeburn 1169: sub spare_can_host {
1170: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1171: my $canhost=1;
1.1172.2.62 raeburn 1172: my $try_server_hostname = &hostname($try_server);
1173: my $serverhomeID = &get_server_homeID($try_server_hostname);
1174: my $serverhomedom = &host_domain($serverhomeID);
1175: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1176: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1177: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1178: $canhost = 0;
1179: }
1180: }
1181: if (($canhost) && ($uint_dom)) {
1182: my @intdoms;
1183: my $internet_names = &get_internet_names($try_server);
1184: if (ref($internet_names) eq 'ARRAY') {
1185: @intdoms = @{$internet_names};
1186: }
1187: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1188: my $remoterev = &get_server_loncaparev(undef,$try_server);
1189: $canhost = &can_host_session($udom,$try_server,$remoterev,
1190: $remotesessions,
1191: $defdomdefaults{'hostedsessions'});
1192: }
1.1083 raeburn 1193: }
1194: return $canhost;
1195: }
1196:
1.1123 raeburn 1197: sub this_host_spares {
1198: my ($dom) = @_;
1.1126 raeburn 1199: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1200: my @hosts = ¤t_machine_ids();
1201: foreach my $lonhost (@hosts) {
1202: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1203: $dom_in_use = $dom;
1204: $lonhost_in_use = $lonhost;
1.1123 raeburn 1205: last;
1206: }
1207: }
1.1126 raeburn 1208: if ($dom_in_use ne '') {
1209: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1210: }
1211: if (ref($result) ne 'HASH') {
1212: $lonhost_in_use = $perlvar{'lonHostID'};
1213: $dom_in_use = &host_domain($lonhost_in_use);
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: if (ref($result) ne 'HASH') {
1216: $result = \%spareid;
1217: }
1218: }
1219: return $result;
1220: }
1221:
1222: sub spares_for_offload {
1223: my ($dom_in_use,$lonhost_in_use) = @_;
1224: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1225: if (defined($cached)) {
1226: return $result;
1227: } else {
1.1126 raeburn 1228: my $cachetime = 60*60*24;
1229: my %domconfig =
1230: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1231: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1232: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1234: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1235: }
1236: }
1237: }
1238: }
1.1126 raeburn 1239: return;
1.1123 raeburn 1240: }
1241:
1.1129 raeburn 1242: sub get_lonbalancer_config {
1243: my ($servers) = @_;
1244: my ($currbalancer,$currtargets);
1245: if (ref($servers) eq 'HASH') {
1246: foreach my $server (keys(%{$servers})) {
1247: my %what = (
1248: spareid => 1,
1249: perlvar => 1,
1250: );
1251: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1252: if ($result eq 'ok') {
1253: if (ref($returnhash) eq 'HASH') {
1254: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1255: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1256: $currbalancer = $server;
1257: $currtargets = {};
1258: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1259: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1260: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1261: }
1262: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1263: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1264: }
1265: }
1266: last;
1267: }
1268: }
1269: }
1270: }
1271: }
1272: }
1273: return ($currbalancer,$currtargets);
1274: }
1275:
1276: sub check_loadbalancing {
1277: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1278: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1279: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1280: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1281: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1282: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1283: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1284: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1285: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1286: my $domneedscache;
1.1129 raeburn 1287: my $cachetime = 60*60*24;
1288:
1289: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1290: $dom_in_use = $udom;
1291: $homeintdom = 1;
1292: } else {
1293: $dom_in_use = $serverhomedom;
1294: }
1295: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1296: unless (defined($cached)) {
1297: my %domconfig =
1298: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1299: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1300: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1301: } else {
1302: $domneedscache = $dom_in_use;
1.1129 raeburn 1303: }
1304: }
1305: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1306: ($is_balancer,$currtargets,$currrules) =
1307: &check_balancer_result($result,@hosts);
1.1129 raeburn 1308: if ($is_balancer) {
1309: if (ref($currrules) eq 'HASH') {
1310: if ($homeintdom) {
1311: if ($uname ne '') {
1312: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1313: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1314: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1315: $rule_in_effect = $currrules->{'_LC_author'};
1316: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1317: $rule_in_effect = $currrules->{'_LC_adv'}
1318: }
1319: }
1320: if ($rule_in_effect eq '') {
1321: my %userenv = &userenvironment($udom,$uname,'inststatus');
1322: if ($userenv{'inststatus'} ne '') {
1323: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1324: my ($othertitle,$usertypes,$types) =
1325: &Apache::loncommon::sorted_inst_types($udom);
1326: if (ref($types) eq 'ARRAY') {
1327: foreach my $type (@{$types}) {
1328: if (grep(/^\Q$type\E$/,@statuses)) {
1329: if (exists($currrules->{$type})) {
1330: $rule_in_effect = $currrules->{$type};
1331: }
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: }
1341: } else {
1342: if (exists($currrules->{'default'})) {
1343: $rule_in_effect = $currrules->{'default'};
1344: }
1345: }
1346: } else {
1347: if ($currrules->{'_LC_external'} ne '') {
1348: $rule_in_effect = $currrules->{'_LC_external'};
1349: }
1350: }
1351: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1352: $uname,$udom);
1353: }
1354: }
1355: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1356: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1357: unless (defined($cached)) {
1358: my %domconfig =
1359: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1360: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1361: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1362: } else {
1363: $domneedscache = $serverhomedom;
1.1129 raeburn 1364: }
1365: }
1366: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1367: ($is_balancer,$currtargets,$currrules) =
1368: &check_balancer_result($result,@hosts);
1369: if ($is_balancer) {
1.1129 raeburn 1370: if (ref($currrules) eq 'HASH') {
1371: if ($currrules->{'_LC_internetdom'} ne '') {
1372: $rule_in_effect = $currrules->{'_LC_internetdom'};
1373: }
1374: }
1375: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1376: $uname,$udom);
1377: }
1378: } else {
1379: if ($perlvar{'lonBalancer'} eq 'yes') {
1380: $is_balancer = 1;
1381: $offloadto = &this_host_spares($dom_in_use);
1382: }
1.1172.2.75 raeburn 1383: unless (defined($cached)) {
1384: $domneedscache = $serverhomedom;
1385: }
1.1129 raeburn 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: }
1395: }
1396: if ($domneedscache) {
1397: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1398: }
1.1172.2.5 raeburn 1399: if ($is_balancer) {
1400: my $lowest_load = 30000;
1401: if (ref($offloadto) eq 'HASH') {
1402: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1403: foreach my $try_server (@{$offloadto->{'primary'}}) {
1404: ($otherserver,$lowest_load) =
1405: &compare_server_load($try_server,$otherserver,$lowest_load);
1406: }
1.1129 raeburn 1407: }
1.1172.2.5 raeburn 1408: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1409:
1.1172.2.5 raeburn 1410: if (!$found_server) {
1411: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1412: foreach my $try_server (@{$offloadto->{'default'}}) {
1413: ($otherserver,$lowest_load) =
1414: &compare_server_load($try_server,$otherserver,$lowest_load);
1415: }
1416: }
1417: }
1418: } elsif (ref($offloadto) eq 'ARRAY') {
1419: if (@{$offloadto} == 1) {
1420: $otherserver = $offloadto->[0];
1421: } elsif (@{$offloadto} > 1) {
1422: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1423: ($otherserver,$lowest_load) =
1424: &compare_server_load($try_server,$otherserver,$lowest_load);
1425: }
1426: }
1427: }
1.1172.2.5 raeburn 1428: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1429: $is_balancer = 0;
1430: if ($uname ne '' && $udom ne '') {
1431: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1432:
1433: &appenv({'user.loadbalexempt' => $lonhost,
1434: 'user.loadbalcheck.time' => time});
1435: }
1.1129 raeburn 1436: }
1437: }
1438: }
1439: return ($is_balancer,$otherserver);
1440: }
1441:
1.1172.2.12 raeburn 1442: sub check_balancer_result {
1443: my ($result,@hosts) = @_;
1444: my ($is_balancer,$currtargets,$currrules);
1445: if (ref($result) eq 'HASH') {
1446: if ($result->{'lonhost'} ne '') {
1447: my $currbalancer = $result->{'lonhost'};
1448: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1449: $is_balancer = 1;
1450: $currtargets = $result->{'targets'};
1451: $currrules = $result->{'rules'};
1452: }
1453: } else {
1454: foreach my $key (keys(%{$result})) {
1455: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1456: (ref($result->{$key}) eq 'HASH')) {
1457: $is_balancer = 1;
1458: $currrules = $result->{$key}{'rules'};
1459: $currtargets = $result->{$key}{'targets'};
1460: last;
1461: }
1462: }
1463: }
1464: }
1465: return ($is_balancer,$currtargets,$currrules);
1466: }
1467:
1.1129 raeburn 1468: sub get_loadbalancer_targets {
1469: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1470: my $offloadto;
1.1172.2.4 raeburn 1471: if ($rule_in_effect eq 'none') {
1472: return [$perlvar{'lonHostID'}];
1473: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1474: $offloadto = $currtargets;
1475: } else {
1476: if ($rule_in_effect eq 'homeserver') {
1477: my $homeserver = &homeserver($uname,$udom);
1478: if ($homeserver ne 'no_host') {
1479: $offloadto = [$homeserver];
1480: }
1481: } elsif ($rule_in_effect eq 'externalbalancer') {
1482: my %domconfig =
1483: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1484: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1485: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1486: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1487: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1488: }
1489: }
1490: } else {
1.1172.2.7 raeburn 1491: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1492: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1493: if (&hostname($remotebalancer) ne '') {
1494: $offloadto = [$remotebalancer];
1495: }
1496: }
1497: } elsif (&hostname($rule_in_effect) ne '') {
1498: $offloadto = [$rule_in_effect];
1499: }
1500: }
1501: return $offloadto;
1502: }
1503:
1.1127 raeburn 1504: sub internet_dom_servers {
1505: my ($dom) = @_;
1506: my (%uniqservers,%servers);
1507: my $primaryserver = &hostname(&domain($dom,'primary'));
1508: my @machinedoms = &machine_domains($primaryserver);
1509: foreach my $mdom (@machinedoms) {
1510: my %currservers = %servers;
1511: my %server = &get_servers($mdom);
1512: %servers = (%currservers,%server);
1513: }
1514: my %by_hostname;
1515: foreach my $id (keys(%servers)) {
1516: push(@{$by_hostname{$servers{$id}}},$id);
1517: }
1518: foreach my $hostname (sort(keys(%by_hostname))) {
1519: if (@{$by_hostname{$hostname}} > 1) {
1520: my $match = 0;
1521: foreach my $id (@{$by_hostname{$hostname}}) {
1522: if (&host_domain($id) eq $dom) {
1523: $uniqservers{$id} = $hostname;
1524: $match = 1;
1525: }
1526: }
1527: unless ($match) {
1528: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1529: }
1530: } else {
1531: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1532: }
1533: }
1534: return %uniqservers;
1535: }
1536:
1.1 albertel 1537: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1538:
1.599 albertel 1539: my %homecache;
1.1 albertel 1540: sub homeserver {
1.230 stredwic 1541: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1542: my $index="$uname:$udom";
1.426 albertel 1543:
1.599 albertel 1544: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1545:
1546: my %servers = &get_servers($udom,'library');
1547: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1548: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1549: exists($badServerCache{$tryserver}));
1.841 albertel 1550:
1551: my $answer=reply("home:$udom:$uname",$tryserver);
1552: if ($answer eq 'found') {
1553: delete($badServerCache{$tryserver});
1554: return $homecache{$index}=$tryserver;
1555: } elsif ($answer eq 'no_host') {
1556: $badServerCache{$tryserver}=1;
1557: }
1.1 albertel 1558: }
1559: return 'no_host';
1.70 www 1560: }
1561:
1562: # ------------------------------------- Find the usernames behind a list of IDs
1563:
1564: sub idget {
1565: my ($udom,@ids)=@_;
1566: my %returnhash=();
1567:
1.841 albertel 1568: my %servers = &get_servers($udom,'library');
1569: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1570: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1571: $idlist=~tr/A-Z/a-z/;
1572: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1573: my @answer=();
1574: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1575: @answer=split(/\&/,$reply);
1576: } ;
1577: my $i;
1578: for ($i=0;$i<=$#ids;$i++) {
1579: if ($answer[$i]) {
1.1172.2.73 raeburn 1580: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1581: }
1582: }
1583: }
1.70 www 1584: return %returnhash;
1585: }
1586:
1587: # ------------------------------------- Find the IDs behind a list of usernames
1588:
1589: sub idrget {
1590: my ($udom,@unames)=@_;
1591: my %returnhash=();
1.800 albertel 1592: foreach my $uname (@unames) {
1593: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1594: }
1.70 www 1595: return %returnhash;
1596: }
1597:
1598: # ------------------------------- Store away a list of names and associated IDs
1599:
1600: sub idput {
1601: my ($udom,%ids)=@_;
1602: my %servers=();
1.800 albertel 1603: foreach my $uname (keys(%ids)) {
1604: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1605: my $uhom=&homeserver($uname,$udom);
1.70 www 1606: if ($uhom ne 'no_host') {
1.800 albertel 1607: my $id=&escape($ids{$uname});
1.70 www 1608: $id=~tr/A-Z/a-z/;
1.800 albertel 1609: my $esc_unam=&escape($uname);
1.70 www 1610: if ($servers{$uhom}) {
1.800 albertel 1611: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1612: } else {
1.800 albertel 1613: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1614: }
1615: }
1.191 harris41 1616: }
1.800 albertel 1617: foreach my $server (keys(%servers)) {
1618: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1619: }
1.344 www 1620: }
1621:
1.1172.2.30 raeburn 1622: # ---------------------------------------- Delete unwanted IDs from ids.db file
1623:
1624: sub iddel {
1625: my ($udom,$idshashref,$uhome)=@_;
1626: my %result=();
1627: unless (ref($idshashref) eq 'HASH') {
1628: return %result;
1629: }
1630: my %servers=();
1631: while (my ($id,$uname) = each(%{$idshashref})) {
1632: my $uhom;
1633: if ($uhome) {
1634: $uhom = $uhome;
1635: } else {
1636: $uhom=&homeserver($uname,$udom);
1637: }
1638: if ($uhom ne 'no_host') {
1639: if ($servers{$uhom}) {
1640: $servers{$uhom}.='&'.&escape($id);
1641: } else {
1642: $servers{$uhom}=&escape($id);
1643: }
1644: }
1645: }
1646: foreach my $server (keys(%servers)) {
1647: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1648: }
1649: return %result;
1650: }
1651:
1.1023 raeburn 1652: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1653: sub dump_dom {
1.1165 droeschl 1654: my ($namespace, $udom, $regexp) = @_;
1655:
1656: $udom ||= $env{'user.domain'};
1657:
1658: return () unless $udom;
1659:
1660: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1661: }
1662:
1.1023 raeburn 1663: # ------------------------------------------ get items from domain db files
1.806 raeburn 1664:
1665: sub get_dom {
1.860 raeburn 1666: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1667: return if ($udom eq 'public');
1.806 raeburn 1668: my $items='';
1669: foreach my $item (@$storearr) {
1670: $items.=&escape($item).'&';
1671: }
1672: $items=~s/\&$//;
1.860 raeburn 1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1675: return if ($udom eq 'public');
1.860 raeburn 1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: } else {
1.874 albertel 1679: undef($uhome);
1.860 raeburn 1680: }
1681: } else {
1682: if (!$uhome) {
1683: if (defined(&domain($udom,'primary'))) {
1684: $uhome=&domain($udom,'primary');
1685: }
1686: }
1687: }
1688: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1689: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1690: my %returnhash;
1.875 albertel 1691: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1692: return %returnhash;
1693: }
1.806 raeburn 1694: my @pairs=split(/\&/,$rep);
1695: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1696: return @pairs;
1697: }
1698: my $i=0;
1699: foreach my $item (@$storearr) {
1700: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1701: $i++;
1702: }
1703: return %returnhash;
1704: } else {
1.880 banghart 1705: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1706: }
1707: }
1708:
1709: # -------------------------------------------- put items in domain db files
1710:
1711: sub put_dom {
1.860 raeburn 1712: my ($namespace,$storehash,$udom,$uhome)=@_;
1713: if (!$udom) {
1714: $udom=$env{'user.domain'};
1715: if (defined(&domain($udom,'primary'))) {
1716: $uhome=&domain($udom,'primary');
1717: } else {
1.874 albertel 1718: undef($uhome);
1.860 raeburn 1719: }
1720: } else {
1721: if (!$uhome) {
1722: if (defined(&domain($udom,'primary'))) {
1723: $uhome=&domain($udom,'primary');
1724: }
1725: }
1726: }
1727: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1728: my $items='';
1729: foreach my $item (keys(%$storehash)) {
1730: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1731: }
1732: $items=~s/\&$//;
1733: return &reply("putdom:$udom:$namespace:$items",$uhome);
1734: } else {
1.860 raeburn 1735: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1736: }
1737: }
1738:
1.1023 raeburn 1739: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1740: sub newput_dom {
1.1023 raeburn 1741: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1742: my $result;
1743: if (!$udom) {
1744: $udom=$env{'user.domain'};
1745: }
1.1023 raeburn 1746: if ($udom) {
1747: my $uname = &get_domainconfiguser($udom);
1748: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1749: }
1750: return $result;
1751: }
1752:
1.1023 raeburn 1753: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1754: sub del_dom {
1.1023 raeburn 1755: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1756: if (ref($storearr) eq 'ARRAY') {
1757: if (!$udom) {
1758: $udom=$env{'user.domain'};
1759: }
1.1023 raeburn 1760: if ($udom) {
1761: my $uname = &get_domainconfiguser($udom);
1762: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1763: }
1764: }
1765: }
1766:
1.1023 raeburn 1767: # ----------------------------------construct domainconfig user for a domain
1768: sub get_domainconfiguser {
1769: my ($udom) = @_;
1770: return $udom.'-domainconfig';
1771: }
1772:
1.837 raeburn 1773: sub retrieve_inst_usertypes {
1774: my ($udom) = @_;
1775: my (%returnhash,@order);
1.989 raeburn 1776: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1777: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1778: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1779: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1780: } else {
1781: if (defined(&domain($udom,'primary'))) {
1782: my $uhome=&domain($udom,'primary');
1783: my $rep=&reply("inst_usertypes:$udom",$uhome);
1784: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1785: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1786: return (\%returnhash,\@order);
1787: }
1788: my ($hashitems,$orderitems) = split(/:/,$rep);
1789: my @pairs=split(/\&/,$hashitems);
1790: foreach my $item (@pairs) {
1791: my ($key,$value)=split(/=/,$item,2);
1792: $key = &unescape($key);
1793: next if ($key =~ /^error: 2 /);
1794: $returnhash{$key}=&thaw_unescape($value);
1795: }
1796: my @esc_order = split(/\&/,$orderitems);
1797: foreach my $item (@esc_order) {
1798: push(@order,&unescape($item));
1799: }
1800: } else {
1.1172.2.44 raeburn 1801: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1802: }
1.1172.2.44 raeburn 1803: return (\%returnhash,\@order);
1.837 raeburn 1804: }
1805: }
1806:
1.868 raeburn 1807: sub is_domainimage {
1808: my ($url) = @_;
1.1172.2.74 raeburn 1809: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1810: if (&domain($1) ne '') {
1811: return '1';
1812: }
1813: }
1814: return;
1815: }
1816:
1.899 raeburn 1817: sub inst_directory_query {
1818: my ($srch) = @_;
1819: my $udom = $srch->{'srchdomain'};
1820: my %results;
1821: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1822: my $outcome;
1.899 raeburn 1823: if ($homeserver ne '') {
1.904 albertel 1824: my $queryid=&reply("querysend:instdirsearch:".
1825: &escape($srch->{'srchby'}).':'.
1826: &escape($srch->{'srchterm'}).':'.
1827: &escape($srch->{'srchtype'}),$homeserver);
1828: my $host=&hostname($homeserver);
1829: if ($queryid !~/^\Q$host\E\_/) {
1830: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1831: return;
1832: }
1833: my $response = &get_query_reply($queryid);
1834: my $maxtries = 5;
1835: my $tries = 1;
1836: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1837: $response = &get_query_reply($queryid);
1838: $tries ++;
1839: }
1840:
1841: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1842: if ($response eq 'unavailable') {
1843: $outcome = $response;
1844: } else {
1845: $outcome = 'ok';
1846: my @matches = split(/\n/,$response);
1847: foreach my $match (@matches) {
1848: my ($key,$value) = split(/=/,$match);
1849: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1850: }
1.899 raeburn 1851: }
1852: }
1853: }
1.909 raeburn 1854: return ($outcome,%results);
1.899 raeburn 1855: }
1856:
1857: sub usersearch {
1858: my ($srch) = @_;
1859: my $dom = $srch->{'srchdomain'};
1860: my %results;
1861: my %libserv = &all_library();
1862: my $query = 'usersearch';
1863: foreach my $tryserver (keys(%libserv)) {
1864: if (&host_domain($tryserver) eq $dom) {
1865: my $host=&hostname($tryserver);
1866: my $queryid=
1.911 raeburn 1867: &reply("querysend:".&escape($query).':'.
1868: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1869: &escape($srch->{'srchtype'}).':'.
1870: &escape($srch->{'srchterm'}),$tryserver);
1871: if ($queryid !~/^\Q$host\E\_/) {
1872: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1873: next;
1.899 raeburn 1874: }
1875: my $reply = &get_query_reply($queryid);
1876: my $maxtries = 1;
1877: my $tries = 1;
1878: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1879: $reply = &get_query_reply($queryid);
1880: $tries ++;
1881: }
1882: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1883: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1884: } else {
1.911 raeburn 1885: my @matches;
1886: if ($reply =~ /\n/) {
1887: @matches = split(/\n/,$reply);
1888: } else {
1889: @matches = split(/\&/,$reply);
1890: }
1.899 raeburn 1891: foreach my $match (@matches) {
1892: my ($uname,$udom,%userhash);
1.911 raeburn 1893: foreach my $entry (split(/:/,$match)) {
1894: my ($key,$value) =
1895: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1896: $userhash{$key} = $value;
1897: if ($key eq 'username') {
1898: $uname = $value;
1899: } elsif ($key eq 'domain') {
1900: $udom = $value;
1.911 raeburn 1901: }
1.899 raeburn 1902: }
1903: $results{$uname.':'.$udom} = \%userhash;
1904: }
1905: }
1906: }
1907: }
1908: return %results;
1909: }
1910:
1.912 raeburn 1911: sub get_instuser {
1912: my ($udom,$uname,$id) = @_;
1913: my $homeserver = &domain($udom,'primary');
1914: my ($outcome,%results);
1915: if ($homeserver ne '') {
1916: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1917: &escape($id).':'.&escape($udom),$homeserver);
1918: my $host=&hostname($homeserver);
1919: if ($queryid !~/^\Q$host\E\_/) {
1920: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1921: return;
1922: }
1923: my $response = &get_query_reply($queryid);
1924: my $maxtries = 5;
1925: my $tries = 1;
1926: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1927: $response = &get_query_reply($queryid);
1928: $tries ++;
1929: }
1930: if (!&error($response) && $response ne 'refused') {
1931: if ($response eq 'unavailable') {
1932: $outcome = $response;
1933: } else {
1934: $outcome = 'ok';
1935: my @matches = split(/\n/,$response);
1936: foreach my $match (@matches) {
1937: my ($key,$value) = split(/=/,$match);
1938: $results{&unescape($key)} = &thaw_unescape($value);
1939: }
1940: }
1941: }
1942: }
1943: my %userinfo;
1944: if (ref($results{$uname}) eq 'HASH') {
1945: %userinfo = %{$results{$uname}};
1946: }
1947: return ($outcome,%userinfo);
1948: }
1949:
1.1172.2.69 raeburn 1950: sub get_multiple_instusers {
1951: my ($udom,$users,$caller) = @_;
1952: my ($outcome,$results);
1953: if (ref($users) eq 'HASH') {
1954: my $count = keys(%{$users});
1955: my $requested = &freeze_escape($users);
1956: my $homeserver = &domain($udom,'primary');
1957: if ($homeserver ne '') {
1958: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1959: my $host=&hostname($homeserver);
1960: if ($queryid !~/^\Q$host\E\_/) {
1961: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1962: ' for host: '.$homeserver.'in domain '.$udom);
1963: return ($outcome,$results);
1964: }
1965: my $response = &get_query_reply($queryid);
1966: my $maxtries = 5;
1967: if ($count > 100) {
1968: $maxtries = 1+int($count/20);
1969: }
1970: my $tries = 1;
1971: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1972: $response = &get_query_reply($queryid);
1973: $tries ++;
1974: }
1975: if ($response eq '') {
1976: $results = {};
1977: foreach my $key (keys(%{$users})) {
1978: my ($uname,$id);
1979: if ($caller eq 'id') {
1980: $id = $key;
1981: } else {
1982: $uname = $key;
1983: }
1984: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1985: $outcome = $resp;
1986: if ($resp eq 'ok') {
1987: %{$results} = (%{$results}, %info);
1988: } else {
1989: last;
1990: }
1991: }
1992: } elsif(!&error($response) && ($response ne 'refused')) {
1993: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
1994: $outcome = $response;
1995: } else {
1996: ($outcome,my $userdata) = split(/=/,$response,2);
1997: if ($outcome eq 'ok') {
1998: $results = &thaw_unescape($userdata);
1999: }
2000: }
2001: }
2002: }
2003: }
2004: return ($outcome,$results);
2005: }
2006:
1.912 raeburn 2007: sub inst_rulecheck {
1.923 raeburn 2008: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2009: my %returnhash;
2010: if ($udom ne '') {
2011: if (ref($rules) eq 'ARRAY') {
2012: @{$rules} = map {&escape($_);} (@{$rules});
2013: my $rulestr = join(':',@{$rules});
2014: my $homeserver=&domain($udom,'primary');
2015: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2016: my $response;
2017: if ($item eq 'username') {
2018: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2019: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2020: $homeserver));
1.923 raeburn 2021: } elsif ($item eq 'id') {
2022: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2023: ':'.&escape($id).':'.$rulestr,
2024: $homeserver));
1.945 raeburn 2025: } elsif ($item eq 'selfcreate') {
2026: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2027: &escape($udom).':'.&escape($uname).
2028: ':'.$rulestr,$homeserver));
1.923 raeburn 2029: }
1.912 raeburn 2030: if ($response ne 'refused') {
2031: my @pairs=split(/\&/,$response);
2032: foreach my $item (@pairs) {
2033: my ($key,$value)=split(/=/,$item,2);
2034: $key = &unescape($key);
2035: next if ($key =~ /^error: 2 /);
2036: $returnhash{$key}=&thaw_unescape($value);
2037: }
2038: }
2039: }
2040: }
2041: }
2042: return %returnhash;
2043: }
2044:
2045: sub inst_userrules {
1.923 raeburn 2046: my ($udom,$check) = @_;
1.912 raeburn 2047: my (%ruleshash,@ruleorder);
2048: if ($udom ne '') {
2049: my $homeserver=&domain($udom,'primary');
2050: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2051: my $response;
2052: if ($check eq 'id') {
2053: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2054: $homeserver);
1.943 raeburn 2055: } elsif ($check eq 'email') {
2056: $response=&reply('instemailrules:'.&escape($udom),
2057: $homeserver);
1.923 raeburn 2058: } else {
2059: $response=&reply('instuserrules:'.&escape($udom),
2060: $homeserver);
2061: }
1.912 raeburn 2062: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2063: ($response ne 'unknown_cmd') &&
1.912 raeburn 2064: ($response ne 'no_such_host')) {
2065: my ($hashitems,$orderitems) = split(/:/,$response);
2066: my @pairs=split(/\&/,$hashitems);
2067: foreach my $item (@pairs) {
2068: my ($key,$value)=split(/=/,$item,2);
2069: $key = &unescape($key);
2070: next if ($key =~ /^error: 2 /);
2071: $ruleshash{$key}=&thaw_unescape($value);
2072: }
2073: my @esc_order = split(/\&/,$orderitems);
2074: foreach my $item (@esc_order) {
2075: push(@ruleorder,&unescape($item));
2076: }
2077: }
2078: }
2079: }
2080: return (\%ruleshash,\@ruleorder);
2081: }
2082:
1.976 raeburn 2083: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2084:
2085: sub get_domain_defaults {
1.1172.2.35 raeburn 2086: my ($domain,$ignore_cache) = @_;
2087: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2088: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2089: unless ($ignore_cache) {
2090: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2091: if (defined($cached)) {
2092: if (ref($result) eq 'HASH') {
2093: return %{$result};
2094: }
1.943 raeburn 2095: }
2096: }
2097: my %domdefaults;
2098: my %domconfig =
1.989 raeburn 2099: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2100: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2101: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2102: 'requestauthor','selfenrollment',
1.1172.2.76 raeburn 2103: 'coursecategories','autoenroll'],$domain);
1.1172.2.41 raeburn 2104: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2105: if (ref($domconfig{'defaults'}) eq 'HASH') {
2106: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2107: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2108: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2109: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2110: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2111: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2112: } else {
2113: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2114: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2115: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2116: }
1.976 raeburn 2117: if (ref($domconfig{'quotas'}) eq 'HASH') {
2118: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2119: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2120: } else {
2121: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2122: }
1.1172.2.6 raeburn 2123: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2124: foreach my $item (@usertools) {
2125: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2126: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2127: }
2128: }
1.1172.2.29 raeburn 2129: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2130: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2131: }
1.976 raeburn 2132: }
1.985 raeburn 2133: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2134: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2135: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2136: }
2137: }
1.1172.2.9 raeburn 2138: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2139: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2140: }
1.989 raeburn 2141: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2142: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2143: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2144: }
2145: }
1.1047 raeburn 2146: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2147: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2148: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2149: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2150: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2151: }
1.1172.2.41 raeburn 2152: foreach my $type (@coursetypes) {
2153: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2154: unless ($type eq 'community') {
2155: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2156: }
2157: }
2158: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2159: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2160: }
1.1172.2.60 raeburn 2161: if ($domdefaults{'postsubmit'} eq 'on') {
2162: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2163: $domdefaults{$type.'postsubtimeout'} =
2164: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2165: }
2166: }
1.1172.2.30 raeburn 2167: }
1.1172.2.67 raeburn 2168: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2169: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2170: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2171: if (@clonecodes) {
2172: $domdefaults{'canclone'} = join('+',@clonecodes);
2173: }
2174: }
2175: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2176: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2177: }
1.1047 raeburn 2178: }
1.1073 raeburn 2179: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2180: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2181: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2182: }
2183: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2184: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2185: }
1.1172.2.62 raeburn 2186: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2187: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2188: }
1.1073 raeburn 2189: }
1.1172.2.41 raeburn 2190: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2191: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2192: my @settings = ('types','registered','enroll_dates','access_dates','section',
2193: 'approval','limit');
2194: foreach my $type (@coursetypes) {
2195: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2196: my @mgrdc = ();
2197: foreach my $item (@settings) {
2198: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2199: push(@mgrdc,$item);
2200: }
2201: }
2202: if (@mgrdc) {
2203: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2204: }
2205: }
2206: }
2207: }
2208: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2209: foreach my $type (@coursetypes) {
2210: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2211: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2212: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2213: }
2214: }
2215: }
2216: }
2217: }
1.1172.2.46 raeburn 2218: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2219: $domdefaults{'catauth'} = 'std';
2220: $domdefaults{'catunauth'} = 'std';
2221: if ($domconfig{'coursecategories'}{'auth'}) {
2222: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2223: }
2224: if ($domconfig{'coursecategories'}{'unauth'}) {
2225: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2226: }
2227: }
1.1172.2.76 raeburn 2228: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2229: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2230: }
1.1172.2.23 raeburn 2231: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2232: return %domdefaults;
2233: }
2234:
1.344 www 2235: # --------------------------------------------------- Assign a key to a student
2236:
2237: sub assign_access_key {
1.364 www 2238: #
2239: # a valid key looks like uname:udom#comments
2240: # comments are being appended
2241: #
1.498 www 2242: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2243: $kdom=
1.620 albertel 2244: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2245: $knum=
1.620 albertel 2246: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2247: $cdom=
1.620 albertel 2248: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2249: $cnum=
1.620 albertel 2250: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2251: $udom=$env{'user.name'} unless (defined($udom));
2252: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2253: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2254: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2255: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2256: # assigned to this person
2257: # - this should not happen,
1.345 www 2258: # unless something went wrong
2259: # the first time around
2260: # ready to assign
1.364 www 2261: $logentry=$1.'; '.$logentry;
1.496 www 2262: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2263: $kdom,$knum) eq 'ok') {
1.345 www 2264: # key now belongs to user
1.346 www 2265: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2266: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2267: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2268: return 'ok';
2269: } else {
2270: return
2271: 'error: Count not permanently assign key, will need to be re-entered later.';
2272: }
2273: } else {
2274: return 'error: Could not assign key, try again later.';
2275: }
1.364 www 2276: } elsif (!$existing{$ckey}) {
1.345 www 2277: # the key does not exist
2278: return 'error: The key does not exist';
2279: } else {
2280: # the key is somebody else's
2281: return 'error: The key is already in use';
2282: }
1.344 www 2283: }
2284:
1.364 www 2285: # ------------------------------------------ put an additional comment on a key
2286:
2287: sub comment_access_key {
2288: #
2289: # a valid key looks like uname:udom#comments
2290: # comments are being appended
2291: #
2292: my ($ckey,$cdom,$cnum,$logentry)=@_;
2293: $cdom=
1.620 albertel 2294: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2295: $cnum=
1.620 albertel 2296: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2297: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2298: if ($existing{$ckey}) {
2299: $existing{$ckey}.='; '.$logentry;
2300: # ready to assign
1.367 www 2301: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2302: $cdom,$cnum) eq 'ok') {
2303: return 'ok';
2304: } else {
2305: return 'error: Count not store comment.';
2306: }
2307: } else {
2308: # the key does not exist
2309: return 'error: The key does not exist';
2310: }
2311: }
2312:
1.344 www 2313: # ------------------------------------------------------ Generate a set of keys
2314:
2315: sub generate_access_keys {
1.364 www 2316: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2317: $cdom=
1.620 albertel 2318: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2319: $cnum=
1.620 albertel 2320: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2321: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2322: unless (($cdom) && ($cnum)) { return 0; }
2323: if ($number>10000) { return 0; }
2324: sleep(2); # make sure don't get same seed twice
2325: srand(time()^($$+($$<<15))); # from "Programming Perl"
2326: my $total=0;
2327: for (my $i=1;$i<=$number;$i++) {
2328: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2329: sprintf("%lx",int(100000*rand)).'-'.
2330: sprintf("%lx",int(100000*rand));
2331: $newkey=~s/1/g/g; # folks mix up 1 and l
2332: $newkey=~s/0/h/g; # and also 0 and O
2333: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2334: if ($existing{$newkey}) {
2335: $i--;
2336: } else {
1.364 www 2337: if (&put('accesskeys',
2338: { $newkey => '# generated '.localtime().
1.620 albertel 2339: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2340: '; '.$logentry },
2341: $cdom,$cnum) eq 'ok') {
1.344 www 2342: $total++;
2343: }
2344: }
2345: }
1.620 albertel 2346: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2347: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2348: return $total;
2349: }
2350:
2351: # ------------------------------------------------------- Validate an accesskey
2352:
2353: sub validate_access_key {
2354: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2355: $cdom=
1.620 albertel 2356: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2357: $cnum=
1.620 albertel 2358: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2359: $udom=$env{'user.domain'} unless (defined($udom));
2360: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2361: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2362: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2363: }
2364:
2365: # ------------------------------------- Find the section of student in a course
1.652 albertel 2366: sub devalidate_getsection_cache {
2367: my ($udom,$unam,$courseid)=@_;
2368: my $hashid="$udom:$unam:$courseid";
2369: &devalidate_cache_new('getsection',$hashid);
2370: }
1.298 matthew 2371:
1.815 albertel 2372: sub courseid_to_courseurl {
2373: my ($courseid) = @_;
2374: #already url style courseid
2375: return $courseid if ($courseid =~ m{^/});
2376:
2377: if (exists($env{'course.'.$courseid.'.num'})) {
2378: my $cnum = $env{'course.'.$courseid.'.num'};
2379: my $cdom = $env{'course.'.$courseid.'.domain'};
2380: return "/$cdom/$cnum";
2381: }
2382:
2383: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2384: if (exists($courseinfo{'num'})) {
2385: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2386: }
2387:
2388: return undef;
2389: }
2390:
1.298 matthew 2391: sub getsection {
2392: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2393: my $cachetime=1800;
1.551 albertel 2394:
2395: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2396: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2397: if (defined($cached)) { return $result; }
2398:
1.298 matthew 2399: my %Pending;
2400: my %Expired;
2401: #
2402: # Each role can either have not started yet (pending), be active,
2403: # or have expired.
2404: #
2405: # If there is an active role, we are done.
2406: #
2407: # If there is more than one role which has not started yet,
2408: # choose the one which will start sooner
2409: # If there is one role which has not started yet, return it.
2410: #
2411: # If there is more than one expired role, choose the one which ended last.
2412: # If there is a role which has expired, return it.
2413: #
1.815 albertel 2414: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2415: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2416: foreach my $key (keys(%roleshash)) {
1.479 albertel 2417: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2418: my $section=$1;
2419: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2420: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2421: my $now=time;
1.548 albertel 2422: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2423: $Expired{$end}=$section;
2424: next;
2425: }
1.548 albertel 2426: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2427: $Pending{$start}=$section;
2428: next;
2429: }
1.599 albertel 2430: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2431: }
2432: #
2433: # Presumedly there will be few matching roles from the above
2434: # loop and the sorting time will be negligible.
2435: if (scalar(keys(%Pending))) {
2436: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2437: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2438: }
2439: if (scalar(keys(%Expired))) {
2440: my @sorted = sort {$a <=> $b} keys(%Expired);
2441: my $time = pop(@sorted);
1.599 albertel 2442: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2443: }
1.599 albertel 2444: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2445: }
1.70 www 2446:
1.599 albertel 2447: sub save_cache {
2448: &purge_remembered();
1.722 albertel 2449: #&Apache::loncommon::validate_page();
1.620 albertel 2450: undef(%env);
1.780 albertel 2451: undef($env_loaded);
1.599 albertel 2452: }
1.452 albertel 2453:
1.599 albertel 2454: my $to_remember=-1;
2455: my %remembered;
2456: my %accessed;
2457: my $kicks=0;
2458: my $hits=0;
1.849 albertel 2459: sub make_key {
2460: my ($name,$id) = @_;
1.872 albertel 2461: if (length($id) > 65
2462: && length(&escape($id)) > 200) {
2463: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2464: }
1.849 albertel 2465: return &escape($name.':'.$id);
2466: }
2467:
1.599 albertel 2468: sub devalidate_cache_new {
2469: my ($name,$id,$debug) = @_;
2470: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2471: my $remembered_id=$name.':'.$id;
1.849 albertel 2472: $id=&make_key($name,$id);
1.599 albertel 2473: $memcache->delete($id);
1.1172.2.81 raeburn 2474: delete($remembered{$remembered_id});
2475: delete($accessed{$remembered_id});
1.599 albertel 2476: }
2477:
2478: sub is_cached_new {
2479: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2480: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2481: # keys in %remembered hash, which persists for
2482: # duration of request (no restriction on key length).
2483: if (exists($remembered{$remembered_id})) {
2484: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2485: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2486: $hits++;
1.1172.2.81 raeburn 2487: return ($remembered{$remembered_id},1);
1.599 albertel 2488: }
1.1172.2.81 raeburn 2489: $id=&make_key($name,$id);
1.599 albertel 2490: my $value = $memcache->get($id);
2491: if (!(defined($value))) {
2492: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2493: return (undef,undef);
1.416 albertel 2494: }
1.599 albertel 2495: if ($value eq '__undef__') {
2496: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2497: $value=undef;
2498: }
1.1172.2.81 raeburn 2499: &make_room($remembered_id,$value,$debug);
1.599 albertel 2500: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2501: return ($value,1);
2502: }
2503:
2504: sub do_cache_new {
2505: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2506: my $remembered_id=$name.':'.$id;
1.849 albertel 2507: $id=&make_key($name,$id);
1.599 albertel 2508: my $setvalue=$value;
2509: if (!defined($setvalue)) {
2510: $setvalue='__undef__';
2511: }
1.623 albertel 2512: if (!defined($time) ) {
2513: $time=600;
2514: }
1.599 albertel 2515: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2516: my $result = $memcache->set($id,$setvalue,$time);
2517: if (! $result) {
1.872 albertel 2518: &logthis("caching of id -> $id failed");
1.910 albertel 2519: $memcache->disconnect_all();
1.872 albertel 2520: }
1.600 albertel 2521: # need to make a copy of $value
1.1172.2.81 raeburn 2522: &make_room($remembered_id,$value,$debug);
1.599 albertel 2523: return $value;
2524: }
2525:
2526: sub make_room {
1.1172.2.81 raeburn 2527: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2528:
1.1172.2.81 raeburn 2529: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2530: : $value;
1.599 albertel 2531: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2532: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2533: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2534: my $to_kick;
2535: my $max_time=0;
2536: foreach my $other (keys(%accessed)) {
2537: if (&tv_interval($accessed{$other}) > $max_time) {
2538: $to_kick=$other;
2539: $max_time=&tv_interval($accessed{$other});
2540: }
2541: }
2542: delete($remembered{$to_kick});
2543: delete($accessed{$to_kick});
2544: $kicks++;
2545: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2546: return;
2547: }
2548:
1.599 albertel 2549: sub purge_remembered {
1.604 albertel 2550: #&logthis("Tossing ".scalar(keys(%remembered)));
2551: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2552: undef(%remembered);
2553: undef(%accessed);
1.428 albertel 2554: }
1.70 www 2555: # ------------------------------------- Read an entry from a user's environment
2556:
2557: sub userenvironment {
2558: my ($udom,$unam,@what)=@_;
1.976 raeburn 2559: my $items;
2560: foreach my $item (@what) {
2561: $items.=&escape($item).'&';
2562: }
2563: $items=~s/\&$//;
1.70 www 2564: my %returnhash=();
1.1009 raeburn 2565: my $uhome = &homeserver($unam,$udom);
2566: unless ($uhome eq 'no_host') {
2567: my @answer=split(/\&/,
2568: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2569: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2570: return %returnhash;
2571: }
1.1009 raeburn 2572: my $i;
2573: for ($i=0;$i<=$#what;$i++) {
2574: $returnhash{$what[$i]}=&unescape($answer[$i]);
2575: }
1.70 www 2576: }
2577: return %returnhash;
1.1 albertel 2578: }
2579:
1.617 albertel 2580: # ---------------------------------------------------------- Get a studentphoto
2581: sub studentphoto {
2582: my ($udom,$unam,$ext) = @_;
2583: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2584: if (defined($env{'request.course.id'})) {
1.708 raeburn 2585: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2586: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2587: return(&retrievestudentphoto($udom,$unam,$ext));
2588: } else {
2589: my ($result,$perm_reqd)=
1.707 albertel 2590: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2591: if ($result eq 'ok') {
2592: if (!($perm_reqd eq 'yes')) {
2593: return(&retrievestudentphoto($udom,$unam,$ext));
2594: }
2595: }
2596: }
2597: }
2598: } else {
2599: my ($result,$perm_reqd) =
1.707 albertel 2600: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2601: if ($result eq 'ok') {
2602: if (!($perm_reqd eq 'yes')) {
2603: return(&retrievestudentphoto($udom,$unam,$ext));
2604: }
2605: }
2606: }
2607: return '/adm/lonKaputt/lonlogo_broken.gif';
2608: }
2609:
2610: sub retrievestudentphoto {
2611: my ($udom,$unam,$ext,$type) = @_;
2612: my $home=&Apache::lonnet::homeserver($unam,$udom);
2613: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2614: if ($ret eq 'ok') {
2615: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2616: if ($type eq 'thumbnail') {
2617: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2618: }
2619: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2620: return $tokenurl;
2621: } else {
2622: if ($type eq 'thumbnail') {
2623: return '/adm/lonKaputt/genericstudent_tn.gif';
2624: } else {
2625: return '/adm/lonKaputt/lonlogo_broken.gif';
2626: }
1.617 albertel 2627: }
2628: }
2629:
1.263 www 2630: # -------------------------------------------------------------------- New chat
2631:
2632: sub chatsend {
1.724 raeburn 2633: my ($newentry,$anon,$group)=@_;
1.620 albertel 2634: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2635: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2636: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2637: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2638: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2639: &escape($newentry)).':'.$group,$chome);
1.292 www 2640: }
2641:
2642: # ------------------------------------------ Find current version of a resource
2643:
2644: sub getversion {
2645: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2646: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2647: return ¤tversion(&filelocation('',$fname));
2648: }
2649:
2650: sub currentversion {
2651: my $fname=shift;
2652: my $author=$fname;
2653: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2654: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2655: my $home=&homeserver($uname,$udom);
1.292 www 2656: if ($home eq 'no_host') {
2657: return -1;
2658: }
1.1112 www 2659: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2660: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2661: return -1;
2662: }
1.1112 www 2663: return $answer;
1.263 www 2664: }
2665:
1.1111 www 2666: #
2667: # Return special version number of resource if set by override, empty otherwise
2668: #
2669: sub usedversion {
2670: my $fname=shift;
2671: unless ($fname) { $fname=$env{'request.uri'}; }
2672: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2673: if ($urlversion) { return $urlversion; }
2674: return '';
2675: }
2676:
1.1 albertel 2677: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2678:
1.1 albertel 2679: sub subscribe {
2680: my $fname=shift;
1.761 raeburn 2681: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2682: $fname=~s/[\n\r]//g;
1.1 albertel 2683: my $author=$fname;
2684: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2685: my ($udom,$uname)=split(/\//,$author);
2686: my $home=homeserver($uname,$udom);
1.335 albertel 2687: if ($home eq 'no_host') {
2688: return 'not_found';
1.1 albertel 2689: }
2690: my $answer=reply("sub:$fname",$home);
1.64 www 2691: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2692: $answer.=' by '.$home;
2693: }
1.1 albertel 2694: return $answer;
2695: }
2696:
1.8 www 2697: # -------------------------------------------------------------- Replicate file
2698:
2699: sub repcopy {
2700: my $filename=shift;
1.23 www 2701: $filename=~s/\/+/\//g;
1.1142 raeburn 2702: my $londocroot = $perlvar{'lonDocRoot'};
2703: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2704: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2705: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2706: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2707: return &repcopy_userfile($filename);
2708: }
1.532 albertel 2709: $filename=~s/[\n\r]//g;
1.8 www 2710: my $transname="$filename.in.transfer";
1.828 www 2711: # FIXME: this should flock
1.607 raeburn 2712: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2713: my $remoteurl=subscribe($filename);
1.64 www 2714: if ($remoteurl =~ /^con_lost by/) {
2715: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2716: return 'unavailable';
1.8 www 2717: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2718: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2719: return 'not_found';
1.64 www 2720: } elsif ($remoteurl =~ /^rejected by/) {
2721: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2722: return 'forbidden';
1.20 www 2723: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2724: return 'ok';
1.8 www 2725: } else {
1.290 www 2726: my $author=$filename;
2727: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2728: my ($udom,$uname)=split(/\//,$author);
2729: my $home=homeserver($uname,$udom);
2730: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2731: my @parts=split(/\//,$filename);
2732: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2733: if ($path ne "$londocroot/res") {
1.8 www 2734: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2735: return 'bad_request';
1.8 www 2736: }
2737: my $count;
2738: for ($count=5;$count<$#parts;$count++) {
2739: $path.="/$parts[$count]";
2740: if ((-e $path)!=1) {
2741: mkdir($path,0777);
2742: }
2743: }
2744: my $ua=new LWP::UserAgent;
2745: my $request=new HTTP::Request('GET',"$remoteurl");
2746: my $response=$ua->request($request,$transname);
2747: if ($response->is_error()) {
2748: unlink($transname);
2749: my $message=$response->status_line;
1.672 albertel 2750: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2751: ." LWP get: $message: $filename</font>");
1.607 raeburn 2752: return 'unavailable';
1.8 www 2753: } else {
1.16 www 2754: if ($remoteurl!~/\.meta$/) {
2755: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2756: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2757: if ($mresponse->is_error()) {
2758: unlink($filename.'.meta');
2759: &logthis(
1.672 albertel 2760: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2761: }
2762: }
1.8 www 2763: rename($transname,$filename);
1.607 raeburn 2764: return 'ok';
1.8 www 2765: }
1.290 www 2766: }
1.8 www 2767: }
1.330 www 2768: }
2769:
2770: # ------------------------------------------------ Get server side include body
2771: sub ssi_body {
1.381 albertel 2772: my ($filelink,%form)=@_;
1.606 matthew 2773: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2774: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2775: }
1.953 www 2776: my $output='';
2777: my $response;
1.980 raeburn 2778: if ($filelink=~/^https?\:/) {
1.954 raeburn 2779: ($output,$response)=&externalssi($filelink);
1.953 www 2780: } else {
1.1004 droeschl 2781: $filelink .= $filelink=~/\?/ ? '&' : '?';
2782: $filelink .= 'inhibitmenu=yes';
1.953 www 2783: ($output,$response)=&ssi($filelink,%form);
2784: }
1.778 albertel 2785: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2786: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2787: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2788: if (wantarray) {
2789: return ($output, $response);
2790: } else {
2791: return $output;
2792: }
1.8 www 2793: }
2794:
1.15 www 2795: # --------------------------------------------------------- Server Side Include
2796:
1.782 albertel 2797: sub absolute_url {
2798: my ($host_name) = @_;
2799: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2800: if ($host_name eq '') {
2801: $host_name = $ENV{'SERVER_NAME'};
2802: }
2803: return $protocol.$host_name;
2804: }
2805:
1.942 foxr 2806: #
2807: # Server side include.
2808: # Parameters:
2809: # fn Possibly encrypted resource name/id.
2810: # form Hash that describes how the rendering should be done
2811: # and other things.
1.944 foxr 2812: # Returns:
1.950 raeburn 2813: # Scalar context: The content of the response.
2814: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2815: #
1.15 www 2816: sub ssi {
2817:
1.944 foxr 2818: my ($fn,%form)=@_;
1.15 www 2819: my $ua=new LWP::UserAgent;
1.23 www 2820: my $request;
1.711 albertel 2821:
2822: $form{'no_update_last_known'}=1;
1.895 albertel 2823: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2824: if (%form) {
1.782 albertel 2825: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2826: $request->content(join('&',map {
2827: my $name = escape($_);
2828: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2829: ? join("&$name=", map {escape($_) } @{$form{$_}})
2830: : &escape($form{$_}) );
2831: } keys(%form)));
1.23 www 2832: } else {
1.782 albertel 2833: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2834: }
2835:
1.15 www 2836: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2837: my $response= $ua->request($request);
1.944 foxr 2838: if (wantarray) {
1.1172.2.3 raeburn 2839: return ($response->content, $response);
1.944 foxr 2840: } else {
1.1172.2.3 raeburn 2841: return $response->content;
1.942 foxr 2842: }
1.324 www 2843: }
2844:
2845: sub externalssi {
2846: my ($url)=@_;
2847: my $ua=new LWP::UserAgent;
2848: my $request=new HTTP::Request('GET',$url);
2849: my $response=$ua->request($request);
1.954 raeburn 2850: if (wantarray) {
2851: return ($response->content, $response);
2852: } else {
2853: return $response->content;
2854: }
1.15 www 2855: }
1.254 www 2856:
1.492 albertel 2857: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2858:
2859: sub allowuploaded {
2860: my ($srcurl,$url)=@_;
2861: $url=&clutter(&declutter($url));
2862: my $dir=$url;
2863: $dir=~s/\/[^\/]+$//;
2864: my %httpref=();
2865: my $httpurl=&hreflocation('',$url);
2866: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2867: &Apache::lonnet::appenv(\%httpref);
1.254 www 2868: }
1.477 raeburn 2869:
1.1172.2.13 raeburn 2870: #
2871: # Determine if the current user should be able to edit a particular resource,
2872: # when viewing in course context.
2873: # (a) When viewing resource used to determine if "Edit" item is included in
2874: # Functions.
2875: # (b) When displaying folder contents in course editor, used to determine if
2876: # "Edit" link will be displayed alongside resource.
2877: #
2878: # input: six args -- filename (decluttered), course number, course domain,
2879: # url, symb (if registered) and group (if this is a group
2880: # item -- e.g., bulletin board, group page etc.).
2881: # output: array of five scalars --
2882: # $cfile -- url for file editing if editable on current server
2883: # $home -- homeserver of resource (i.e., for author if published,
2884: # or course if uploaded.).
2885: # $switchserver -- 1 if server switch will be needed.
2886: # $forceedit -- 1 if icon/link should be to go to edit mode
2887: # $forceview -- 1 if icon/link should be to go to view mode
2888: #
2889:
2890: sub can_edit_resource {
2891: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2892: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2893: #
2894: # For aboutme pages user can only edit his/her own.
2895: #
2896: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2897: my ($sdom,$sname) = ($1,$2);
2898: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2899: $home = $env{'user.home'};
2900: $cfile = $resurl;
2901: if ($env{'form.forceedit'}) {
2902: $forceview = 1;
2903: } else {
2904: $forceedit = 1;
2905: }
2906: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2907: } else {
2908: return;
2909: }
2910: }
2911:
2912: if ($env{'request.course.id'}) {
2913: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2914: if ($group ne '') {
2915: # if this is a group homepage or group bulletin board, check group privs
2916: my $allowed = 0;
2917: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2918: if ((&allowed('mdg',$env{'request.course.id'}.
2919: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2920: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2921: $allowed = 1;
2922: }
2923: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2924: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2925: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2926: $allowed = 1;
2927: }
2928: }
2929: if ($allowed) {
2930: $home=&homeserver($cnum,$cdom);
2931: if ($env{'form.forceedit'}) {
2932: $forceview = 1;
2933: } else {
2934: $forceedit = 1;
2935: }
2936: $cfile = $resurl;
2937: } else {
2938: return;
2939: }
2940: } else {
1.1172.2.15 raeburn 2941: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2942: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2943: return;
2944: }
2945: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2946: #
2947: # No edit allowed where CC has switched to student role.
2948: #
2949: return;
2950: }
2951: }
2952: }
2953:
2954: if ($file ne '') {
2955: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2956: if (&is_course_upload($file,$cnum,$cdom)) {
2957: $uploaded = 1;
2958: $incourse = 1;
2959: if ($file =~/\.(htm|html|css|js|txt)$/) {
2960: $cfile = &hreflocation('',$file);
2961: if ($env{'form.forceedit'}) {
2962: $forceview = 1;
2963: } else {
2964: $forceedit = 1;
2965: }
2966: }
2967: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2968: $incourse = 1;
2969: if ($env{'form.forceedit'}) {
2970: $forceview = 1;
2971: } else {
2972: $forceedit = 1;
2973: }
2974: $cfile = $resurl;
2975: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2976: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2977: $incourse = 1;
2978: if ($env{'form.forceedit'}) {
2979: $forceview = 1;
2980: } else {
2981: $forceedit = 1;
2982: }
2983: $cfile = $resurl;
2984: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2985: $incourse = 1;
2986: $cfile = $resurl.'/smpedit';
2987: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2988: $incourse = 1;
2989: if ($env{'form.forceedit'}) {
2990: $forceview = 1;
2991: } else {
2992: $forceedit = 1;
2993: }
2994: $cfile = $resurl;
1.1172.2.15 raeburn 2995: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2996: $incourse = 1;
2997: if ($env{'form.forceedit'}) {
2998: $forceview = 1;
2999: } else {
3000: $forceedit = 1;
3001: }
3002: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3003: }
3004: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3005: my $template = '/res/lib/templates/simpleproblem.problem';
3006: if (&is_on_map($template)) {
3007: $incourse = 1;
3008: $forceview = 1;
3009: $cfile = $template;
3010: }
3011: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3012: $incourse = 1;
3013: if ($env{'form.forceedit'}) {
3014: $forceview = 1;
3015: } else {
3016: $forceedit = 1;
3017: }
3018: $cfile = $resurl;
3019: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3020: $incourse = 1;
3021: $forceview = 1;
3022: if ($symb) {
3023: my ($map,$id,$res)=&decode_symb($symb);
3024: $env{'request.symb'} = $symb;
3025: $cfile = &clutter($res);
3026: } else {
3027: $cfile = $env{'form.suppurl'};
3028: $cfile =~ s{^http://}{};
3029: $cfile = '/adm/wrapper/ext/'.$cfile;
3030: }
1.1172.2.31 raeburn 3031: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3032: if ($env{'form.forceedit'}) {
3033: $forceview = 1;
3034: } else {
3035: $forceedit = 1;
3036: }
3037: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3038: }
3039: }
3040: if ($uploaded || $incourse) {
3041: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3042: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3043: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3044: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3045: # Check that the user has permission to edit this resource
3046: my $setpriv = 1;
3047: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3048: if (defined($cfudom)) {
3049: $home=&homeserver($cfuname,$cfudom);
3050: $cfile=$file;
3051: }
3052: }
3053: if (($cfile ne '') && (!$incourse || $uploaded) &&
3054: (($home ne '') && ($home ne 'no_host'))) {
3055: my @ids=¤t_machine_ids();
3056: unless (grep(/^\Q$home\E$/,@ids)) {
3057: $switchserver=1;
3058: }
3059: }
3060: }
3061: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3062: }
3063:
3064: sub is_course_upload {
3065: my ($file,$cnum,$cdom) = @_;
3066: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3067: $uploadpath =~ s{^\/}{};
3068: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3069: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3070: return 1;
3071: }
3072: return;
3073: }
3074:
3075: sub in_course {
3076: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3077: if ($hideprivileged) {
3078: my $skipuser;
1.1172.2.23 raeburn 3079: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3080: my @possdoms = ($cdom);
3081: if ($coursehash{'checkforpriv'}) {
3082: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3083: }
3084: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3085: $skipuser = 1;
3086: if ($coursehash{'nothideprivileged'}) {
3087: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3088: my $user;
3089: if ($item =~ /:/) {
3090: $user = $item;
3091: } else {
3092: $user = join(':',split(/[\@]/,$item));
3093: }
3094: if ($user eq $uname.':'.$udom) {
3095: undef($skipuser);
3096: last;
3097: }
3098: }
3099: }
3100: if ($skipuser) {
3101: return 0;
3102: }
3103: }
3104: }
3105: $type ||= 'any';
3106: if (!defined($cdom) || !defined($cnum)) {
3107: my $cid = $env{'request.course.id'};
3108: $cdom = $env{'course.'.$cid.'.domain'};
3109: $cnum = $env{'course.'.$cid.'.num'};
3110: }
3111: my $typesref;
3112: if (($type eq 'any') || ($type eq 'all')) {
3113: $typesref = ['active','previous','future'];
3114: } elsif ($type eq 'previous' || $type eq 'future') {
3115: $typesref = [$type];
3116: }
3117: my %roles = &get_my_roles($uname,$udom,'userroles',
3118: $typesref,undef,[$cdom]);
3119: my ($tmp) = keys(%roles);
3120: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3121: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3122: if (@course_roles > 0) {
3123: return 1;
3124: }
3125: return 0;
3126: }
3127:
1.478 albertel 3128: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3129: # input: action, courseID, current domain, intended
1.637 raeburn 3130: # path to file, source of file, instruction to parse file for objects,
3131: # ref to hash for embedded objects,
3132: # ref to hash for codebase of java objects.
1.1095 raeburn 3133: # reference to scalar to accommodate mime type determined
3134: # from File::MMagic if $parser = parse.
1.637 raeburn 3135: #
1.485 raeburn 3136: # output: url to file (if action was uploaddoc),
3137: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3138: #
1.478 albertel 3139: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3140: # course.
1.477 raeburn 3141: #
1.478 albertel 3142: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3143: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3144: # course's home server.
1.477 raeburn 3145: #
1.478 albertel 3146: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3147: # be copied from $source (current location) to
3148: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3149: # and will then be copied to
3150: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3151: # course's home server.
1.485 raeburn 3152: #
1.481 raeburn 3153: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3154: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3155: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3156: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3157: # in course's home server.
1.637 raeburn 3158: #
1.477 raeburn 3159:
3160: sub process_coursefile {
1.1095 raeburn 3161: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3162: $mimetype)=@_;
1.477 raeburn 3163: my $fetchresult;
1.638 albertel 3164: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3165: if ($action eq 'propagate') {
1.638 albertel 3166: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3167: $home);
1.481 raeburn 3168: } else {
1.477 raeburn 3169: my $fpath = '';
3170: my $fname = $file;
1.478 albertel 3171: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3172: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3173: my $filepath = &build_filepath($fpath);
1.481 raeburn 3174: if ($action eq 'copy') {
3175: if ($source eq '') {
3176: $fetchresult = 'no source file';
3177: return $fetchresult;
3178: } else {
3179: my $destination = $filepath.'/'.$fname;
3180: rename($source,$destination);
3181: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3182: $home);
1.481 raeburn 3183: }
3184: } elsif ($action eq 'uploaddoc') {
3185: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3186: print $fh $env{'form.'.$source};
1.481 raeburn 3187: close($fh);
1.637 raeburn 3188: if ($parser eq 'parse') {
1.1024 raeburn 3189: my $mm = new File::MMagic;
1.1095 raeburn 3190: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3191: if ($type eq 'text/html') {
1.1024 raeburn 3192: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3193: unless ($parse_result eq 'ok') {
3194: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3195: }
1.637 raeburn 3196: }
1.1095 raeburn 3197: if (ref($mimetype)) {
3198: $$mimetype = $type;
3199: }
1.637 raeburn 3200: }
1.477 raeburn 3201: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3202: $home);
1.481 raeburn 3203: if ($fetchresult eq 'ok') {
3204: return '/uploaded/'.$fpath.'/'.$fname;
3205: } else {
3206: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3207: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3208: return '/adm/notfound.html';
3209: }
1.477 raeburn 3210: }
3211: }
1.485 raeburn 3212: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3213: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3214: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3215: }
3216: return $fetchresult;
3217: }
3218:
1.637 raeburn 3219: sub build_filepath {
3220: my ($fpath) = @_;
3221: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3222: unless ($fpath eq '') {
3223: my @parts=split('/',$fpath);
3224: foreach my $part (@parts) {
3225: $filepath.= '/'.$part;
3226: if ((-e $filepath)!=1) {
3227: mkdir($filepath,0777);
3228: }
3229: }
3230: }
3231: return $filepath;
3232: }
3233:
3234: sub store_edited_file {
1.638 albertel 3235: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3236: my $file = $primary_url;
3237: $file =~ s#^/uploaded/$docudom/$docuname/##;
3238: my $fpath = '';
3239: my $fname = $file;
3240: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3241: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3242: my $filepath = &build_filepath($fpath);
3243: open(my $fh,'>'.$filepath.'/'.$fname);
3244: print $fh $content;
3245: close($fh);
1.638 albertel 3246: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3247: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3248: $home);
1.637 raeburn 3249: if ($$fetchresult eq 'ok') {
3250: return '/uploaded/'.$fpath.'/'.$fname;
3251: } else {
1.638 albertel 3252: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3253: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3254: return '/adm/notfound.html';
3255: }
3256: }
3257:
1.531 albertel 3258: sub clean_filename {
1.831 albertel 3259: my ($fname,$args)=@_;
1.315 www 3260: # Replace Windows backslashes by forward slashes
1.257 www 3261: $fname=~s/\\/\//g;
1.831 albertel 3262: if (!$args->{'keep_path'}) {
3263: # Get rid of everything but the actual filename
3264: $fname=~s/^.*\/([^\/]+)$/$1/;
3265: }
1.315 www 3266: # Replace spaces by underscores
3267: $fname=~s/\s+/\_/g;
3268: # Replace all other weird characters by nothing
1.831 albertel 3269: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3270: # Replace all .\d. sequences with _\d. so they no longer look like version
3271: # numbers
3272: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3273: return $fname;
3274: }
1.1051 raeburn 3275: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3276: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3277: # image with the same aspect ratio as the original, but with dimensions which do
3278: # not exceed $resizewidth and $resizeheight.
3279:
1.984 neumanie 3280: sub resizeImage {
1.1051 raeburn 3281: my ($img_path,$resizewidth,$resizeheight) = @_;
3282: my $ima = Image::Magick->new;
3283: my $resized;
3284: if (-e $img_path) {
3285: $ima->Read($img_path);
3286: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3287: my $width = $ima->Get('width');
3288: my $height = $ima->Get('height');
3289: if ($width > $resizewidth) {
3290: my $factor = $width/$resizewidth;
3291: my $newheight = $height/$factor;
3292: $ima->Scale(width=>$resizewidth,height=>$newheight);
3293: $resized = 1;
3294: }
3295: }
3296: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3297: my $width = $ima->Get('width');
3298: my $height = $ima->Get('height');
3299: if ($height > $resizeheight) {
3300: my $factor = $height/$resizeheight;
3301: my $newwidth = $width/$factor;
3302: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3303: $resized = 1;
3304: }
3305: }
3306: if ($resized) {
3307: $ima->Write($img_path);
3308: }
3309: }
3310: return;
1.977 amueller 3311: }
3312:
1.608 albertel 3313: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3314: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3315: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3316: # $context - possible values: coursedoc, existingfile, overwrite,
3317: # canceloverwrite, or ''.
3318: # if 'coursedoc': upload to the current course
3319: # if 'existingfile': write file to tmp/overwrites directory
3320: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3321: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3322: # $subdir - directory in userfile to store the file into
1.858 raeburn 3323: # $parser - instruction to parse file for objects ($parser = parse)
3324: # $allfiles - reference to hash for embedded objects
3325: # $codebase - reference to hash for codebase of java objects
3326: # $desuname - username for permanent storage of uploaded file
3327: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3328: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3329: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3330: # $resizewidth - width (pixels) to which to resize uploaded image
3331: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3332: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3333: # from File::MMagic.
1.858 raeburn 3334: #
1.686 albertel 3335: # output: url of file in userspace, or error: <message>
3336: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3337:
1.531 albertel 3338: sub userfileupload {
1.1090 raeburn 3339: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3340: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3341: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3342: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3343: $fname=&clean_filename($fname);
1.1090 raeburn 3344: # See if there is anything left
1.257 www 3345: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3346: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3347: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3348: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3349: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3350: my $now = time;
1.1090 raeburn 3351: my $filepath;
1.1095 raeburn 3352: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3353: $filepath = 'tmp/helprequests/'.$now;
3354: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3355: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3356: '_'.$env{'user.domain'}.'/pending';
3357: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3358: my ($docuname,$docudom);
3359: if ($destudom) {
3360: $docudom = $destudom;
3361: } else {
3362: $docudom = $env{'user.domain'};
3363: }
3364: if ($destuname) {
3365: $docuname = $destuname;
3366: } else {
3367: $docuname = $env{'user.name'};
3368: }
3369: if (exists($env{'form.group'})) {
3370: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3371: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3372: }
3373: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3374: if ($context eq 'canceloverwrite') {
3375: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3376: if (-e $tempfile) {
3377: my @info = stat($tempfile);
3378: if ($info[9] eq $env{'form.timestamp'}) {
3379: unlink($tempfile);
3380: }
3381: }
3382: return;
1.523 raeburn 3383: }
3384: }
1.1090 raeburn 3385: # Create the directory if not present
1.741 raeburn 3386: my @parts=split(/\//,$filepath);
3387: my $fullpath = $perlvar{'lonDaemons'};
3388: for (my $i=0;$i<@parts;$i++) {
3389: $fullpath .= '/'.$parts[$i];
3390: if ((-e $fullpath)!=1) {
3391: mkdir($fullpath,0777);
3392: }
3393: }
3394: open(my $fh,'>'.$fullpath.'/'.$fname);
3395: print $fh $env{'form.'.$formname};
3396: close($fh);
1.1090 raeburn 3397: if ($context eq 'existingfile') {
3398: my @info = stat($fullpath.'/'.$fname);
3399: return ($fullpath.'/'.$fname,$info[9]);
3400: } else {
3401: return $fullpath.'/'.$fname;
3402: }
1.523 raeburn 3403: }
1.995 raeburn 3404: if ($subdir eq 'scantron') {
3405: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3406: } else {
1.995 raeburn 3407: $fname="$subdir/$fname";
3408: }
1.1090 raeburn 3409: if ($context eq 'coursedoc') {
1.638 albertel 3410: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3411: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3412: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3413: return &finishuserfileupload($docuname,$docudom,
3414: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3415: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3416: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3417: } else {
1.1172.2.21 raeburn 3418: if ($env{'form.folder'}) {
3419: $fname=$env{'form.folder'}.'/'.$fname;
3420: }
1.638 albertel 3421: return &process_coursefile('uploaddoc',$docuname,$docudom,
3422: $fname,$formname,$parser,
1.1095 raeburn 3423: $allfiles,$codebase,$mimetype);
1.481 raeburn 3424: }
1.719 banghart 3425: } elsif (defined($destuname)) {
3426: my $docuname=$destuname;
3427: my $docudom=$destudom;
1.860 raeburn 3428: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3429: $parser,$allfiles,$codebase,
1.1051 raeburn 3430: $thumbwidth,$thumbheight,
1.1095 raeburn 3431: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3432: } else {
1.638 albertel 3433: my $docuname=$env{'user.name'};
3434: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3435: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3436: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3437: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3438: }
1.860 raeburn 3439: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3440: $parser,$allfiles,$codebase,
1.1051 raeburn 3441: $thumbwidth,$thumbheight,
1.1095 raeburn 3442: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3443: }
1.271 www 3444: }
3445:
3446: sub finishuserfileupload {
1.860 raeburn 3447: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3448: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3449: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3450: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3451:
1.860 raeburn 3452: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3453: $file=$fname;
3454: if ($fname=~m|/|) {
3455: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3456: $path.=$fnamepath.'/';
3457: }
1.259 www 3458: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3459: my $count;
3460: for ($count=4;$count<=$#parts;$count++) {
3461: $filepath.="/$parts[$count]";
3462: if ((-e $filepath)!=1) {
3463: mkdir($filepath,0777);
3464: }
3465: }
1.984 neumanie 3466:
1.258 www 3467: # Save the file
3468: {
1.701 albertel 3469: if (!open(FH,'>'.$filepath.'/'.$file)) {
3470: &logthis('Failed to create '.$filepath.'/'.$file);
3471: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3472: return '/adm/notfound.html';
3473: }
1.1090 raeburn 3474: if ($context eq 'overwrite') {
1.1117 foxr 3475: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3476: my $target = $filepath.'/'.$file;
3477: if (-e $source) {
3478: my @info = stat($source);
3479: if ($info[9] eq $env{'form.timestamp'}) {
3480: unless (&File::Copy::move($source,$target)) {
3481: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3482: return "Moving from $source failed";
3483: }
3484: } else {
3485: return "Temporary file: $source had unexpected date/time for last modification";
3486: }
3487: } else {
3488: return "Temporary file: $source missing";
3489: }
3490: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3491: &logthis('Failed to write to '.$filepath.'/'.$file);
3492: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3493: return '/adm/notfound.html';
3494: }
1.570 albertel 3495: close(FH);
1.1051 raeburn 3496: if ($resizewidth && $resizeheight) {
3497: my $mm = new File::MMagic;
3498: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3499: if ($mime_type =~ m{^image/}) {
3500: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3501: }
1.977 amueller 3502: }
1.258 www 3503: }
1.1152 raeburn 3504: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3505: if (ref($mimetype)) {
3506: if ($$mimetype eq '') {
3507: my $mm = new File::MMagic;
3508: my $type = $mm->checktype_filename($filepath.'/'.$file);
3509: $$mimetype = $type;
3510: }
3511: }
3512: }
1.637 raeburn 3513: if ($parser eq 'parse') {
1.1152 raeburn 3514: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3515: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3516: $allfiles,$codebase);
3517: unless ($parse_result eq 'ok') {
3518: &logthis('Failed to parse '.$filepath.$file.
3519: ' for embedded media: '.$parse_result);
3520: }
1.637 raeburn 3521: }
3522: }
1.860 raeburn 3523: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3524: my $input = $filepath.'/'.$file;
3525: my $output = $filepath.'/'.'tn-'.$file;
3526: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3527: system("convert -sample $thumbsize $input $output");
3528: if (-e $filepath.'/'.'tn-'.$file) {
3529: $fetchthumb = 1;
3530: }
3531: }
1.858 raeburn 3532:
1.259 www 3533: # Notify homeserver to grep it
3534: #
1.984 neumanie 3535: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3536: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3537: if ($fetchresult eq 'ok') {
1.860 raeburn 3538: if ($fetchthumb) {
3539: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3540: if ($thumbresult ne 'ok') {
3541: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3542: $docuhome.': '.$thumbresult);
3543: }
3544: }
1.259 www 3545: #
1.258 www 3546: # Return the URL to it
1.494 albertel 3547: return '/uploaded/'.$path.$file;
1.263 www 3548: } else {
1.494 albertel 3549: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3550: ': '.$fetchresult);
1.263 www 3551: return '/adm/notfound.html';
1.858 raeburn 3552: }
1.493 albertel 3553: }
3554:
1.637 raeburn 3555: sub extract_embedded_items {
1.961 raeburn 3556: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3557: my @state = ();
1.1164 raeburn 3558: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3559: my %javafiles = (
3560: codebase => '',
3561: code => '',
3562: archive => ''
3563: );
3564: my %mediafiles = (
3565: src => '',
3566: movie => '',
3567: );
1.648 raeburn 3568: my $p;
3569: if ($content) {
3570: $p = HTML::LCParser->new($content);
3571: } else {
1.961 raeburn 3572: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3573: }
1.641 albertel 3574: while (my $t=$p->get_token()) {
1.640 albertel 3575: if ($t->[0] eq 'S') {
3576: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3577: push(@state, $tagname);
1.648 raeburn 3578: if (lc($tagname) eq 'allow') {
3579: &add_filetype($allfiles,$attr->{'src'},'src');
3580: }
1.640 albertel 3581: if (lc($tagname) eq 'img') {
3582: &add_filetype($allfiles,$attr->{'src'},'src');
3583: }
1.886 albertel 3584: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3585: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3586: &add_filetype($allfiles,$attr->{'href'},'href');
3587: }
1.886 albertel 3588: }
1.645 raeburn 3589: if (lc($tagname) eq 'script') {
1.1164 raeburn 3590: my $src;
1.645 raeburn 3591: if ($attr->{'archive'} =~ /\.jar$/i) {
3592: &add_filetype($allfiles,$attr->{'archive'},'archive');
3593: } else {
1.1164 raeburn 3594: if ($attr->{'src'} ne '') {
3595: $src = $attr->{'src'};
3596: &add_filetype($allfiles,$src,'src');
3597: }
3598: }
3599: my $text = $p->get_trimmed_text();
3600: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3601: my @swfargs = split(/,/,$1);
3602: foreach my $item (@swfargs) {
3603: $item =~ s/["']//g;
3604: $item =~ s/^\s+//;
3605: $item =~ s/\s+$//;
3606: }
3607: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3608: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3609: push(@{$related{$swfargs[0]}},$swfargs[2]);
3610: } else {
3611: $related{$swfargs[0]} = [$swfargs[2]];
3612: }
3613: }
1.645 raeburn 3614: }
3615: }
3616: if (lc($tagname) eq 'link') {
3617: if (lc($attr->{'rel'}) eq 'stylesheet') {
3618: &add_filetype($allfiles,$attr->{'href'},'href');
3619: }
3620: }
1.640 albertel 3621: if (lc($tagname) eq 'object' ||
3622: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3623: foreach my $item (keys(%javafiles)) {
3624: $javafiles{$item} = '';
3625: }
1.1164 raeburn 3626: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3627: $lastids{lc($tagname)} = $attr->{'id'};
3628: }
1.640 albertel 3629: }
3630: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3631: my $name = lc($attr->{'name'});
3632: foreach my $item (keys(%javafiles)) {
3633: if ($name eq $item) {
3634: $javafiles{$item} = $attr->{'value'};
3635: last;
3636: }
3637: }
1.1164 raeburn 3638: my $pathfrom;
1.640 albertel 3639: foreach my $item (keys(%mediafiles)) {
3640: if ($name eq $item) {
1.1164 raeburn 3641: $pathfrom = $attr->{'value'};
3642: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3643: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3644: last;
3645: }
3646: }
1.1164 raeburn 3647: if ($name eq 'flashvars') {
3648: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3649: }
3650: if ($pathfrom ne '') {
3651: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3652: $pathfrom);
3653: }
1.640 albertel 3654: }
3655: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3656: foreach my $item (keys(%javafiles)) {
3657: if ($attr->{$item}) {
3658: $javafiles{$item} = $attr->{$item};
3659: last;
3660: }
3661: }
3662: foreach my $item (keys(%mediafiles)) {
3663: if ($attr->{$item}) {
3664: &add_filetype($allfiles,$attr->{$item},$item);
3665: last;
3666: }
3667: }
1.1164 raeburn 3668: if (lc($tagname) eq 'embed') {
3669: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3670: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3671: $attr->{'src'});
3672: }
3673: }
1.640 albertel 3674: }
1.1172.2.35 raeburn 3675: if (lc($tagname) eq 'iframe') {
3676: my $src = $attr->{'src'} ;
3677: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3678: &add_filetype($allfiles,$src,'src');
3679: } elsif ($src =~ m{^/}) {
3680: if ($env{'request.course.id'}) {
3681: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3682: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3683: my $url = &hreflocation('',$fullpath);
3684: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3685: my $relpath = $1;
3686: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3687: &add_filetype($allfiles,$1,'src');
3688: }
3689: }
3690: }
3691: }
3692: }
1.1164 raeburn 3693: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3694: pop(@state);
1.1164 raeburn 3695: }
1.640 albertel 3696: } elsif ($t->[0] eq 'E') {
3697: my ($tagname) = ($t->[1]);
3698: if ($javafiles{'codebase'} ne '') {
3699: $javafiles{'codebase'} .= '/';
3700: }
3701: if (lc($tagname) eq 'applet' ||
3702: lc($tagname) eq 'object' ||
3703: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3704: ) {
3705: foreach my $item (keys(%javafiles)) {
3706: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3707: my $file=$javafiles{'codebase'}.$javafiles{$item};
3708: &add_filetype($allfiles,$file,$item);
3709: }
3710: }
3711: }
3712: pop @state;
3713: }
3714: }
1.1164 raeburn 3715: foreach my $id (sort(keys(%flashvars))) {
3716: if ($shockwave{$id} ne '') {
3717: my @pairs = split(/\&/,$flashvars{$id});
3718: foreach my $pair (@pairs) {
3719: my ($key,$value) = split(/\=/,$pair);
3720: if ($key eq 'thumb') {
3721: &add_filetype($allfiles,$value,$key);
3722: } elsif ($key eq 'content') {
3723: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3724: my ($ext) = ($value =~ /\.([^.]+)$/);
3725: if ($ext ne '') {
3726: &add_filetype($allfiles,$path.$value,$ext);
3727: }
3728: }
3729: }
3730: }
3731: }
1.637 raeburn 3732: return 'ok';
3733: }
3734:
1.639 albertel 3735: sub add_filetype {
3736: my ($allfiles,$file,$type)=@_;
3737: if (exists($allfiles->{$file})) {
3738: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3739: push(@{$allfiles->{$file}}, &escape($type));
3740: }
3741: } else {
3742: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3743: }
3744: }
3745:
1.1164 raeburn 3746: sub embedded_dependency {
3747: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3748: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3749: if (($identifier ne '') &&
3750: (ref($related->{$identifier}) eq 'ARRAY') &&
3751: ($pathfrom ne '')) {
3752: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3753: foreach my $dep (@{$related->{$identifier}}) {
3754: &add_filetype($allfiles,$path.$dep,'object');
3755: }
3756: }
3757: }
3758: return;
3759: }
3760:
1.493 albertel 3761: sub removeuploadedurl {
1.984 neumanie 3762: my ($url)=@_;
3763: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3764: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3765: }
3766:
3767: sub removeuserfile {
3768: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3769: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3770: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3771: if ($result eq 'ok') {
1.798 raeburn 3772: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3773: my $metafile = $fname.'.meta';
3774: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3775: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3776: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3777: my $sqlresult =
1.823 albertel 3778: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3779: 'portfolio_metadata',$group,
3780: 'delete');
1.798 raeburn 3781: }
3782: }
3783: return $result;
1.257 www 3784: }
1.15 www 3785:
1.530 albertel 3786: sub mkdiruserfile {
3787: my ($docuname,$docudom,$dir)=@_;
3788: my $home=&homeserver($docuname,$docudom);
3789: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3790: }
3791:
1.531 albertel 3792: sub renameuserfile {
3793: my ($docuname,$docudom,$old,$new)=@_;
3794: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3795: my $result = &reply("renameuserfile:$docudom:$docuname:".
3796: &escape("$old").':'.&escape("$new"),$home);
3797: if ($result eq 'ok') {
3798: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3799: my $oldmeta = $old.'.meta';
3800: my $newmeta = $new.'.meta';
3801: my $metaresult =
3802: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3803: my $url = "/uploaded/$docudom/$docuname/$old";
3804: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3805: my $sqlresult =
1.823 albertel 3806: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3807: 'portfolio_metadata',$group,
3808: 'delete');
1.798 raeburn 3809: }
3810: }
3811: return $result;
1.531 albertel 3812: }
3813:
1.14 www 3814: # ------------------------------------------------------------------------- Log
3815:
3816: sub log {
3817: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3818: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3819: }
3820:
3821: # ------------------------------------------------------------------ Course Log
1.352 www 3822: #
3823: # This routine flushes several buffers of non-mission-critical nature
3824: #
1.157 www 3825:
3826: sub flushcourselogs {
1.352 www 3827: &logthis('Flushing log buffers');
3828: #
3829: # course logs
3830: # This is a log of all transactions in a course, which can be used
3831: # for data mining purposes
3832: #
3833: # It also collects the courseid database, which lists last transaction
3834: # times and course titles for all courseids
3835: #
3836: my %courseidbuffer=();
1.921 raeburn 3837: foreach my $crsid (keys(%courselogs)) {
1.352 www 3838: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3839: &escape($courselogs{$crsid}),
3840: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3841: delete $courselogs{$crsid};
3842: } else {
3843: &logthis('Failed to flush log buffer for '.$crsid);
3844: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3845: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3846: " exceeded maximum size, deleting.</font>");
3847: delete $courselogs{$crsid};
3848: }
1.352 www 3849: }
1.920 raeburn 3850: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3851: 'description' => $coursedescrbuf{$crsid},
3852: 'inst_code' => $courseinstcodebuf{$crsid},
3853: 'type' => $coursetypebuf{$crsid},
3854: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3855: };
1.191 harris41 3856: }
1.352 www 3857: #
3858: # Write course id database (reverse lookup) to homeserver of courses
3859: # Is used in pickcourse
3860: #
1.840 albertel 3861: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3862: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3863: $courseidbuffer{$crs_home},
3864: $crs_home,'timeonly');
1.352 www 3865: }
3866: #
3867: # File accesses
3868: # Writes to the dynamic metadata of resources to get hit counts, etc.
3869: #
1.449 matthew 3870: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3871: if ($entry =~ /___count$/) {
3872: my ($dom,$name);
1.807 albertel 3873: ($dom,$name,undef)=
1.811 albertel 3874: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3875: if (! defined($dom) || $dom eq '' ||
3876: ! defined($name) || $name eq '') {
1.620 albertel 3877: my $cid = $env{'request.course.id'};
3878: $dom = $env{'request.'.$cid.'.domain'};
3879: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3880: }
1.450 matthew 3881: my $value = $accesshash{$entry};
3882: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3883: my %temphash=($url => $value);
1.449 matthew 3884: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3885: if ($result eq 'ok') {
3886: delete $accesshash{$entry};
3887: }
3888: } else {
1.811 albertel 3889: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3890: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3891: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3892: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3893: delete $accesshash{$entry};
3894: }
1.185 www 3895: }
1.191 harris41 3896: }
1.352 www 3897: #
3898: # Roles
3899: # Reverse lookup of user roles for course faculty/staff and co-authorship
3900: #
1.800 albertel 3901: foreach my $entry (keys(%userrolehash)) {
1.351 www 3902: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3903: split(/\:/,$entry);
3904: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3905: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3906: $rudom,$runame) eq 'ok') {
3907: delete $userrolehash{$entry};
3908: }
3909: }
1.662 raeburn 3910: #
3911: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3912: #
3913: my %domrolebuffer = ();
1.1000 raeburn 3914: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3915: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3916: if ($domrolebuffer{$rudom}) {
3917: $domrolebuffer{$rudom}.='&'.&escape($entry).
3918: '='.&escape($domainrolehash{$entry});
3919: } else {
3920: $domrolebuffer{$rudom}.=&escape($entry).
3921: '='.&escape($domainrolehash{$entry});
3922: }
3923: delete $domainrolehash{$entry};
3924: }
3925: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82! raeburn 3926: my %servers;
! 3927: if (defined(&domain($dom,'primary'))) {
! 3928: my $primary=&domain($dom,'primary');
! 3929: my $hostname=&hostname($primary);
! 3930: $servers{$primary} = $hostname;
! 3931: } else {
! 3932: %servers = &get_servers($dom,'library');
! 3933: }
1.841 albertel 3934: foreach my $tryserver (keys(%servers)) {
1.1172.2.82! raeburn 3935: if (&reply('domroleput:'.$dom.':'.
! 3936: $domrolebuffer{$dom},$tryserver) eq 'ok') {
! 3937: last;
! 3938: } else {
1.841 albertel 3939: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3940: }
1.662 raeburn 3941: }
3942: }
1.186 www 3943: $dumpcount++;
1.157 www 3944: }
3945:
3946: sub courselog {
3947: my $what=shift;
1.158 www 3948: $what=time.':'.$what;
1.620 albertel 3949: unless ($env{'request.course.id'}) { return ''; }
3950: $coursedombuf{$env{'request.course.id'}}=
3951: $env{'course.'.$env{'request.course.id'}.'.domain'};
3952: $coursenumbuf{$env{'request.course.id'}}=
3953: $env{'course.'.$env{'request.course.id'}.'.num'};
3954: $coursehombuf{$env{'request.course.id'}}=
3955: $env{'course.'.$env{'request.course.id'}.'.home'};
3956: $coursedescrbuf{$env{'request.course.id'}}=
3957: $env{'course.'.$env{'request.course.id'}.'.description'};
3958: $courseinstcodebuf{$env{'request.course.id'}}=
3959: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3960: $courseownerbuf{$env{'request.course.id'}}=
3961: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3962: $coursetypebuf{$env{'request.course.id'}}=
3963: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3964: if (defined $courselogs{$env{'request.course.id'}}) {
3965: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3966: } else {
1.620 albertel 3967: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3968: }
1.620 albertel 3969: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3970: &flushcourselogs();
3971: }
1.158 www 3972: }
3973:
3974: sub courseacclog {
3975: my $fnsymb=shift;
1.620 albertel 3976: unless ($env{'request.course.id'}) { return ''; }
3977: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3978: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3979: $what.=':POST';
1.583 matthew 3980: # FIXME: Probably ought to escape things....
1.800 albertel 3981: foreach my $key (keys(%env)) {
3982: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3983: my $formitem = $1;
3984: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3985: $what.=':'.$formitem.'='.$env{$key};
3986: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3987: $what.=':'.$formitem.'='.$env{$key};
3988: }
1.158 www 3989: }
1.191 harris41 3990: }
1.583 matthew 3991: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3992: # FIXME: We should not be depending on a form parameter that someone
3993: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3994: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3995: $what.= ':POST';
3996: # FIXME: Probably ought to escape things....
3997: foreach my $element ('courseexp','crsfulltext','crsrelated',
3998: 'crsdiscuss') {
1.620 albertel 3999: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4000: }
4001: }
1.158 www 4002: }
4003: &courselog($what);
1.149 www 4004: }
4005:
1.185 www 4006: sub countacc {
4007: my $url=&declutter(shift);
1.458 matthew 4008: return if (! defined($url) || $url eq '');
1.620 albertel 4009: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4010: #
4011: # Mark that this url was used in this course
4012: #
1.620 albertel 4013: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4014: #
4015: # Increase the access count for this resource in this child process
4016: #
1.281 www 4017: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4018: $accesshash{$key}++;
1.185 www 4019: }
1.349 www 4020:
1.361 www 4021: sub linklog {
4022: my ($from,$to)=@_;
4023: $from=&declutter($from);
4024: $to=&declutter($to);
4025: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4026: $accesshash{$to.'___'.$from.'___goto'}=1;
4027: }
1.1160 www 4028:
4029: sub statslog {
4030: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4031: if ($users<2) { return; }
4032: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4033: 'course' => $env{'request.course.id'},
4034: 'sections' => '"all"',
4035: 'num_students' => $users,
4036: 'part' => $part,
4037: 'symb' => $symb,
4038: 'mean_tries' => $av_attempts,
4039: 'deg_of_diff' => $degdiff});
4040: foreach my $key (keys(%dynstore)) {
4041: $accesshash{$key}=$dynstore{$key};
4042: }
4043: }
1.361 www 4044:
1.349 www 4045: sub userrolelog {
4046: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4047: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4048: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4049: $userrolehash
4050: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4051: =$tend.':'.$tstart;
1.662 raeburn 4052: }
1.1169 droeschl 4053: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4054: $userrolehash
4055: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4056: =$tend.':'.$tstart;
4057: }
1.1169 droeschl 4058: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4059: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4060: $domainrolehash
4061: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4062: = $tend.':'.$tstart;
4063: }
1.351 www 4064: }
4065:
1.957 raeburn 4066: sub courserolelog {
4067: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4068: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4069: my $cdom = $1;
4070: my $cnum = $2;
4071: my $sec = $3;
4072: my $namespace = 'rolelog';
4073: my %storehash = (
4074: role => $trole,
4075: start => $tstart,
4076: end => $tend,
4077: selfenroll => $selfenroll,
4078: context => $context,
4079: );
4080: if ($trole eq 'gr') {
4081: $namespace = 'groupslog';
4082: $storehash{'group'} = $sec;
4083: } else {
4084: $storehash{'section'} = $sec;
4085: }
4086: &write_log('course',$namespace,\%storehash,$delflag,$username,
4087: $domain,$cnum,$cdom);
4088: if (($trole ne 'st') || ($sec ne '')) {
4089: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4090: }
4091: }
4092: return;
4093: }
4094:
1.1172.2.9 raeburn 4095: sub domainrolelog {
4096: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4097: if ($area =~ m{^/($match_domain)/$}) {
4098: my $cdom = $1;
4099: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4100: my $namespace = 'rolelog';
4101: my %storehash = (
4102: role => $trole,
4103: start => $tstart,
4104: end => $tend,
4105: context => $context,
4106: );
4107: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4108: $domain,$domconfiguser,$cdom);
4109: }
4110: return;
4111:
4112: }
4113:
4114: sub coauthorrolelog {
4115: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4116: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4117: my $audom = $1;
4118: my $auname = $2;
4119: my $namespace = 'rolelog';
4120: my %storehash = (
4121: role => $trole,
4122: start => $tstart,
4123: end => $tend,
4124: context => $context,
4125: );
4126: &write_log('author',$namespace,\%storehash,$delflag,$username,
4127: $domain,$auname,$audom);
4128: }
4129: return;
4130: }
4131:
1.351 www 4132: sub get_course_adv_roles {
1.948 raeburn 4133: my ($cid,$codes) = @_;
1.620 albertel 4134: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4135: my %coursehash=&coursedescription($cid);
1.988 raeburn 4136: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4137: my %nothide=();
1.800 albertel 4138: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4139: if ($user !~ /:/) {
4140: $nothide{join(':',split(/[\@]/,$user))}=1;
4141: } else {
4142: $nothide{$user}=1;
4143: }
1.470 www 4144: }
1.1172.2.23 raeburn 4145: my @possdoms = ($coursehash{'domain'});
4146: if ($coursehash{'checkforpriv'}) {
4147: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4148: }
1.351 www 4149: my %returnhash=();
4150: my %dumphash=
4151: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4152: my $now=time;
1.997 raeburn 4153: my %privileged;
1.1000 raeburn 4154: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4155: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4156: if (($tstart) && ($tstart<0)) { next; }
4157: if (($tend) && ($tend<$now)) { next; }
4158: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4159: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4160: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4161: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4162: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4163: if ($role eq 'cr') { next; }
1.948 raeburn 4164: if ($codes) {
4165: if ($section) { $role .= ':'.$section; }
4166: if ($returnhash{$role}) {
4167: $returnhash{$role}.=','.$username.':'.$domain;
4168: } else {
4169: $returnhash{$role}=$username.':'.$domain;
4170: }
1.351 www 4171: } else {
1.988 raeburn 4172: my $key=&plaintext($role,$crstype);
1.973 bisitz 4173: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4174: if ($returnhash{$key}) {
4175: $returnhash{$key}.=','.$username.':'.$domain;
4176: } else {
4177: $returnhash{$key}=$username.':'.$domain;
4178: }
1.351 www 4179: }
1.948 raeburn 4180: }
1.400 www 4181: return %returnhash;
4182: }
4183:
4184: sub get_my_roles {
1.937 raeburn 4185: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4186: unless (defined($uname)) { $uname=$env{'user.name'}; }
4187: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4188: my (%dumphash,%nothide);
1.1086 raeburn 4189: if ($context eq 'userroles') {
1.1166 raeburn 4190: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4191: } else {
1.1172.2.23 raeburn 4192: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4193: if ($hidepriv) {
4194: my %coursehash=&coursedescription($udom.'_'.$uname);
4195: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4196: if ($user !~ /:/) {
4197: $nothide{join(':',split(/[\@]/,$user))} = 1;
4198: } else {
4199: $nothide{$user} = 1;
4200: }
4201: }
4202: }
1.858 raeburn 4203: }
1.400 www 4204: my %returnhash=();
4205: my $now=time;
1.999 raeburn 4206: my %privileged;
1.800 albertel 4207: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4208: my ($role,$tend,$tstart);
4209: if ($context eq 'userroles') {
1.1149 raeburn 4210: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4211: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4212: } else {
4213: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4214: }
1.400 www 4215: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4216: my $status = 'active';
1.939 raeburn 4217: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4218: $status = 'previous';
4219: }
4220: if (($tstart) && ($now<$tstart)) {
4221: $status = 'future';
4222: }
4223: if (ref($types) eq 'ARRAY') {
4224: if (!grep(/^\Q$status\E$/,@{$types})) {
4225: next;
4226: }
4227: } else {
4228: if ($status ne 'active') {
4229: next;
4230: }
4231: }
1.867 raeburn 4232: my ($rolecode,$username,$domain,$section,$area);
4233: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4234: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4235: (undef,$domain,$username,$section) = split(/\//,$area);
4236: } else {
4237: ($role,$username,$domain,$section) = split(/\:/,$entry);
4238: }
1.832 raeburn 4239: if (ref($roledoms) eq 'ARRAY') {
4240: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4241: next;
4242: }
4243: }
4244: if (ref($roles) eq 'ARRAY') {
4245: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4246: if ($role =~ /^cr\//) {
4247: if (!grep(/^cr$/,@{$roles})) {
4248: next;
4249: }
1.1104 raeburn 4250: } elsif ($role =~ /^gr\//) {
4251: if (!grep(/^gr$/,@{$roles})) {
4252: next;
4253: }
1.922 raeburn 4254: } else {
4255: next;
4256: }
1.832 raeburn 4257: }
1.867 raeburn 4258: }
1.937 raeburn 4259: if ($hidepriv) {
1.1172.2.23 raeburn 4260: my @privroles = ('dc','su');
1.999 raeburn 4261: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4262: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4263: } else {
1.1172.2.23 raeburn 4264: my $possdoms = [$domain];
4265: if (ref($roledoms) eq 'ARRAY') {
4266: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4267: }
1.1172.2.23 raeburn 4268: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4269: if (!$nothide{$username.':'.$domain}) {
4270: next;
4271: }
4272: }
1.937 raeburn 4273: }
4274: }
1.933 raeburn 4275: if ($withsec) {
4276: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4277: $tstart.':'.$tend;
4278: } else {
4279: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4280: }
1.832 raeburn 4281: }
1.373 www 4282: return %returnhash;
1.399 www 4283: }
4284:
4285: # ----------------------------------------------------- Frontpage Announcements
4286: #
4287: #
4288:
4289: sub postannounce {
4290: my ($server,$text)=@_;
1.844 albertel 4291: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4292: unless ($text=~/\w/) { $text=''; }
4293: return &reply('setannounce:'.&escape($text),$server);
4294: }
4295:
4296: sub getannounce {
1.448 albertel 4297:
4298: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4299: my $announcement='';
1.800 albertel 4300: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4301: close($fh);
1.399 www 4302: if ($announcement=~/\w/) {
4303: return
4304: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4305: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4306: } else {
4307: return '';
4308: }
4309: } else {
4310: return '';
4311: }
1.351 www 4312: }
1.353 www 4313:
4314: # ---------------------------------------------------------- Course ID routines
4315: # Deal with domain's nohist_courseid.db files
4316: #
4317:
4318: sub courseidput {
1.921 raeburn 4319: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4320: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4321: my $outcome;
4322: if ($caller eq 'timeonly') {
4323: my $cids = '';
4324: foreach my $item (keys(%$storehash)) {
4325: $cids.=&escape($item).'&';
4326: }
4327: $cids=~s/\&$//;
4328: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4329: $coursehome);
4330: } else {
4331: my $items = '';
4332: foreach my $item (keys(%$storehash)) {
4333: $items.= &escape($item).'='.
4334: &freeze_escape($$storehash{$item}).'&';
4335: }
4336: $items=~s/\&$//;
4337: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4338: $coursehome);
1.918 raeburn 4339: }
4340: if ($outcome eq 'unknown_cmd') {
4341: my $what;
4342: foreach my $cid (keys(%$storehash)) {
4343: $what .= &escape($cid).'=';
1.921 raeburn 4344: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4345: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4346: }
4347: $what =~ s/\:$/&/;
4348: }
4349: $what =~ s/\&$//;
4350: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4351: } else {
4352: return $outcome;
4353: }
1.353 www 4354: }
4355:
4356: sub courseiddump {
1.921 raeburn 4357: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4358: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4359: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4360: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4361: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4362: my $as_hash = 1;
4363: my %returnhash;
4364: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4365: my %libserv = &all_library();
4366: foreach my $tryserver (keys(%libserv)) {
4367: if ( ( $hostidflag == 1
4368: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4369: || (!defined($hostidflag)) ) {
4370:
1.918 raeburn 4371: if (($domfilter eq '') ||
4372: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4373: my $rep;
4374: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4375: $rep = &LONCAPA::Lond::dump_course_id_handler(
4376: join(":", (&host_domain($tryserver), $sincefilter,
4377: &escape($descfilter), &escape($instcodefilter),
4378: &escape($ownerfilter), &escape($coursefilter),
4379: &escape($typefilter), &escape($regexp_ok),
4380: $as_hash, &escape($selfenrollonly),
4381: &escape($catfilter), $showhidden, $caller,
4382: &escape($cloner), &escape($cc_clone), $cloneonly,
4383: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4384: &escape($creationcontext),$domcloner,$hasuniquecode,
4385: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4386: } else {
4387: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4388: $sincefilter.':'.&escape($descfilter).':'.
4389: &escape($instcodefilter).':'.&escape($ownerfilter).
4390: ':'.&escape($coursefilter).':'.&escape($typefilter).
4391: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4392: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4393: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4394: &escape($cc_clone).':'.$cloneonly.':'.
4395: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4396: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4397: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4398: }
4399:
1.918 raeburn 4400: my @pairs=split(/\&/,$rep);
4401: foreach my $item (@pairs) {
4402: my ($key,$value)=split(/\=/,$item,2);
4403: $key = &unescape($key);
4404: next if ($key =~ /^error: 2 /);
4405: my $result = &thaw_unescape($value);
4406: if (ref($result) eq 'HASH') {
4407: $returnhash{$key}=$result;
4408: } else {
1.921 raeburn 4409: my @responses = split(/:/,$value);
4410: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4411: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4412: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4413: }
1.1008 raeburn 4414: }
1.353 www 4415: }
4416: }
4417: }
4418: }
4419: return %returnhash;
4420: }
4421:
1.1055 raeburn 4422: sub courselastaccess {
4423: my ($cdom,$cnum,$hostidref) = @_;
4424: my %returnhash;
4425: if ($cdom && $cnum) {
4426: my $chome = &homeserver($cnum,$cdom);
4427: if ($chome ne 'no_host') {
4428: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4429: &extract_lastaccess(\%returnhash,$rep);
4430: }
4431: } else {
4432: if (!$cdom) { $cdom=''; }
4433: my %libserv = &all_library();
4434: foreach my $tryserver (keys(%libserv)) {
4435: if (ref($hostidref) eq 'ARRAY') {
4436: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4437: }
4438: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4439: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4440: &extract_lastaccess(\%returnhash,$rep);
4441: }
4442: }
4443: }
4444: return %returnhash;
4445: }
4446:
4447: sub extract_lastaccess {
4448: my ($returnhash,$rep) = @_;
4449: if (ref($returnhash) eq 'HASH') {
4450: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4451: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4452: $rep eq '') {
4453: my @pairs=split(/\&/,$rep);
4454: foreach my $item (@pairs) {
4455: my ($key,$value)=split(/\=/,$item,2);
4456: $key = &unescape($key);
4457: next if ($key =~ /^error: 2 /);
4458: $returnhash->{$key} = &thaw_unescape($value);
4459: }
4460: }
4461: }
4462: return;
4463: }
4464:
1.658 raeburn 4465: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4466:
4467: sub dcmailput {
1.685 raeburn 4468: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4469: my $status = &Apache::lonnet::critical(
1.740 www 4470: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4471: &escape($message),$server);
1.662 raeburn 4472: return $status;
4473: }
4474:
1.658 raeburn 4475: sub dcmaildump {
4476: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4477: my %returnhash=();
1.846 albertel 4478:
4479: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4480: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4481: &escape($enddate).':';
4482: my @esc_senders=map { &escape($_)} @$senders;
4483: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4484: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4485: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4486: if (($key) && ($value)) {
4487: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4488: }
4489: }
4490: }
4491: return %returnhash;
4492: }
1.662 raeburn 4493: # ---------------------------------------------------------- Domain roles
4494:
4495: sub get_domain_roles {
4496: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4497: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4498: $startdate = '.';
4499: }
1.1018 raeburn 4500: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4501: $enddate = '.';
4502: }
1.922 raeburn 4503: my $rolelist;
4504: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4505: $rolelist = join('&',@{$roles});
1.922 raeburn 4506: }
1.662 raeburn 4507: my %personnel = ();
1.841 albertel 4508:
4509: my %servers = &get_servers($dom,'library');
4510: foreach my $tryserver (keys(%servers)) {
4511: %{$personnel{$tryserver}}=();
4512: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4513: &escape($startdate).':'.
4514: &escape($enddate).':'.
4515: &escape($rolelist), $tryserver))) {
4516: my ($key,$value) = split(/\=/,$line,2);
4517: if (($key) && ($value)) {
4518: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4519: }
4520: }
1.662 raeburn 4521: }
4522: return %personnel;
4523: }
1.658 raeburn 4524:
1.1057 www 4525: # ----------------------------------------------------------- Interval timing
1.149 www 4526:
1.1153 www 4527: {
4528: # Caches needed for speedup of navmaps
4529: # We don't want to cache this for very long at all (5 seconds at most)
4530: #
4531: # The user for whom we cache
4532: my $cachedkey='';
4533: # The cached times for this user
4534: my %cachedtimes=();
4535: # When this was last done
1.1172.2.66 raeburn 4536: my $cachedtime='';
1.1153 www 4537:
4538: sub load_all_first_access {
1.1154 raeburn 4539: my ($uname,$udom)=@_;
1.1156 www 4540: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4541: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4542: return;
4543: }
4544: $cachedtime=time;
4545: $cachedkey=$uname.':'.$udom;
4546: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4547: }
4548:
1.504 albertel 4549: sub get_first_access {
1.1162 raeburn 4550: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4551: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4552: if ($argsymb) { $symb=$argsymb; }
4553: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4554: if ($argmap) { $map = $argmap; }
1.926 albertel 4555: if ($type eq 'course') {
4556: $res='course';
4557: } elsif ($type eq 'map') {
1.588 albertel 4558: $res=&symbread($map);
4559: } else {
4560: $res=$symb;
4561: }
1.1153 www 4562: &load_all_first_access($uname,$udom);
4563: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4564: }
4565:
4566: sub set_first_access {
1.1162 raeburn 4567: my ($type,$interval)=@_;
1.790 albertel 4568: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4569: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4570: if ($type eq 'course') {
4571: $res='course';
4572: } elsif ($type eq 'map') {
1.588 albertel 4573: $res=&symbread($map);
4574: } else {
4575: $res=$symb;
4576: }
1.1153 www 4577: $cachedkey='';
1.1162 raeburn 4578: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4579: if (!$firstaccess) {
1.1162 raeburn 4580: my $start = time;
4581: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4582: $udom,$uname);
4583: if ($putres eq 'ok') {
4584: &put('timerinterval',{"$courseid\0$res"=>$interval},
4585: $udom,$uname);
4586: &appenv(
4587: {
4588: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4589: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4590: }
4591: );
4592: }
4593: return $putres;
1.505 albertel 4594: }
4595: return 'already_set';
1.504 albertel 4596: }
1.1153 www 4597: }
1.1172.2.32 raeburn 4598:
4599: sub checkout {
4600: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4601: my $now=time;
4602: my $lonhost=$perlvar{'lonHostID'};
4603: my $infostr=&escape(
4604: 'CHECKOUTTOKEN&'.
4605: $tuname.'&'.
4606: $tudom.'&'.
4607: $tcrsid.'&'.
4608: $symb.'&'.
4609: $now.'&'.$ENV{'REMOTE_ADDR'});
4610: my $token=&reply('tmpput:'.$infostr,$lonhost);
4611: if ($token=~/^error\:/) {
4612: &logthis("<font color=\"blue\">WARNING: ".
4613: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4614: "</font>");
4615: return '';
4616: }
4617:
4618: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4619: $token=~tr/a-z/A-Z/;
4620:
4621: my %infohash=('resource.0.outtoken' => $token,
4622: 'resource.0.checkouttime' => $now,
4623: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4624:
4625: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4626: return '';
4627: } else {
4628: &logthis("<font color=\"blue\">WARNING: ".
4629: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4630: "</font>");
4631: }
4632:
4633: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4634: &escape('Checkout '.$infostr.' - '.
4635: $token)) ne 'ok') {
4636: return '';
4637: } else {
4638: &logthis("<font color=\"blue\">WARNING: ".
4639: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4640: "</font>");
4641: }
4642: return $token;
4643: }
4644:
4645: # ------------------------------------------------------------ Check in an item
4646:
4647: sub checkin {
4648: my $token=shift;
4649: my $now=time;
4650: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4651: $lonhost=~tr/A-Z/a-z/;
4652: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4653: $dtoken=~s/\W/\_/g;
4654: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4655: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4656:
4657: unless (($tuname) && ($tudom)) {
4658: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4659: return '';
4660: }
4661:
4662: unless (&allowed('mgr',$tcrsid)) {
4663: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4664: $env{'user.name'}.' - '.$env{'user.domain'});
4665: return '';
4666: }
4667:
4668: my %infohash=('resource.0.intoken' => $token,
4669: 'resource.0.checkintime' => $now,
4670: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4671:
4672: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4673: return '';
4674: }
4675:
4676: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4677: &escape('Checkin - '.$token)) ne 'ok') {
4678: return '';
4679: }
4680:
4681: return ($symb,$tuname,$tudom,$tcrsid);
4682: }
4683:
1.110 www 4684: # --------------------------------------------- Set Expire Date for Spreadsheet
4685:
4686: sub expirespread {
4687: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4688: my $cid=$env{'request.course.id'};
1.110 www 4689: if ($cid) {
4690: my $now=time;
4691: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4692: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4693: $env{'course.'.$cid.'.num'}.
1.110 www 4694: ':nohist_expirationdates:'.
4695: &escape($key).'='.$now,
1.620 albertel 4696: $env{'course.'.$cid.'.home'})
1.110 www 4697: }
4698: return 'ok';
1.14 www 4699: }
4700:
1.109 www 4701: # ----------------------------------------------------- Devalidate Spreadsheets
4702:
4703: sub devalidate {
1.325 www 4704: my ($symb,$uname,$udom)=@_;
1.620 albertel 4705: my $cid=$env{'request.course.id'};
1.109 www 4706: if ($cid) {
1.391 matthew 4707: # delete the stored spreadsheets for
4708: # - the student level sheet of this user in course's homespace
4709: # - the assessment level sheet for this resource
4710: # for this user in user's homespace
1.553 albertel 4711: # - current conditional state info
1.325 www 4712: my $key=$uname.':'.$udom.':';
1.109 www 4713: my $status=
1.299 matthew 4714: &del('nohist_calculatedsheets',
1.391 matthew 4715: [$key.'studentcalc:'],
1.620 albertel 4716: $env{'course.'.$cid.'.domain'},
4717: $env{'course.'.$cid.'.num'})
1.133 albertel 4718: .' '.
4719: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4720: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4721: unless ($status eq 'ok ok') {
4722: &logthis('Could not devalidate spreadsheet '.
1.325 www 4723: $uname.' at '.$udom.' for '.
1.109 www 4724: $symb.': '.$status);
1.133 albertel 4725: }
1.553 albertel 4726: &delenv('user.state.'.$cid);
1.109 www 4727: }
4728: }
4729:
1.265 albertel 4730: sub get_scalar {
4731: my ($string,$end) = @_;
4732: my $value;
4733: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4734: $value = $1;
4735: } elsif ($$string =~ s/^([^&]*?)&//) {
4736: $value = $1;
4737: }
4738: return &unescape($value);
4739: }
4740:
4741: sub array2str {
4742: my (@array) = @_;
4743: my $result=&arrayref2str(\@array);
4744: $result=~s/^__ARRAY_REF__//;
4745: $result=~s/__END_ARRAY_REF__$//;
4746: return $result;
4747: }
4748:
1.204 albertel 4749: sub arrayref2str {
4750: my ($arrayref) = @_;
1.265 albertel 4751: my $result='__ARRAY_REF__';
1.204 albertel 4752: foreach my $elem (@$arrayref) {
1.265 albertel 4753: if(ref($elem) eq 'ARRAY') {
4754: $result.=&arrayref2str($elem).'&';
4755: } elsif(ref($elem) eq 'HASH') {
4756: $result.=&hashref2str($elem).'&';
4757: } elsif(ref($elem)) {
4758: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4759: } else {
4760: $result.=&escape($elem).'&';
4761: }
4762: }
4763: $result=~s/\&$//;
1.265 albertel 4764: $result .= '__END_ARRAY_REF__';
1.204 albertel 4765: return $result;
4766: }
4767:
1.168 albertel 4768: sub hash2str {
1.204 albertel 4769: my (%hash) = @_;
4770: my $result=&hashref2str(\%hash);
1.265 albertel 4771: $result=~s/^__HASH_REF__//;
4772: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4773: return $result;
4774: }
4775:
4776: sub hashref2str {
4777: my ($hashref)=@_;
1.265 albertel 4778: my $result='__HASH_REF__';
1.800 albertel 4779: foreach my $key (sort(keys(%$hashref))) {
4780: if (ref($key) eq 'ARRAY') {
4781: $result.=&arrayref2str($key).'=';
4782: } elsif (ref($key) eq 'HASH') {
4783: $result.=&hashref2str($key).'=';
4784: } elsif (ref($key)) {
1.265 albertel 4785: $result.='=';
1.800 albertel 4786: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4787: } else {
1.1132 raeburn 4788: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4789: }
4790:
1.800 albertel 4791: if(ref($hashref->{$key}) eq 'ARRAY') {
4792: $result.=&arrayref2str($hashref->{$key}).'&';
4793: } elsif(ref($hashref->{$key}) eq 'HASH') {
4794: $result.=&hashref2str($hashref->{$key}).'&';
4795: } elsif(ref($hashref->{$key})) {
1.265 albertel 4796: $result.='&';
1.800 albertel 4797: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4798: } else {
1.800 albertel 4799: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4800: }
4801: }
1.168 albertel 4802: $result=~s/\&$//;
1.265 albertel 4803: $result .= '__END_HASH_REF__';
1.168 albertel 4804: return $result;
4805: }
4806:
4807: sub str2hash {
1.265 albertel 4808: my ($string)=@_;
4809: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4810: return %$hash;
4811: }
4812:
4813: sub str2hashref {
1.168 albertel 4814: my ($string) = @_;
1.265 albertel 4815:
4816: my %hash;
4817:
4818: if($string !~ /^__HASH_REF__/) {
4819: if (! ($string eq '' || !defined($string))) {
4820: $hash{'error'}='Not hash reference';
4821: }
4822: return (\%hash, $string);
4823: }
4824:
4825: $string =~ s/^__HASH_REF__//;
4826:
4827: while($string !~ /^__END_HASH_REF__/) {
4828: #key
4829: my $key='';
4830: if($string =~ /^__HASH_REF__/) {
4831: ($key, $string)=&str2hashref($string);
4832: if(defined($key->{'error'})) {
4833: $hash{'error'}='Bad data';
4834: return (\%hash, $string);
4835: }
4836: } elsif($string =~ /^__ARRAY_REF__/) {
4837: ($key, $string)=&str2arrayref($string);
4838: if($key->[0] eq 'Array reference error') {
4839: $hash{'error'}='Bad data';
4840: return (\%hash, $string);
4841: }
4842: } else {
4843: $string =~ s/^(.*?)=//;
1.267 albertel 4844: $key=&unescape($1);
1.265 albertel 4845: }
4846: $string =~ s/^=//;
4847:
4848: #value
4849: my $value='';
4850: if($string =~ /^__HASH_REF__/) {
4851: ($value, $string)=&str2hashref($string);
4852: if(defined($value->{'error'})) {
4853: $hash{'error'}='Bad data';
4854: return (\%hash, $string);
4855: }
4856: } elsif($string =~ /^__ARRAY_REF__/) {
4857: ($value, $string)=&str2arrayref($string);
4858: if($value->[0] eq 'Array reference error') {
4859: $hash{'error'}='Bad data';
4860: return (\%hash, $string);
4861: }
4862: } else {
4863: $value=&get_scalar(\$string,'__END_HASH_REF__');
4864: }
4865: $string =~ s/^&//;
4866:
4867: $hash{$key}=$value;
1.204 albertel 4868: }
1.265 albertel 4869:
4870: $string =~ s/^__END_HASH_REF__//;
4871:
4872: return (\%hash, $string);
1.204 albertel 4873: }
4874:
4875: sub str2array {
1.265 albertel 4876: my ($string)=@_;
4877: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4878: return @$array;
4879: }
4880:
4881: sub str2arrayref {
1.204 albertel 4882: my ($string) = @_;
1.265 albertel 4883: my @array;
4884:
4885: if($string !~ /^__ARRAY_REF__/) {
4886: if (! ($string eq '' || !defined($string))) {
4887: $array[0]='Array reference error';
4888: }
4889: return (\@array, $string);
4890: }
4891:
4892: $string =~ s/^__ARRAY_REF__//;
4893:
4894: while($string !~ /^__END_ARRAY_REF__/) {
4895: my $value='';
4896: if($string =~ /^__HASH_REF__/) {
4897: ($value, $string)=&str2hashref($string);
4898: if(defined($value->{'error'})) {
4899: $array[0] ='Array reference error';
4900: return (\@array, $string);
4901: }
4902: } elsif($string =~ /^__ARRAY_REF__/) {
4903: ($value, $string)=&str2arrayref($string);
4904: if($value->[0] eq 'Array reference error') {
4905: $array[0] ='Array reference error';
4906: return (\@array, $string);
4907: }
4908: } else {
4909: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4910: }
4911: $string =~ s/^&//;
4912:
4913: push(@array, $value);
1.191 harris41 4914: }
1.265 albertel 4915:
4916: $string =~ s/^__END_ARRAY_REF__//;
4917:
4918: return (\@array, $string);
1.168 albertel 4919: }
4920:
1.167 albertel 4921: # -------------------------------------------------------------------Temp Store
4922:
1.168 albertel 4923: sub tmpreset {
4924: my ($symb,$namespace,$domain,$stuname) = @_;
4925: if (!$symb) {
4926: $symb=&symbread();
1.620 albertel 4927: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4928: }
4929: $symb=escape($symb);
4930:
1.620 albertel 4931: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4932: $namespace=~s/\//\_/g;
4933: $namespace=~s/\W//g;
4934:
1.620 albertel 4935: if (!$domain) { $domain=$env{'user.domain'}; }
4936: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4937: if ($domain eq 'public' && $stuname eq 'public') {
4938: $stuname=$ENV{'REMOTE_ADDR'};
4939: }
1.1117 foxr 4940: my $path=LONCAPA::tempdir();
1.168 albertel 4941: my %hash;
4942: if (tie(%hash,'GDBM_File',
4943: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4944: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4945: foreach my $key (keys(%hash)) {
1.180 albertel 4946: if ($key=~ /:$symb/) {
1.168 albertel 4947: delete($hash{$key});
4948: }
4949: }
4950: }
4951: }
4952:
1.167 albertel 4953: sub tmpstore {
1.168 albertel 4954: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4955:
4956: if (!$symb) {
4957: $symb=&symbread();
1.620 albertel 4958: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4959: }
4960: $symb=escape($symb);
4961:
4962: if (!$namespace) {
4963: # I don't think we would ever want to store this for a course.
4964: # it seems this will only be used if we don't have a course.
1.620 albertel 4965: #$namespace=$env{'request.course.id'};
1.168 albertel 4966: #if (!$namespace) {
1.620 albertel 4967: $namespace=$env{'request.state'};
1.168 albertel 4968: #}
4969: }
4970: $namespace=~s/\//\_/g;
4971: $namespace=~s/\W//g;
1.620 albertel 4972: if (!$domain) { $domain=$env{'user.domain'}; }
4973: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4974: if ($domain eq 'public' && $stuname eq 'public') {
4975: $stuname=$ENV{'REMOTE_ADDR'};
4976: }
1.168 albertel 4977: my $now=time;
4978: my %hash;
1.1117 foxr 4979: my $path=LONCAPA::tempdir();
1.168 albertel 4980: if (tie(%hash,'GDBM_File',
4981: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4982: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4983: $hash{"version:$symb"}++;
4984: my $version=$hash{"version:$symb"};
4985: my $allkeys='';
4986: foreach my $key (keys(%$storehash)) {
4987: $allkeys.=$key.':';
1.591 albertel 4988: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4989: }
4990: $hash{"$version:$symb:timestamp"}=$now;
4991: $allkeys.='timestamp';
4992: $hash{"$version:keys:$symb"}=$allkeys;
4993: if (untie(%hash)) {
4994: return 'ok';
4995: } else {
4996: return "error:$!";
4997: }
4998: } else {
4999: return "error:$!";
5000: }
5001: }
1.167 albertel 5002:
1.168 albertel 5003: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5004:
1.168 albertel 5005: sub tmprestore {
5006: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5007:
1.168 albertel 5008: if (!$symb) {
5009: $symb=&symbread();
1.620 albertel 5010: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5011: }
5012: $symb=escape($symb);
5013:
1.620 albertel 5014: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5015:
1.620 albertel 5016: if (!$domain) { $domain=$env{'user.domain'}; }
5017: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5018: if ($domain eq 'public' && $stuname eq 'public') {
5019: $stuname=$ENV{'REMOTE_ADDR'};
5020: }
1.168 albertel 5021: my %returnhash;
5022: $namespace=~s/\//\_/g;
5023: $namespace=~s/\W//g;
5024: my %hash;
1.1117 foxr 5025: my $path=LONCAPA::tempdir();
1.168 albertel 5026: if (tie(%hash,'GDBM_File',
5027: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5028: &GDBM_READER(),0640)) {
1.168 albertel 5029: my $version=$hash{"version:$symb"};
5030: $returnhash{'version'}=$version;
5031: my $scope;
5032: for ($scope=1;$scope<=$version;$scope++) {
5033: my $vkeys=$hash{"$scope:keys:$symb"};
5034: my @keys=split(/:/,$vkeys);
5035: my $key;
5036: $returnhash{"$scope:keys"}=$vkeys;
5037: foreach $key (@keys) {
1.591 albertel 5038: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5039: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5040: }
5041: }
1.168 albertel 5042: if (!(untie(%hash))) {
5043: return "error:$!";
5044: }
5045: } else {
5046: return "error:$!";
5047: }
5048: return %returnhash;
1.167 albertel 5049: }
5050:
1.9 www 5051: # ----------------------------------------------------------------------- Store
5052:
5053: sub store {
1.1172.2.64 raeburn 5054: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5055: my $home='';
5056:
1.168 albertel 5057: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5058:
1.213 www 5059: $symb=&symbclean($symb);
1.122 albertel 5060: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5061:
1.620 albertel 5062: if (!$domain) { $domain=$env{'user.domain'}; }
5063: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5064:
5065: &devalidate($symb,$stuname,$domain);
1.109 www 5066:
5067: $symb=escape($symb);
1.187 www 5068: if (!$namespace) {
1.620 albertel 5069: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5070: return '';
5071: }
5072: }
1.620 albertel 5073: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5074:
5075: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5076: $$storehash{'host'}=$perlvar{'lonHostID'};
5077:
1.12 www 5078: my $namevalue='';
1.800 albertel 5079: foreach my $key (keys(%$storehash)) {
5080: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5081: }
1.12 www 5082: $namevalue=~s/\&$//;
1.187 www 5083: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5084: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5085: }
5086:
1.47 www 5087: # -------------------------------------------------------------- Critical Store
5088:
5089: sub cstore {
1.1172.2.64 raeburn 5090: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5091: my $home='';
5092:
1.168 albertel 5093: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5094:
1.213 www 5095: $symb=&symbclean($symb);
1.122 albertel 5096: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5097:
1.620 albertel 5098: if (!$domain) { $domain=$env{'user.domain'}; }
5099: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5100:
5101: &devalidate($symb,$stuname,$domain);
1.109 www 5102:
5103: $symb=escape($symb);
1.187 www 5104: if (!$namespace) {
1.620 albertel 5105: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5106: return '';
5107: }
5108: }
1.620 albertel 5109: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5110:
5111: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5112: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5113:
1.47 www 5114: my $namevalue='';
1.800 albertel 5115: foreach my $key (keys(%$storehash)) {
5116: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5117: }
1.47 www 5118: $namevalue=~s/\&$//;
1.187 www 5119: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5120: return critical
1.1172.2.64 raeburn 5121: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5122: }
5123:
1.9 www 5124: # --------------------------------------------------------------------- Restore
5125:
5126: sub restore {
1.124 www 5127: my ($symb,$namespace,$domain,$stuname) = @_;
5128: my $home='';
5129:
1.168 albertel 5130: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5131:
1.122 albertel 5132: if (!$symb) {
1.1172.2.26 raeburn 5133: return if ($namespace eq 'courserequests');
5134: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5135: } else {
1.1172.2.26 raeburn 5136: unless ($namespace eq 'courserequests') {
5137: $symb=&escape(&symbclean($symb));
5138: }
1.122 albertel 5139: }
1.188 www 5140: if (!$namespace) {
1.620 albertel 5141: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5142: return '';
5143: }
5144: }
1.620 albertel 5145: if (!$domain) { $domain=$env{'user.domain'}; }
5146: if (!$stuname) { $stuname=$env{'user.name'}; }
5147: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5148: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5149:
1.12 www 5150: my %returnhash=();
1.800 albertel 5151: foreach my $line (split(/\&/,$answer)) {
5152: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5153: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5154: }
1.75 www 5155: my $version;
5156: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5157: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5158: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5159: }
1.75 www 5160: }
1.13 www 5161: return %returnhash;
1.34 www 5162: }
5163:
5164: # ---------------------------------------------------------- Course Description
1.1118 foxr 5165: #
5166: #
1.34 www 5167:
5168: sub coursedescription {
1.731 albertel 5169: my ($courseid,$args)=@_;
1.34 www 5170: $courseid=~s/^\///;
1.49 www 5171: $courseid=~s/\_/\//g;
1.34 www 5172: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5173: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5174: my $normalid=$cdomain.'_'.$cnum;
5175: # need to always cache even if we get errors otherwise we keep
5176: # trying and trying and trying to get the course description.
5177: my %envhash=();
5178: my %returnhash=();
1.731 albertel 5179:
5180: my $expiretime=600;
5181: if ($env{'request.course.id'} eq $normalid) {
5182: $expiretime=120;
5183: }
5184:
5185: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5186: if (!$args->{'freshen_cache'}
5187: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5188: foreach my $key (keys(%env)) {
5189: next if ($key !~ /^\Q$prefix\E(.*)/);
5190: my ($setting) = $1;
5191: $returnhash{$setting} = $env{$key};
5192: }
5193: return %returnhash;
5194: }
5195:
1.1118 foxr 5196: # get the data again
5197:
1.731 albertel 5198: if (!$args->{'one_time'}) {
5199: $envhash{'course.'.$normalid.'.last_cache'}=time;
5200: }
1.811 albertel 5201:
1.34 www 5202: if ($chome ne 'no_host') {
1.302 albertel 5203: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5204: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5205: my $username = $env{'user.name'}; # Defult username
5206: if(defined $args->{'user'}) {
5207: $username = $args->{'user'};
5208: }
1.129 albertel 5209: $returnhash{'home'}= $chome;
5210: $returnhash{'domain'} = $cdomain;
5211: $returnhash{'num'} = $cnum;
1.741 raeburn 5212: if (!defined($returnhash{'type'})) {
5213: $returnhash{'type'} = 'Course';
5214: }
1.130 albertel 5215: while (my ($name,$value) = each %returnhash) {
1.53 www 5216: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5217: }
1.270 www 5218: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5219: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5220: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5221: $envhash{'course.'.$normalid.'.home'}=$chome;
5222: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5223: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5224: }
5225: }
1.731 albertel 5226: if (!$args->{'one_time'}) {
1.949 raeburn 5227: &appenv(\%envhash);
1.731 albertel 5228: }
1.302 albertel 5229: return %returnhash;
1.461 www 5230: }
5231:
1.1080 raeburn 5232: sub update_released_required {
5233: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5234: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5235: $cid = $env{'request.course.id'};
5236: $cdom = $env{'course.'.$cid.'.domain'};
5237: $cnum = $env{'course.'.$cid.'.num'};
5238: $chome = $env{'course.'.$cid.'.home'};
5239: }
5240: if ($needsrelease) {
5241: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5242: my $needsupdate;
5243: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5244: $needsupdate = 1;
5245: } else {
5246: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5247: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5248: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5249: $needsupdate = 1;
5250: }
5251: }
5252: if ($needsupdate) {
5253: my %needshash = (
5254: 'internal.releaserequired' => $needsrelease,
5255: );
5256: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5257: if ($putresult eq 'ok') {
5258: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5259: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5260: if (ref($crsinfo{$cid}) eq 'HASH') {
5261: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5262: &courseidput($cdom,\%crsinfo,$chome,'notime');
5263: }
5264: }
5265: }
5266: }
5267: return;
5268: }
5269:
1.461 www 5270: # -------------------------------------------------See if a user is privileged
5271:
5272: sub privileged {
1.1172.2.23 raeburn 5273: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5274: my $now = time;
1.1172.2.23 raeburn 5275: my $roles;
5276: if (ref($possroles) eq 'ARRAY') {
5277: $roles = $possroles;
5278: } else {
5279: $roles = ['dc','su'];
5280: }
5281: if (ref($possdomains) eq 'ARRAY') {
5282: my %privileged = &privileged_by_domain($possdomains,$roles);
5283: foreach my $dom (@{$possdomains}) {
5284: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5285: (ref($privileged{$dom}) eq 'HASH')) {
5286: foreach my $role (@{$roles}) {
5287: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5288: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5289: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5290: return 1 unless (($end && $end < $now) ||
5291: ($start && $start > $now));
5292: }
5293: }
5294: }
5295: }
5296: }
5297: } else {
5298: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5299: my $now = time;
1.1170 droeschl 5300:
1.1172.2.58 raeburn 5301: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5302: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5303: if (grep(/^\Q$trole\E$/,@{$roles})) {
5304: return 1 unless ($tend && $tend < $now)
5305: or ($tstart && $tstart > $now);
1.1170 droeschl 5306: }
1.1172.2.23 raeburn 5307: }
5308: }
1.461 www 5309: return 0;
1.9 www 5310: }
1.1 albertel 5311:
1.1172.2.23 raeburn 5312: sub privileged_by_domain {
5313: my ($domains,$roles) = @_;
5314: my %privileged = ();
5315: my $cachetime = 60*60*24;
5316: my $now = time;
5317: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5318: return %privileged;
5319: }
5320: foreach my $dom (@{$domains}) {
5321: next if (ref($privileged{$dom}) eq 'HASH');
5322: my $needroles;
5323: foreach my $role (@{$roles}) {
5324: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5325: if (defined($cached)) {
5326: if (ref($result) eq 'HASH') {
5327: $privileged{$dom}{$role} = $result;
5328: }
5329: } else {
5330: $needroles = 1;
5331: }
5332: }
5333: if ($needroles) {
5334: my %dompersonnel = &get_domain_roles($dom,$roles);
5335: $privileged{$dom} = {};
5336: foreach my $server (keys(%dompersonnel)) {
5337: if (ref($dompersonnel{$server}) eq 'HASH') {
5338: foreach my $item (keys(%{$dompersonnel{$server}})) {
5339: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5340: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5341: next if ($end && $end < $now);
5342: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5343: $dompersonnel{$server}{$item};
5344: }
5345: }
5346: }
5347: if (ref($privileged{$dom}) eq 'HASH') {
5348: foreach my $role (@{$roles}) {
5349: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5350: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5351: } else {
5352: my %hash = ();
5353: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5354: }
5355: }
5356: }
5357: }
5358: }
5359: return %privileged;
5360: }
5361:
1.103 harris41 5362: # -------------------------------------------------------- Get user privileges
1.11 www 5363:
5364: sub rolesinit {
1.1169 droeschl 5365: my ($domain, $username) = @_;
5366: my %userroles = ('user.login.time' => time);
5367: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5368:
5369: # firstaccess and timerinterval are related to timed maps/resources.
5370: # also, blocking can be triggered by an activating timer
5371: # it's saved in the user's %env.
5372: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5373: my %timerinterval = &dump('timerinterval', $domain, $username);
5374: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5375: %timerintchk, %timerintenv);
5376:
1.1162 raeburn 5377: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5378: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5379: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5380: }
1.1169 droeschl 5381:
1.1162 raeburn 5382: foreach my $key (keys(%timerinterval)) {
5383: my ($cid,$rest) = split(/\0/,$key);
5384: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5385: }
1.1169 droeschl 5386:
1.11 www 5387: my %allroles=();
1.1162 raeburn 5388: my %allgroups=();
1.11 www 5389:
1.1172.2.58 raeburn 5390: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5391: my $role = $rolesdump{$area};
5392: $area =~ s/\_\w\w$//;
5393:
5394: my ($trole, $tend, $tstart, $group_privs);
5395:
5396: if ($role =~ /^cr/) {
5397: # Custom role, defined by a user
5398: # e.g., user.role.cr/msu/smith/mynewrole
5399: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5400: $trole = $1;
5401: ($tend, $tstart) = split('_', $2);
5402: } else {
5403: $trole = $role;
5404: }
5405: } elsif ($role =~ m|^gr/|) {
5406: # Role of member in a group, defined within a course/community
5407: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5408: ($trole, $tend, $tstart) = split(/_/, $role);
5409: next if $tstart eq '-1';
5410: ($trole, $group_privs) = split(/\//, $trole);
5411: $group_privs = &unescape($group_privs);
5412: } else {
5413: # Just a normal role, defined in roles.tab
5414: ($trole, $tend, $tstart) = split(/_/,$role);
5415: }
5416:
5417: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5418: $username);
5419: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5420:
5421: # role expired or not available yet?
5422: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5423: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5424:
5425: next if $area eq '' or $trole eq '';
5426:
5427: my $spec = "$trole.$area";
5428: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5429:
5430: if ($trole =~ /^cr\//) {
5431: # Custom role, defined by a user
5432: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5433: } elsif ($trole eq 'gr') {
5434: # Role of a member in a group, defined within a course/community
5435: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5436: next;
5437: } else {
5438: # Normal role, defined in roles.tab
5439: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5440: }
5441:
5442: my $cid = $tdomain.'_'.$trest;
5443: unless ($firstaccchk{$cid}) {
5444: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5445: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5446: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5447: $coursetimerstarts{$cid}{$item};
5448: }
5449: }
5450: $firstaccchk{$cid} = 1;
5451: }
5452: unless ($timerintchk{$cid}) {
5453: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5454: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5455: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5456: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5457: }
1.12 www 5458: }
1.1169 droeschl 5459: $timerintchk{$cid} = 1;
1.191 harris41 5460: }
1.11 www 5461: }
1.1169 droeschl 5462:
5463: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5464: \%allroles, \%allgroups);
5465: $env{'user.adv'} = $userroles{'user.adv'};
5466:
1.1162 raeburn 5467: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5468: }
5469:
1.567 raeburn 5470: sub set_arearole {
1.1172.2.19 raeburn 5471: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5472: unless ($nolog) {
1.567 raeburn 5473: # log the associated role with the area
1.1172.2.19 raeburn 5474: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5475: }
1.743 albertel 5476: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5477: }
5478:
5479: sub custom_roleprivs {
5480: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5481: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5482: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5483: if (&hostname($homsvr) ne '') {
1.567 raeburn 5484: my ($rdummy,$roledef)=
5485: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5486: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5487: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5488: if (defined($syspriv)) {
1.1043 raeburn 5489: if ($trest =~ /^$match_community$/) {
5490: $syspriv =~ s/bre\&S//;
5491: }
1.567 raeburn 5492: $$allroles{'cm./'}.=':'.$syspriv;
5493: $$allroles{$spec.'./'}.=':'.$syspriv;
5494: }
5495: if ($tdomain ne '') {
5496: if (defined($dompriv)) {
5497: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5498: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5499: }
5500: if (($trest ne '') && (defined($coursepriv))) {
5501: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5502: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5503: }
5504: }
5505: }
5506: }
5507: }
5508:
1.678 raeburn 5509: sub group_roleprivs {
5510: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5511: my $access = 1;
5512: my $now = time;
5513: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5514: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5515: if ($access) {
1.811 albertel 5516: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5517: $$allgroups{$course}{$group} .=':'.$group_privs;
5518: }
5519: }
1.567 raeburn 5520:
5521: sub standard_roleprivs {
5522: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5523: if (defined($pr{$trole.':s'})) {
5524: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5525: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5526: }
5527: if ($tdomain ne '') {
5528: if (defined($pr{$trole.':d'})) {
5529: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5530: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5531: }
5532: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5533: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5534: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5535: }
5536: }
5537: }
5538:
5539: sub set_userprivs {
1.1064 raeburn 5540: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5541: my $author=0;
5542: my $adv=0;
1.678 raeburn 5543: my %grouproles = ();
5544: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5545: my @groupkeys;
1.1000 raeburn 5546: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5547: push(@groupkeys,$role);
5548: }
5549: if (ref($groups_roles) eq 'HASH') {
5550: foreach my $key (keys(%{$groups_roles})) {
5551: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5552: push(@groupkeys,$key);
5553: }
5554: }
5555: }
5556: if (@groupkeys > 0) {
5557: foreach my $role (@groupkeys) {
5558: my ($trole,$area,$sec,$extendedarea);
5559: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5560: $trole = $1;
5561: $area = $2;
5562: $sec = $3;
5563: $extendedarea = $area.$sec;
5564: if (exists($$allgroups{$area})) {
5565: foreach my $group (keys(%{$$allgroups{$area}})) {
5566: my $spec = $trole.'.'.$extendedarea;
5567: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5568: $$allgroups{$area}{$group};
1.1064 raeburn 5569: }
1.678 raeburn 5570: }
5571: }
5572: }
5573: }
5574: }
1.800 albertel 5575: foreach my $group (keys(%grouproles)) {
5576: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5577: }
1.800 albertel 5578: foreach my $role (keys(%{$allroles})) {
5579: my %thesepriv;
1.941 raeburn 5580: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5581: foreach my $item (split(/:/,$$allroles{$role})) {
5582: if ($item ne '') {
5583: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5584: if ($restrictions eq '') {
5585: $thesepriv{$privilege}='F';
5586: } elsif ($thesepriv{$privilege} ne 'F') {
5587: $thesepriv{$privilege}.=$restrictions;
5588: }
5589: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5590: }
5591: }
5592: my $thesestr='';
1.1104 raeburn 5593: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5594: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5595: }
5596: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5597: }
5598: return ($author,$adv);
5599: }
5600:
1.994 raeburn 5601: sub role_status {
1.1104 raeburn 5602: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5603: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5604: my ($one,$two) = split(m{\./},$rolekey,2);
5605: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5606: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5607: $$where = '/'.$two;
1.994 raeburn 5608: $$trolecode=$$role.'.'.$$where;
5609: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5610: $$tstatus='is';
1.1104 raeburn 5611: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5612: $$tstatus='future';
1.1034 raeburn 5613: if ($$tstart<$now) {
5614: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5615: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5616: my (%allroles,%allgroups,$group_privs,
5617: %groups_roles,@rolecodes);
1.1002 raeburn 5618: my %userroles = (
5619: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5620: );
1.1064 raeburn 5621: @rolecodes = ('cm');
1.1002 raeburn 5622: my $spec=$$role.'.'.$$where;
5623: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5624: if ($$role =~ /^cr\//) {
5625: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5626: push(@rolecodes,'cr');
1.1002 raeburn 5627: } elsif ($$role eq 'gr') {
1.1064 raeburn 5628: push(@rolecodes,$$role);
1.1002 raeburn 5629: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5630: $env{'user.name'});
1.1064 raeburn 5631: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5632: (undef,my $group_privs) = split(/\//,$trole);
5633: $group_privs = &unescape($group_privs);
5634: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5635: 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 5636: &get_groups_roles($tdomain,$trest,
5637: \%course_roles,\@rolecodes,
5638: \%groups_roles);
1.1002 raeburn 5639: } else {
1.1064 raeburn 5640: push(@rolecodes,$$role);
1.1002 raeburn 5641: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5642: }
1.1064 raeburn 5643: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5644: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5645: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5646: }
5647: }
1.1034 raeburn 5648: $$tstatus = 'is';
1.1002 raeburn 5649: }
1.994 raeburn 5650: }
5651: if ($$tend) {
1.1104 raeburn 5652: if ($$tend<$update) {
1.994 raeburn 5653: $$tstatus='expired';
5654: } elsif ($$tend<$now) {
5655: $$tstatus='will_not';
5656: }
5657: }
5658: }
5659: }
5660: }
5661:
1.1104 raeburn 5662: sub get_groups_roles {
5663: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5664: return unless((ref($cdom_courseroles) eq 'HASH') &&
5665: (ref($rolecodes) eq 'ARRAY') &&
5666: (ref($groups_roles) eq 'HASH'));
5667: if (keys(%{$cdom_courseroles}) > 0) {
5668: my ($cnum) = ($rest =~ /^($match_courseid)/);
5669: if ($cdom ne '' && $cnum ne '') {
5670: foreach my $key (keys(%{$cdom_courseroles})) {
5671: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5672: my $crsrole = $1;
5673: my $crssec = $2;
5674: if ($crsrole =~ /^cr/) {
5675: unless (grep(/^cr$/,@{$rolecodes})) {
5676: push(@{$rolecodes},'cr');
5677: }
5678: } else {
5679: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5680: push(@{$rolecodes},$crsrole);
5681: }
5682: }
5683: my $rolekey = "$crsrole./$cdom/$cnum";
5684: if ($crssec ne '') {
5685: $rolekey .= "/$crssec";
5686: }
5687: $rolekey .= './';
5688: $groups_roles->{$rolekey} = $rolecodes;
5689: }
5690: }
5691: }
5692: }
5693: return;
5694: }
5695:
5696: sub delete_env_groupprivs {
5697: my ($where,$courseroles,$possroles) = @_;
5698: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5699: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5700: unless (ref($courseroles->{$udom}) eq 'HASH') {
5701: %{$courseroles->{$udom}} =
5702: &get_my_roles('','','userroles',['active'],
5703: $possroles,[$udom],1);
5704: }
5705: if (ref($courseroles->{$udom}) eq 'HASH') {
5706: foreach my $item (keys(%{$courseroles->{$udom}})) {
5707: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5708: my $area = '/'.$cdom.'/'.$cnum;
5709: my $privkey = "user.priv.$crsrole.$area";
5710: if ($crssec ne '') {
5711: $privkey .= '/'.$crssec;
5712: }
5713: $privkey .= ".$area/$group";
5714: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5715: }
5716: }
5717: return;
5718: }
5719:
1.994 raeburn 5720: sub check_adhoc_privs {
1.1104 raeburn 5721: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5722: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5723: my $setprivs;
1.994 raeburn 5724: if ($env{$cckey}) {
5725: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5726: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5727: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5728: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5729: $setprivs = 1;
1.994 raeburn 5730: }
5731: } else {
1.1088 raeburn 5732: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5733: $setprivs = 1;
1.994 raeburn 5734: }
1.1172.2.9 raeburn 5735: return $setprivs;
1.994 raeburn 5736: }
5737:
5738: sub set_adhoc_privileges {
5739: # role can be cc or ca
1.1088 raeburn 5740: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5741: my $area = '/'.$dcdom.'/'.$pickedcourse;
5742: my $spec = $role.'.'.$area;
5743: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5744: $env{'user.name'},1);
1.994 raeburn 5745: my %ccrole = ();
5746: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5747: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5748: &appenv(\%userroles,[$role,'cm']);
5749: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5750: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5751: &appenv( {'request.role' => $spec,
5752: 'request.role.domain' => $dcdom,
5753: 'request.course.sec' => ''
5754: }
5755: );
5756: my $tadv=0;
5757: if (&allowed('adv') eq 'F') { $tadv=1; }
5758: &appenv({'request.role.adv' => $tadv});
5759: }
1.994 raeburn 5760: }
5761:
1.12 www 5762: # --------------------------------------------------------------- get interface
5763:
5764: sub get {
1.131 albertel 5765: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5766: my $items='';
1.800 albertel 5767: foreach my $item (@$storearr) {
5768: $items.=&escape($item).'&';
1.191 harris41 5769: }
1.12 www 5770: $items=~s/\&$//;
1.620 albertel 5771: if (!$udomain) { $udomain=$env{'user.domain'}; }
5772: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5773: my $uhome=&homeserver($uname,$udomain);
5774:
1.133 albertel 5775: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5776: my @pairs=split(/\&/,$rep);
1.273 albertel 5777: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5778: return @pairs;
5779: }
1.15 www 5780: my %returnhash=();
1.42 www 5781: my $i=0;
1.800 albertel 5782: foreach my $item (@$storearr) {
5783: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5784: $i++;
1.191 harris41 5785: }
1.15 www 5786: return %returnhash;
1.27 www 5787: }
5788:
5789: # --------------------------------------------------------------- del interface
5790:
5791: sub del {
1.133 albertel 5792: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5793: my $items='';
1.800 albertel 5794: foreach my $item (@$storearr) {
5795: $items.=&escape($item).'&';
1.191 harris41 5796: }
1.984 neumanie 5797:
1.27 www 5798: $items=~s/\&$//;
1.620 albertel 5799: if (!$udomain) { $udomain=$env{'user.domain'}; }
5800: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5801: my $uhome=&homeserver($uname,$udomain);
5802: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5803: }
5804:
5805: # -------------------------------------------------------------- dump interface
5806:
1.1172.2.22 raeburn 5807: sub unserialize {
5808: my ($rep, $escapedkeys) = @_;
5809:
5810: return {} if $rep =~ /^error/;
5811:
5812: my %returnhash=();
5813: foreach my $item (split(/\&/,$rep)) {
5814: my ($key, $value) = split(/=/, $item, 2);
5815: $key = unescape($key) unless $escapedkeys;
5816: next if $key =~ /^error: 2 /;
5817: $returnhash{$key} = &thaw_unescape($value);
5818: }
5819: return \%returnhash;
5820: }
5821:
5822: # see Lond::dump_with_regexp
5823: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5824: sub dump {
1.1172.2.22 raeburn 5825: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5826: if (!$udomain) { $udomain=$env{'user.domain'}; }
5827: if (!$uname) { $uname=$env{'user.name'}; }
5828: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5829:
1.1172.2.55 raeburn 5830: if ($regexp) {
5831: $regexp=&escape($regexp);
5832: } else {
5833: $regexp='.';
5834: }
1.1172.2.22 raeburn 5835: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5836: # user is hosted on this machine
1.1172.2.55 raeburn 5837: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5838: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5839: return %{&unserialize($reply, $escapedkeys)};
5840: }
1.1166 raeburn 5841: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5842: my @pairs=split(/\&/,$rep);
5843: my %returnhash=();
1.1098 foxr 5844: if (!($rep =~ /^error/ )) {
5845: foreach my $item (@pairs) {
5846: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5847: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5848: next if ($key =~ /^error: 2 /);
5849: $returnhash{$key}=&thaw_unescape($value);
5850: }
1.755 albertel 5851: }
5852: return %returnhash;
1.407 www 5853: }
5854:
1.1098 foxr 5855:
1.717 albertel 5856: # --------------------------------------------------------- dumpstore interface
5857:
5858: sub dumpstore {
5859: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5860: # same as dump but keys must be escaped. They may contain colon separated
5861: # lists of values that may themself contain colons (e.g. symbs).
5862: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5863: }
5864:
1.407 www 5865: # -------------------------------------------------------------- keys interface
5866:
5867: sub getkeys {
5868: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5869: if (!$udomain) { $udomain=$env{'user.domain'}; }
5870: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5871: my $uhome=&homeserver($uname,$udomain);
5872: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5873: my @keyarray=();
1.800 albertel 5874: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5875: next if ($key =~ /^error: 2 /);
1.800 albertel 5876: push(@keyarray,&unescape($key));
1.407 www 5877: }
5878: return @keyarray;
1.318 matthew 5879: }
5880:
1.319 matthew 5881: # --------------------------------------------------------------- currentdump
5882: sub currentdump {
1.328 matthew 5883: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5884: $courseid = $env{'request.course.id'} if (! defined($courseid));
5885: $sdom = $env{'user.domain'} if (! defined($sdom));
5886: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5887: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5888: my $rep;
5889:
5890: if (grep { $_ eq $uhome } current_machine_ids()) {
5891: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5892: $courseid)));
5893: } else {
5894: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5895: }
5896:
1.318 matthew 5897: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5898: #
1.318 matthew 5899: my %returnhash=();
1.319 matthew 5900: #
5901: if ($rep eq "unknown_cmd") {
5902: # an old lond will not know currentdump
5903: # Do a dump and make it look like a currentdump
1.822 albertel 5904: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5905: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5906: my %hash = @tmp;
5907: @tmp=();
1.424 matthew 5908: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5909: } else {
5910: my @pairs=split(/\&/,$rep);
1.800 albertel 5911: foreach my $pair (@pairs) {
5912: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5913: my ($symb,$param) = split(/:/,$key);
5914: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5915: &thaw_unescape($value);
1.319 matthew 5916: }
1.191 harris41 5917: }
1.12 www 5918: return %returnhash;
1.424 matthew 5919: }
5920:
5921: sub convert_dump_to_currentdump{
5922: my %hash = %{shift()};
5923: my %returnhash;
5924: # Code ripped from lond, essentially. The only difference
5925: # here is the unescaping done by lonnet::dump(). Conceivably
5926: # we might run in to problems with parameter names =~ /^v\./
5927: while (my ($key,$value) = each(%hash)) {
5928: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5929: $symb = &unescape($symb);
5930: $param = &unescape($param);
1.424 matthew 5931: next if ($v eq 'version' || $symb eq 'keys');
5932: next if (exists($returnhash{$symb}) &&
5933: exists($returnhash{$symb}->{$param}) &&
5934: $returnhash{$symb}->{'v.'.$param} > $v);
5935: $returnhash{$symb}->{$param}=$value;
5936: $returnhash{$symb}->{'v.'.$param}=$v;
5937: }
5938: #
5939: # Remove all of the keys in the hashes which keep track of
5940: # the version of the parameter.
5941: while (my ($symb,$param_hash) = each(%returnhash)) {
5942: # use a foreach because we are going to delete from the hash.
5943: foreach my $key (keys(%$param_hash)) {
5944: delete($param_hash->{$key}) if ($key =~ /^v\./);
5945: }
5946: }
5947: return \%returnhash;
1.12 www 5948: }
5949:
1.627 albertel 5950: # ------------------------------------------------------ critical inc interface
5951:
5952: sub cinc {
5953: return &inc(@_,'critical');
5954: }
5955:
1.449 matthew 5956: # --------------------------------------------------------------- inc interface
5957:
5958: sub inc {
1.627 albertel 5959: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5960: if (!$udomain) { $udomain=$env{'user.domain'}; }
5961: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5962: my $uhome=&homeserver($uname,$udomain);
5963: my $items='';
5964: if (! ref($store)) {
5965: # got a single value, so use that instead
5966: $items = &escape($store).'=&';
5967: } elsif (ref($store) eq 'SCALAR') {
5968: $items = &escape($$store).'=&';
5969: } elsif (ref($store) eq 'ARRAY') {
5970: $items = join('=&',map {&escape($_);} @{$store});
5971: } elsif (ref($store) eq 'HASH') {
5972: while (my($key,$value) = each(%{$store})) {
5973: $items.= &escape($key).'='.&escape($value).'&';
5974: }
5975: }
5976: $items=~s/\&$//;
1.627 albertel 5977: if ($critical) {
5978: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5979: } else {
5980: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5981: }
1.449 matthew 5982: }
5983:
1.12 www 5984: # --------------------------------------------------------------- put interface
5985:
5986: sub put {
1.134 albertel 5987: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5988: if (!$udomain) { $udomain=$env{'user.domain'}; }
5989: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5990: my $uhome=&homeserver($uname,$udomain);
1.12 www 5991: my $items='';
1.800 albertel 5992: foreach my $item (keys(%$storehash)) {
5993: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5994: }
1.12 www 5995: $items=~s/\&$//;
1.134 albertel 5996: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5997: }
5998:
1.631 albertel 5999: # ------------------------------------------------------------ newput interface
6000:
6001: sub newput {
6002: my ($namespace,$storehash,$udomain,$uname)=@_;
6003: if (!$udomain) { $udomain=$env{'user.domain'}; }
6004: if (!$uname) { $uname=$env{'user.name'}; }
6005: my $uhome=&homeserver($uname,$udomain);
6006: my $items='';
6007: foreach my $key (keys(%$storehash)) {
6008: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6009: }
6010: $items=~s/\&$//;
6011: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6012: }
6013:
6014: # --------------------------------------------------------- putstore interface
6015:
1.524 raeburn 6016: sub putstore {
1.1172.2.59 raeburn 6017: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6018: if (!$udomain) { $udomain=$env{'user.domain'}; }
6019: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6020: my $uhome=&homeserver($uname,$udomain);
6021: my $items='';
1.715 albertel 6022: foreach my $key (keys(%$storehash)) {
6023: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6024: }
1.715 albertel 6025: $items=~s/\&$//;
1.716 albertel 6026: my $esc_symb=&escape($symb);
6027: my $esc_v=&escape($version);
1.715 albertel 6028: my $reply =
1.716 albertel 6029: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6030: $uhome);
1.1172.2.59 raeburn 6031: if (($tolog) && ($reply eq 'ok')) {
6032: my $namevalue='';
6033: foreach my $key (keys(%{$storehash})) {
6034: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6035: }
6036: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6037: '&host='.&escape($perlvar{'lonHostID'}).
6038: '&version='.$esc_v.
6039: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6040: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6041: }
1.715 albertel 6042: if ($reply eq 'unknown_cmd') {
1.716 albertel 6043: # gfall back to way things use to be done
1.715 albertel 6044: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6045: $uname);
1.524 raeburn 6046: }
1.715 albertel 6047: return $reply;
6048: }
6049:
6050: sub old_putstore {
1.716 albertel 6051: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6052: if (!$udomain) { $udomain=$env{'user.domain'}; }
6053: if (!$uname) { $uname=$env{'user.name'}; }
6054: my $uhome=&homeserver($uname,$udomain);
6055: my %newstorehash;
1.800 albertel 6056: foreach my $item (keys(%$storehash)) {
6057: my $key = $version.':'.&escape($symb).':'.$item;
6058: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6059: }
6060: my $items='';
6061: my %allitems = ();
1.800 albertel 6062: foreach my $item (keys(%newstorehash)) {
6063: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6064: my $key = $1.':keys:'.$2;
6065: $allitems{$key} .= $3.':';
6066: }
1.800 albertel 6067: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6068: }
1.800 albertel 6069: foreach my $item (keys(%allitems)) {
6070: $allitems{$item} =~ s/\:$//;
6071: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6072: }
6073: $items=~s/\&$//;
6074: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6075: }
6076:
1.47 www 6077: # ------------------------------------------------------ critical put interface
6078:
6079: sub cput {
1.134 albertel 6080: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6081: if (!$udomain) { $udomain=$env{'user.domain'}; }
6082: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6083: my $uhome=&homeserver($uname,$udomain);
1.47 www 6084: my $items='';
1.800 albertel 6085: foreach my $item (keys(%$storehash)) {
6086: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6087: }
1.47 www 6088: $items=~s/\&$//;
1.134 albertel 6089: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6090: }
6091:
6092: # -------------------------------------------------------------- eget interface
6093:
6094: sub eget {
1.133 albertel 6095: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6096: my $items='';
1.800 albertel 6097: foreach my $item (@$storearr) {
6098: $items.=&escape($item).'&';
1.191 harris41 6099: }
1.12 www 6100: $items=~s/\&$//;
1.620 albertel 6101: if (!$udomain) { $udomain=$env{'user.domain'}; }
6102: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6103: my $uhome=&homeserver($uname,$udomain);
6104: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6105: my @pairs=split(/\&/,$rep);
6106: my %returnhash=();
1.42 www 6107: my $i=0;
1.800 albertel 6108: foreach my $item (@$storearr) {
6109: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6110: $i++;
1.191 harris41 6111: }
1.12 www 6112: return %returnhash;
6113: }
6114:
1.667 albertel 6115: # ------------------------------------------------------------ tmpput interface
6116: sub tmpput {
1.802 raeburn 6117: my ($storehash,$server,$context)=@_;
1.667 albertel 6118: my $items='';
1.800 albertel 6119: foreach my $item (keys(%$storehash)) {
6120: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6121: }
6122: $items=~s/\&$//;
1.802 raeburn 6123: if (defined($context)) {
6124: $items .= ':'.&escape($context);
6125: }
1.667 albertel 6126: return &reply("tmpput:$items",$server);
6127: }
6128:
6129: # ------------------------------------------------------------ tmpget interface
6130: sub tmpget {
1.688 albertel 6131: my ($token,$server)=@_;
6132: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6133: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6134: my %returnhash;
6135: foreach my $item (split(/\&/,$rep)) {
6136: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6137: next if ($key =~ /^error: 2 /);
1.667 albertel 6138: $returnhash{&unescape($key)}=&thaw_unescape($value);
6139: }
6140: return %returnhash;
6141: }
6142:
1.1113 raeburn 6143: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6144: sub tmpdel {
6145: my ($token,$server)=@_;
6146: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6147: return &reply("tmpdel:$token",$server);
6148: }
6149:
1.1172.2.13 raeburn 6150: # ------------------------------------------------------------ get_timebased_id
6151:
6152: sub get_timebased_id {
6153: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6154: $maxtries) = @_;
6155: my ($newid,$error,$dellock);
6156: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6157: return ('','ok','invalid call to get suffix');
6158: }
6159:
6160: # set defaults for any optional args for which values were not supplied
6161: if ($who eq '') {
6162: $who = $env{'user.name'}.':'.$env{'user.domain'};
6163: }
6164: if (!$locktries) {
6165: $locktries = 3;
6166: }
6167: if (!$maxtries) {
6168: $maxtries = 10;
6169: }
6170:
6171: if (($cdom eq '') || ($cnum eq '')) {
6172: if ($env{'request.course.id'}) {
6173: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6174: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6175: }
6176: if (($cdom eq '') || ($cnum eq '')) {
6177: return ('','ok','call to get suffix not in course context');
6178: }
6179: }
6180:
6181: # construct locking item
6182: my $lockhash = {
6183: $prefix."\0".'locked_'.$keyid => $who,
6184: };
6185: my $tries = 0;
6186:
6187: # attempt to get lock on nohist_$namespace file
6188: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6189: while (($gotlock ne 'ok') && $tries <$locktries) {
6190: $tries ++;
6191: sleep 1;
6192: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6193: }
6194:
6195: # attempt to get unique identifier, based on current timestamp
6196: if ($gotlock eq 'ok') {
6197: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6198: my $id = time;
6199: $newid = $id;
1.1172.2.56 raeburn 6200: if ($idtype eq 'addcode') {
6201: $newid .= &sixnum_code();
6202: }
1.1172.2.13 raeburn 6203: my $idtries = 0;
6204: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6205: if ($idtype eq 'concat') {
6206: $newid = $id.$idtries;
1.1172.2.56 raeburn 6207: } elsif ($idtype eq 'addcode') {
6208: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6209: } else {
6210: $newid ++;
6211: }
6212: $idtries ++;
6213: }
6214: if (!exists($inuse{$prefix."\0".$newid})) {
6215: my %new_item = (
6216: $prefix."\0".$newid => $who,
6217: );
6218: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6219: $cdom,$cnum);
6220: if ($putresult ne 'ok') {
6221: undef($newid);
6222: $error = 'error saving new item: '.$putresult;
6223: }
6224: } else {
1.1172.2.56 raeburn 6225: undef($newid);
1.1172.2.13 raeburn 6226: $error = ('error: no unique suffix available for the new item ');
6227: }
6228: # remove lock
6229: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6230: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6231: } else {
6232: $error = "error: could not obtain lockfile\n";
6233: $dellock = 'ok';
1.1172.2.58 raeburn 6234: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6235: $dellock = 'nolock';
6236: }
1.1172.2.13 raeburn 6237: }
6238: return ($newid,$dellock,$error);
6239: }
6240:
1.1172.2.56 raeburn 6241: sub sixnum_code {
6242: my $code;
6243: for (0..6) {
6244: $code .= int( rand(9) );
6245: }
6246: return $code;
6247: }
6248:
1.765 albertel 6249: # -------------------------------------------------- portfolio access checking
6250:
6251: sub portfolio_access {
1.1172.2.77 raeburn 6252: my ($requrl,$clientip) = @_;
1.765 albertel 6253: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6254: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6255: if ($result) {
6256: my %setters;
6257: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6258: my ($startblock,$endblock) =
6259: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6260: if ($startblock && $endblock) {
6261: return 'B';
6262: }
6263: } else {
6264: my ($startblock,$endblock) =
6265: &Apache::loncommon::blockcheck(\%setters,'port');
6266: if ($startblock && $endblock) {
6267: return 'B';
6268: }
6269: }
6270: }
1.765 albertel 6271: if ($result eq 'ok') {
1.766 albertel 6272: return 'F';
1.765 albertel 6273: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6274: return 'A';
1.765 albertel 6275: }
1.766 albertel 6276: return '';
1.765 albertel 6277: }
6278:
6279: sub get_portfolio_access {
1.1172.2.77 raeburn 6280: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6281:
6282: if (!ref($access_hash)) {
6283: my $current_perms = &get_portfile_permissions($udom,$unum);
6284: my %access_controls = &get_access_controls($current_perms,$group,
6285: $file_name);
6286: $access_hash = $access_controls{$file_name};
6287: }
6288:
1.1172.2.77 raeburn 6289: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6290: my $now = time;
6291: if (ref($access_hash) eq 'HASH') {
6292: foreach my $key (keys(%{$access_hash})) {
6293: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6294: if ($start > $now) {
6295: next;
6296: }
6297: if ($end && $end<$now) {
6298: next;
6299: }
6300: if ($scope eq 'public') {
6301: $public = $key;
6302: last;
6303: } elsif ($scope eq 'guest') {
6304: $guest = $key;
6305: } elsif ($scope eq 'domains') {
6306: push(@domains,$key);
6307: } elsif ($scope eq 'users') {
6308: push(@users,$key);
6309: } elsif ($scope eq 'course') {
6310: push(@courses,$key);
6311: } elsif ($scope eq 'group') {
6312: push(@groups,$key);
1.1172.2.77 raeburn 6313: } elsif ($scope eq 'ip') {
6314: push(@ips,$key);
1.765 albertel 6315: }
6316: }
6317: if ($public) {
6318: return 'ok';
1.1172.2.77 raeburn 6319: } elsif (@ips > 0) {
6320: my $allowed;
6321: foreach my $ipkey (@ips) {
6322: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6323: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6324: $allowed = 1;
6325: last;
6326: }
6327: }
6328: }
6329: if ($allowed) {
6330: return 'ok';
6331: }
1.765 albertel 6332: }
6333: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6334: if ($guest) {
6335: return $guest;
6336: }
6337: } else {
6338: if (@domains > 0) {
6339: foreach my $domkey (@domains) {
6340: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6341: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6342: return 'ok';
6343: }
6344: }
6345: }
6346: }
6347: if (@users > 0) {
6348: foreach my $userkey (@users) {
1.865 raeburn 6349: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6350: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6351: if (ref($item) eq 'HASH') {
6352: if (($item->{'uname'} eq $env{'user.name'}) &&
6353: ($item->{'udom'} eq $env{'user.domain'})) {
6354: return 'ok';
6355: }
6356: }
6357: }
6358: }
1.765 albertel 6359: }
6360: }
6361: my %roleshash;
6362: my @courses_and_groups = @courses;
6363: push(@courses_and_groups,@groups);
6364: if (@courses_and_groups > 0) {
6365: my (%allgroups,%allroles);
6366: my ($start,$end,$role,$sec,$group);
6367: foreach my $envkey (%env) {
1.1060 raeburn 6368: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6369: my $cid = $2.'_'.$3;
6370: if ($1 eq 'gr') {
6371: $group = $4;
6372: $allgroups{$cid}{$group} = $env{$envkey};
6373: } else {
6374: if ($4 eq '') {
6375: $sec = 'none';
6376: } else {
6377: $sec = $4;
6378: }
6379: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6380: }
1.811 albertel 6381: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6382: my $cid = $2.'_'.$3;
6383: if ($4 eq '') {
6384: $sec = 'none';
6385: } else {
6386: $sec = $4;
6387: }
6388: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6389: }
6390: }
6391: if (keys(%allroles) == 0) {
6392: return;
6393: }
6394: foreach my $key (@courses_and_groups) {
6395: my %content = %{$$access_hash{$key}};
6396: my $cnum = $content{'number'};
6397: my $cdom = $content{'domain'};
6398: my $cid = $cdom.'_'.$cnum;
6399: if (!exists($allroles{$cid})) {
6400: next;
6401: }
6402: foreach my $role_id (keys(%{$content{'roles'}})) {
6403: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6404: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6405: my @status = @{$content{'roles'}{$role_id}{'access'}};
6406: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6407: foreach my $role (keys(%{$allroles{$cid}})) {
6408: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6409: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6410: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6411: if (grep/^all$/,@sections) {
6412: return 'ok';
6413: } else {
6414: if (grep/^$sec$/,@sections) {
6415: return 'ok';
6416: }
6417: }
6418: }
6419: }
6420: if (keys(%{$allgroups{$cid}}) == 0) {
6421: if (grep/^none$/,@groups) {
6422: return 'ok';
6423: }
6424: } else {
6425: if (grep/^all$/,@groups) {
6426: return 'ok';
6427: }
6428: foreach my $group (keys(%{$allgroups{$cid}})) {
6429: if (grep/^$group$/,@groups) {
6430: return 'ok';
6431: }
6432: }
6433: }
6434: }
6435: }
6436: }
6437: }
6438: }
6439: if ($guest) {
6440: return $guest;
6441: }
6442: }
6443: }
6444: return;
6445: }
6446:
6447: sub course_group_datechecker {
6448: my ($dates,$now,$status) = @_;
6449: my ($start,$end) = split(/\./,$dates);
6450: if (!$start && !$end) {
6451: return 'ok';
6452: }
6453: if (grep/^active$/,@{$status}) {
6454: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6455: return 'ok';
6456: }
6457: }
6458: if (grep/^previous$/,@{$status}) {
6459: if ($end > $now ) {
6460: return 'ok';
6461: }
6462: }
6463: if (grep/^future$/,@{$status}) {
6464: if ($start > $now) {
6465: return 'ok';
6466: }
6467: }
6468: return;
6469: }
6470:
6471: sub parse_portfolio_url {
6472: my ($url) = @_;
6473:
6474: my ($type,$udom,$unum,$group,$file_name);
6475:
1.823 albertel 6476: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6477: $type = 1;
6478: $udom = $1;
6479: $unum = $2;
6480: $file_name = $3;
1.823 albertel 6481: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6482: $type = 2;
6483: $udom = $1;
6484: $unum = $2;
6485: $group = $3;
6486: $file_name = $3.'/'.$4;
6487: }
6488: if (wantarray) {
6489: return ($type,$udom,$unum,$file_name,$group);
6490: }
6491: return $type;
6492: }
6493:
6494: sub is_portfolio_url {
6495: my ($url) = @_;
6496: return scalar(&parse_portfolio_url($url));
6497: }
6498:
1.798 raeburn 6499: sub is_portfolio_file {
6500: my ($file) = @_;
1.820 raeburn 6501: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6502: return 1;
6503: }
6504: return;
6505: }
6506:
1.976 raeburn 6507: sub usertools_access {
1.1084 raeburn 6508: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6509: my ($access,%tools);
6510: if ($context eq '') {
6511: $context = 'tools';
6512: }
6513: if ($context eq 'requestcourses') {
6514: %tools = (
6515: official => 1,
6516: unofficial => 1,
1.1006 raeburn 6517: community => 1,
1.1172.2.37 raeburn 6518: textbook => 1,
1.985 raeburn 6519: );
1.1172.2.9 raeburn 6520: } elsif ($context eq 'requestauthor') {
6521: %tools = (
6522: requestauthor => 1,
6523: );
1.985 raeburn 6524: } else {
6525: %tools = (
6526: aboutme => 1,
6527: blog => 1,
1.1172.2.6 raeburn 6528: webdav => 1,
1.985 raeburn 6529: portfolio => 1,
6530: );
6531: }
1.976 raeburn 6532: return if (!defined($tools{$tool}));
6533:
1.1172.2.35 raeburn 6534: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6535: $udom = $env{'user.domain'};
6536: $uname = $env{'user.name'};
6537: }
6538:
1.978 raeburn 6539: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6540: if ($action ne 'reload') {
1.985 raeburn 6541: if ($context eq 'requestcourses') {
6542: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6543: } elsif ($context eq 'requestauthor') {
6544: return $env{'environment.canrequest.author'};
1.985 raeburn 6545: } else {
6546: return $env{'environment.availabletools.'.$tool};
6547: }
6548: }
1.976 raeburn 6549: }
6550:
1.1172.2.9 raeburn 6551: my ($toolstatus,$inststatus,$envkey);
6552: if ($context eq 'requestauthor') {
6553: $envkey = $context;
6554: } else {
6555: $envkey = $context.'.'.$tool;
6556: }
1.976 raeburn 6557:
1.985 raeburn 6558: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6559: ($action ne 'reload')) {
1.1172.2.9 raeburn 6560: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6561: $inststatus = $env{'environment.inststatus'};
6562: } else {
1.1084 raeburn 6563: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6564: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6565: $inststatus = $userenvref->{'inststatus'};
6566: } else {
1.1172.2.9 raeburn 6567: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6568: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6569: $inststatus = $userenv{'inststatus'};
6570: }
1.976 raeburn 6571: }
6572:
6573: if ($toolstatus ne '') {
6574: if ($toolstatus) {
6575: $access = 1;
6576: } else {
6577: $access = 0;
6578: }
6579: return $access;
6580: }
6581:
1.1084 raeburn 6582: my ($is_adv,%domdef);
6583: if (ref($is_advref) eq 'HASH') {
6584: $is_adv = $is_advref->{'is_adv'};
6585: } else {
6586: $is_adv = &is_advanced_user($udom,$uname);
6587: }
6588: if (ref($domdefref) eq 'HASH') {
6589: %domdef = %{$domdefref};
6590: } else {
6591: %domdef = &get_domain_defaults($udom);
6592: }
1.976 raeburn 6593: if (ref($domdef{$tool}) eq 'HASH') {
6594: if ($is_adv) {
6595: if ($domdef{$tool}{'_LC_adv'} ne '') {
6596: if ($domdef{$tool}{'_LC_adv'}) {
6597: $access = 1;
6598: } else {
6599: $access = 0;
6600: }
6601: return $access;
6602: }
6603: }
6604: if ($inststatus ne '') {
6605: my ($hasaccess,$hasnoaccess);
6606: foreach my $affiliation (split(/:/,$inststatus)) {
6607: if ($domdef{$tool}{$affiliation} ne '') {
6608: if ($domdef{$tool}{$affiliation}) {
6609: $hasaccess = 1;
6610: } else {
6611: $hasnoaccess = 1;
6612: }
6613: }
6614: }
6615: if ($hasaccess || $hasnoaccess) {
6616: if ($hasaccess) {
6617: $access = 1;
6618: } elsif ($hasnoaccess) {
6619: $access = 0;
6620: }
6621: return $access;
6622: }
6623: } else {
6624: if ($domdef{$tool}{'default'} ne '') {
6625: if ($domdef{$tool}{'default'}) {
6626: $access = 1;
6627: } elsif ($domdef{$tool}{'default'} == 0) {
6628: $access = 0;
6629: }
6630: return $access;
6631: }
6632: }
6633: } else {
1.1172.2.6 raeburn 6634: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6635: $access = 1;
6636: } else {
6637: $access = 0;
6638: }
1.976 raeburn 6639: return $access;
6640: }
6641: }
6642:
1.1050 raeburn 6643: sub is_course_owner {
6644: my ($cdom,$cnum,$udom,$uname) = @_;
6645: if (($udom eq '') || ($uname eq '')) {
6646: $udom = $env{'user.domain'};
6647: $uname = $env{'user.name'};
6648: }
6649: unless (($udom eq '') || ($uname eq '')) {
6650: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6651: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6652: return 1;
6653: } else {
6654: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6655: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6656: return 1;
6657: }
6658: }
6659: }
6660: }
6661: return;
6662: }
6663:
1.976 raeburn 6664: sub is_advanced_user {
6665: my ($udom,$uname) = @_;
1.1085 raeburn 6666: if ($udom ne '' && $uname ne '') {
6667: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6668: if (wantarray) {
6669: return ($env{'user.adv'},$env{'user.author'});
6670: } else {
6671: return $env{'user.adv'};
6672: }
1.1085 raeburn 6673: }
6674: }
1.976 raeburn 6675: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6676: my %allroles;
1.1128 raeburn 6677: my ($is_adv,$is_author);
1.976 raeburn 6678: foreach my $role (keys(%roleshash)) {
6679: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6680: my $area = '/'.$tdomain.'/'.$trest;
6681: if ($sec ne '') {
6682: $area .= '/'.$sec;
6683: }
6684: if (($area ne '') && ($trole ne '')) {
6685: my $spec=$trole.'.'.$area;
6686: if ($trole =~ /^cr\//) {
6687: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6688: } elsif ($trole ne 'gr') {
6689: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6690: }
1.1128 raeburn 6691: if ($trole eq 'au') {
6692: $is_author = 1;
6693: }
1.976 raeburn 6694: }
6695: }
6696: foreach my $role (keys(%allroles)) {
6697: last if ($is_adv);
6698: foreach my $item (split(/:/,$allroles{$role})) {
6699: if ($item ne '') {
6700: my ($privilege,$restrictions)=split(/&/,$item);
6701: if ($privilege eq 'adv') {
6702: $is_adv = 1;
6703: last;
6704: }
6705: }
6706: }
6707: }
1.1128 raeburn 6708: if (wantarray) {
6709: return ($is_adv,$is_author);
6710: }
1.976 raeburn 6711: return $is_adv;
6712: }
1.798 raeburn 6713:
1.1035 raeburn 6714: sub check_can_request {
1.1036 raeburn 6715: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6716: my $canreq = 0;
6717: my ($types,$typename) = &Apache::loncommon::course_types();
6718: my @options = ('approval','validate','autolimit');
6719: my $optregex = join('|',@options);
6720: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6721: foreach my $type (@{$types}) {
6722: if (&usertools_access($env{'user.name'},
6723: $env{'user.domain'},
6724: $type,undef,'requestcourses')) {
6725: $canreq ++;
1.1036 raeburn 6726: if (ref($request_domains) eq 'HASH') {
6727: push(@{$request_domains->{$type}},$env{'user.domain'});
6728: }
1.1035 raeburn 6729: if ($dom eq $env{'user.domain'}) {
6730: $can_request->{$type} = 1;
6731: }
6732: }
6733: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6734: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6735: if (@curr > 0) {
1.1036 raeburn 6736: foreach my $item (@curr) {
6737: if (ref($request_domains) eq 'HASH') {
6738: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6739: if ($otherdom ne '') {
6740: if (ref($request_domains->{$type}) eq 'ARRAY') {
6741: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6742: push(@{$request_domains->{$type}},$otherdom);
6743: }
6744: } else {
6745: push(@{$request_domains->{$type}},$otherdom);
6746: }
6747: }
6748: }
6749: }
6750: unless($dom eq $env{'user.domain'}) {
6751: $canreq ++;
1.1035 raeburn 6752: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6753: $can_request->{$type} = 1;
6754: }
6755: }
6756: }
6757: }
6758: }
6759: }
6760: return $canreq;
6761: }
6762:
1.341 www 6763: # ---------------------------------------------- Custom access rule evaluation
6764:
6765: sub customaccess {
6766: my ($priv,$uri)=@_;
1.807 albertel 6767: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6768: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6769: $udom = &LONCAPA::clean_domain($udom);
6770: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6771: my $access=0;
1.800 albertel 6772: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6773: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6774: if ($type eq 'user') {
6775: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6776: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6777: if ($tdom) {
6778: if ($tdom ne $env{'user.domain'}) { next; }
6779: }
1.896 albertel 6780: if ($tuname) {
6781: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6782: }
6783: $access=($effect eq 'allow');
6784: last;
6785: }
6786: } else {
6787: if ($role) {
6788: if ($role ne $urole) { next; }
6789: }
6790: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6791: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6792: if ($tdom) {
6793: if ($tdom ne $udom) { next; }
6794: }
6795: if ($tcrs) {
6796: if ($tcrs ne $ucrs) { next; }
6797: }
6798: if ($tsec) {
6799: if ($tsec ne $usec) { next; }
6800: }
6801: $access=($effect eq 'allow');
6802: last;
6803: }
6804: if ($realm eq '' && $role eq '') {
6805: $access=($effect eq 'allow');
6806: }
1.402 bowersj2 6807: }
1.341 www 6808: }
6809: return $access;
6810: }
6811:
1.103 harris41 6812: # ------------------------------------------------- Check for a user privilege
1.12 www 6813:
6814: sub allowed {
1.1172.2.65 raeburn 6815: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6816: my $ver_orguri=$uri;
1.439 www 6817: $uri=&deversion($uri);
1.152 www 6818: my $orguri=$uri;
1.52 www 6819: $uri=&declutter($uri);
1.809 raeburn 6820:
1.810 raeburn 6821: if ($priv eq 'evb') {
6822: # Evade communication block restrictions for specified role in a course
6823: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6824: return $1;
6825: } else {
6826: return;
6827: }
6828: }
6829:
1.620 albertel 6830: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6831: # Free bre access to adm and meta resources
1.775 albertel 6832: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6833: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6834: && ($priv eq 'bre')) {
1.14 www 6835: return 'F';
1.159 www 6836: }
6837:
1.545 banghart 6838: # Free bre access to user's own portfolio contents
1.714 raeburn 6839: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6840: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6841: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6842: my %setters;
6843: my ($startblock,$endblock) =
6844: &Apache::loncommon::blockcheck(\%setters,'port');
6845: if ($startblock && $endblock) {
6846: return 'B';
6847: } else {
6848: return 'F';
6849: }
1.545 banghart 6850: }
6851:
1.762 raeburn 6852: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6853: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6854: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6855: if (exists($env{'request.course.id'})) {
6856: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6857: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6858: if (($domain eq $cdom) && ($name eq $cnum)) {
6859: my $courseprivid=$env{'request.course.id'};
6860: $courseprivid=~s/\_/\//;
6861: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6862: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6863: return $1;
1.762 raeburn 6864: } else {
6865: if ($env{'request.course.sec'}) {
6866: $courseprivid.='/'.$env{'request.course.sec'};
6867: }
6868: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6869: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6870: return $2;
6871: }
1.714 raeburn 6872: }
6873: }
6874: }
6875: }
6876:
1.159 www 6877: # Free bre to public access
6878:
6879: if ($priv eq 'bre') {
1.238 www 6880: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6881: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6882: return 'F';
6883: }
1.238 www 6884: if ($copyright eq 'priv') {
6885: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6886: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6887: return '';
6888: }
6889: }
6890: if ($copyright eq 'domain') {
6891: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6892: unless (($env{'user.domain'} eq $1) ||
6893: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6894: return '';
6895: }
1.262 matthew 6896: }
1.620 albertel 6897: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6898: # Library role, so allow browsing of resources in this domain.
6899: return 'F';
1.238 www 6900: }
1.341 www 6901: if ($copyright eq 'custom') {
6902: unless (&customaccess($priv,$uri)) { return ''; }
6903: }
1.14 www 6904: }
1.264 matthew 6905: # Domain coordinator is trying to create a course
1.620 albertel 6906: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6907: # uri is the requested domain in this case.
6908: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6909: # a role of dc for the domain in question.
1.620 albertel 6910: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6911: }
1.29 www 6912:
1.52 www 6913: my $thisallowed='';
6914: my $statecond=0;
6915: my $courseprivid='';
6916:
1.1039 raeburn 6917: my $ownaccess;
1.1043 raeburn 6918: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6919: if (($priv eq 'bro') && ($env{'user.author'})) {
6920: if ($uri eq '') {
6921: $ownaccess = 1;
6922: } else {
6923: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6924: my $udom = $env{'user.domain'};
6925: my $uname = $env{'user.name'};
6926: if ($uri =~ m{^\Q$udom\E/?$}) {
6927: $ownaccess = 1;
1.1040 raeburn 6928: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6929: unless ($uri =~ m{\.\./}) {
6930: $ownaccess = 1;
6931: }
6932: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6933: my $now = time;
6934: if ($uri =~ m{^([^/]+)/?$}) {
6935: my $adom = $1;
6936: foreach my $key (keys(%env)) {
1.1042 raeburn 6937: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6938: my ($start,$end) = split('.',$env{$key});
6939: if (($now >= $start) && (!$end || $end < $now)) {
6940: $ownaccess = 1;
6941: last;
6942: }
6943: }
6944: }
6945: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6946: my $adom = $1;
6947: my $aname = $2;
1.1042 raeburn 6948: foreach my $role ('ca','aa') {
6949: if ($env{"user.role.$role./$adom/$aname"}) {
6950: my ($start,$end) =
6951: split('.',$env{"user.role.$role./$adom/$aname"});
6952: if (($now >= $start) && (!$end || $end < $now)) {
6953: $ownaccess = 1;
6954: last;
6955: }
1.1039 raeburn 6956: }
6957: }
6958: }
6959: }
6960: }
6961: }
6962: }
6963:
1.52 www 6964: # Course
6965:
1.620 albertel 6966: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6967: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6968: $thisallowed.=$1;
6969: }
1.52 www 6970: }
1.29 www 6971:
1.52 www 6972: # Domain
6973:
1.620 albertel 6974: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6975: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6976: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6977: $thisallowed.=$1;
6978: }
1.12 www 6979: }
1.52 www 6980:
1.1141 raeburn 6981: # User who is not author or co-author might still be able to edit
6982: # resource of an author in the domain (e.g., if Domain Coordinator).
6983: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6984: (&allowed('mdc',$env{'request.course.id'}))) {
6985: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6986: $thisallowed.=$1;
6987: }
6988: }
6989:
1.52 www 6990: # Course: uri itself is a course
1.66 www 6991: my $courseuri=$uri;
6992: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6993: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6994:
1.620 albertel 6995: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6996: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6997: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6998: $thisallowed.=$1;
6999: }
1.12 www 7000: }
1.29 www 7001:
1.665 albertel 7002: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7003: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7004: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7005: $thisallowed='';
1.671 raeburn 7006: my ($match)=&is_on_map($uri);
7007: if ($match) {
7008: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7009: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7010: my $value = $1;
7011: if ($noblockcheck) {
7012: $thisallowed.=$value;
1.1162 raeburn 7013: } else {
1.1172.2.65 raeburn 7014: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7015: if (@blockers > 0) {
7016: $thisallowed = 'B';
7017: } else {
7018: $thisallowed.=$value;
7019: }
1.1162 raeburn 7020: }
1.671 raeburn 7021: }
7022: } else {
1.705 albertel 7023: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7024: if ($refuri) {
7025: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7026: $thisallowed='F';
1.671 raeburn 7027: } else {
7028: $refuri=&declutter($refuri);
7029: my ($match) = &is_on_map($refuri);
7030: if ($match) {
1.1172.2.65 raeburn 7031: if ($noblockcheck) {
1.1162 raeburn 7032: $thisallowed='F';
1.1172.2.65 raeburn 7033: } else {
7034: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7035: if (@blockers > 0) {
7036: $thisallowed = 'B';
7037: } else {
7038: $thisallowed='F';
7039: }
1.1162 raeburn 7040: }
1.671 raeburn 7041: }
1.669 raeburn 7042: }
1.671 raeburn 7043: }
7044: }
1.314 www 7045: }
1.492 albertel 7046:
1.766 albertel 7047: if ($priv eq 'bre'
7048: && $thisallowed ne 'F'
7049: && $thisallowed ne '2'
7050: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7051: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7052: }
7053:
1.52 www 7054: # Full access at system, domain or course-wide level? Exit.
1.29 www 7055: if ($thisallowed=~/F/) {
7056: return 'F';
7057: }
7058:
1.52 www 7059: # If this is generating or modifying users, exit with special codes
1.29 www 7060:
1.643 www 7061: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7062: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7063: my ($audom,$auname)=split('/',$uri);
1.643 www 7064: # no author name given, so this just checks on the general right to make a co-author in this domain
7065: unless ($auname) { return $thisallowed; }
7066: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7067: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7068: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7069: ($audom ne $env{'request.role.domain'}))) { return ''; }
7070: }
1.52 www 7071: return $thisallowed;
7072: }
7073: #
1.103 harris41 7074: # Gathered so far: system, domain and course wide privileges
1.52 www 7075: #
7076: # Course: See if uri or referer is an individual resource that is part of
7077: # the course
7078:
1.620 albertel 7079: if ($env{'request.course.id'}) {
1.232 www 7080:
1.620 albertel 7081: $courseprivid=$env{'request.course.id'};
7082: if ($env{'request.course.sec'}) {
7083: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7084: }
7085: $courseprivid=~s/\_/\//;
7086: my $checkreferer=1;
1.232 www 7087: my ($match,$cond)=&is_on_map($uri);
7088: if ($match) {
7089: $statecond=$cond;
1.620 albertel 7090: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7091: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7092: my $value = $1;
7093: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7094: if ($noblockcheck) {
1.1162 raeburn 7095: $thisallowed.=$value;
1.1172.2.65 raeburn 7096: } else {
7097: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7098: if (@blockers > 0) {
7099: $thisallowed = 'B';
7100: } else {
7101: $thisallowed.=$value;
7102: }
1.1162 raeburn 7103: }
7104: } else {
7105: $thisallowed.=$value;
7106: }
1.52 www 7107: $checkreferer=0;
7108: }
1.29 www 7109: }
1.83 www 7110:
1.148 www 7111: if ($checkreferer) {
1.620 albertel 7112: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7113: unless ($refuri) {
1.800 albertel 7114: foreach my $key (keys(%env)) {
7115: if ($key=~/^httpref\..*\*/) {
7116: my $pattern=$key;
1.156 www 7117: $pattern=~s/^httpref\.\/res\///;
1.148 www 7118: $pattern=~s/\*/\[\^\/\]\+/g;
7119: $pattern=~s/\//\\\//g;
1.152 www 7120: if ($orguri=~/$pattern/) {
1.800 albertel 7121: $refuri=$env{$key};
1.148 www 7122: }
7123: }
1.191 harris41 7124: }
1.148 www 7125: }
1.232 www 7126:
1.148 www 7127: if ($refuri) {
1.152 www 7128: $refuri=&declutter($refuri);
1.232 www 7129: my ($match,$cond)=&is_on_map($refuri);
7130: if ($match) {
7131: my $refstatecond=$cond;
1.620 albertel 7132: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7133: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7134: my $value = $1;
7135: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7136: if ($noblockcheck) {
1.1162 raeburn 7137: $thisallowed.=$value;
1.1172.2.65 raeburn 7138: } else {
7139: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7140: if (@blockers > 0) {
7141: $thisallowed = 'B';
7142: } else {
7143: $thisallowed.=$value;
7144: }
1.1162 raeburn 7145: }
7146: } else {
7147: $thisallowed.=$value;
7148: }
1.53 www 7149: $uri=$refuri;
7150: $statecond=$refstatecond;
1.52 www 7151: }
7152: }
1.148 www 7153: }
1.29 www 7154: }
1.52 www 7155: }
1.29 www 7156:
1.52 www 7157: #
1.103 harris41 7158: # Gathered now: all privileges that could apply, and condition number
1.52 www 7159: #
7160: #
7161: # Full or no access?
7162: #
1.29 www 7163:
1.52 www 7164: if ($thisallowed=~/F/) {
7165: return 'F';
7166: }
1.29 www 7167:
1.52 www 7168: unless ($thisallowed) {
7169: return '';
7170: }
1.29 www 7171:
1.52 www 7172: # Restrictions exist, deal with them
7173: #
7174: # C:according to course preferences
7175: # R:according to resource settings
7176: # L:unless locked
7177: # X:according to user session state
7178: #
7179:
7180: # Possibly locked functionality, check all courses
1.54 www 7181: # Locks might take effect only after 10 minutes cache expiration for other
7182: # courses, and 2 minutes for current course
1.52 www 7183:
7184: my $envkey;
7185: if ($thisallowed=~/L/) {
1.1000 raeburn 7186: foreach $envkey (keys(%env)) {
1.54 www 7187: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7188: my $courseid=$2;
7189: my $roleid=$1.'.'.$2;
1.92 www 7190: $courseid=~s/^\///;
1.54 www 7191: my $expiretime=600;
1.620 albertel 7192: if ($env{'request.role'} eq $roleid) {
1.54 www 7193: $expiretime=120;
7194: }
7195: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7196: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7197: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7198: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7199: }
1.620 albertel 7200: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7201: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7202: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7203: &log($env{'user.domain'},$env{'user.name'},
7204: $env{'user.home'},
1.57 www 7205: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7206: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7207: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7208: return '';
7209: }
7210: }
1.620 albertel 7211: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7212: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7213: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7214: &log($env{'user.domain'},$env{'user.name'},
7215: $env{'user.home'},
1.57 www 7216: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7217: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7218: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7219: return '';
7220: }
7221: }
7222: }
1.29 www 7223: }
1.52 www 7224: }
7225:
7226: #
7227: # Rest of the restrictions depend on selected course
7228: #
7229:
1.620 albertel 7230: unless ($env{'request.course.id'}) {
1.766 albertel 7231: if ($thisallowed eq 'A') {
7232: return 'A';
1.814 raeburn 7233: } elsif ($thisallowed eq 'B') {
7234: return 'B';
1.766 albertel 7235: } else {
7236: return '1';
7237: }
1.52 www 7238: }
1.29 www 7239:
1.52 www 7240: #
7241: # Now user is definitely in a course
7242: #
1.53 www 7243:
7244:
7245: # Course preferences
7246:
7247: if ($thisallowed=~/C/) {
1.620 albertel 7248: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7249: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7250: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7251: =~/\Q$rolecode\E/) {
1.1103 raeburn 7252: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7253: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7254: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7255: $env{'request.course.id'});
7256: }
1.237 www 7257: return '';
7258: }
7259:
1.620 albertel 7260: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7261: =~/\Q$unamedom\E/) {
1.1103 raeburn 7262: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7263: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7264: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7265: $env{'request.course.id'});
7266: }
1.54 www 7267: return '';
7268: }
1.53 www 7269: }
7270:
7271: # Resource preferences
7272:
7273: if ($thisallowed=~/R/) {
1.620 albertel 7274: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7275: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7276: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7277: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7278: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7279: }
7280: return '';
1.54 www 7281: }
1.53 www 7282: }
1.30 www 7283:
1.246 www 7284: # Restricted by state or randomout?
1.30 www 7285:
1.52 www 7286: if ($thisallowed=~/X/) {
1.620 albertel 7287: if ($env{'acc.randomout'}) {
1.579 albertel 7288: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7289: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7290: return '';
7291: }
1.247 www 7292: }
7293: if (&condval($statecond)) {
1.52 www 7294: return '2';
7295: } else {
7296: return '';
7297: }
7298: }
1.30 www 7299:
1.766 albertel 7300: if ($thisallowed eq 'A') {
7301: return 'A';
1.814 raeburn 7302: } elsif ($thisallowed eq 'B') {
7303: return 'B';
1.766 albertel 7304: }
1.52 www 7305: return 'F';
1.232 www 7306: }
1.1162 raeburn 7307:
1.1172.2.13 raeburn 7308: # ------------------------------------------- Check construction space access
7309:
7310: sub constructaccess {
7311: my ($url,$setpriv)=@_;
7312:
7313: # We do not allow editing of previous versions of files
7314: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7315:
7316: # Get username and domain from URL
7317: my ($ownername,$ownerdomain,$ownerhome);
7318:
7319: ($ownerdomain,$ownername) =
7320: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7321:
7322: # The URL does not really point to any authorspace, forget it
7323: unless (($ownername) && ($ownerdomain)) { return ''; }
7324:
7325: # Now we need to see if the user has access to the authorspace of
7326: # $ownername at $ownerdomain
7327:
7328: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7329: # Real author for this?
7330: $ownerhome = $env{'user.home'};
7331: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7332: return ($ownername,$ownerdomain,$ownerhome);
7333: }
7334: } else {
7335: # Co-author for this?
7336: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7337: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7338: $ownerhome = &homeserver($ownername,$ownerdomain);
7339: return ($ownername,$ownerdomain,$ownerhome);
7340: }
7341: }
7342:
7343: # We don't have any access right now. If we are not possibly going to do anything about this,
7344: # we might as well leave
7345: unless ($setpriv) { return ''; }
7346:
7347: # Backdoor access?
7348: my $allowed=&allowed('eco',$ownerdomain);
7349: # Nope
7350: unless ($allowed) { return ''; }
7351: # Looks like we may have access, but could be locked by the owner of the construction space
7352: if ($allowed eq 'U') {
7353: my %blocked=&get('environment',['domcoord.author'],
7354: $ownerdomain,$ownername);
7355: # Is blocked by owner
7356: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7357: }
7358: if (($allowed eq 'F') || ($allowed eq 'U')) {
7359: # Grant temporary access
7360: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7361: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7362: if (!$update) { $update = $then; }
7363: my $refresh=$env{'user.refresh.time'};
7364: if (!$refresh) { $refresh = $update; }
7365: my $now = time;
7366: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7367: $now,'ca','constructaccess');
7368: $ownerhome = &homeserver($ownername,$ownerdomain);
7369: return($ownername,$ownerdomain,$ownerhome);
7370: }
7371: # No business here
7372: return '';
7373: }
7374:
1.1172.2.66 raeburn 7375: # ----------------------------------------------------------- Content Blocking
7376:
7377: {
7378: # Caches for faster Course Contents display where content blocking
7379: # is in operation (i.e., interval param set) for timed quiz.
7380: #
7381: # User for whom data are being temporarily cached.
7382: my $cacheduser='';
7383: # Cached blockers for this user (a hash of blocking items).
7384: my %cachedblockers=();
7385: # When the data were last cached.
7386: my $cachedlast='';
7387:
7388: sub load_all_blockers {
7389: my ($uname,$udom,$blocks)=@_;
7390: if (($uname ne '') && ($udom ne '')) {
7391: if (($cacheduser eq $uname.':'.$udom) &&
7392: (abs($cachedlast-time)<5)) {
7393: return;
7394: }
7395: }
7396: $cachedlast=time;
7397: $cacheduser=$uname.':'.$udom;
7398: %cachedblockers = &get_commblock_resources($blocks);
7399: }
7400:
1.1162 raeburn 7401: sub get_comm_blocks {
7402: my ($cdom,$cnum) = @_;
7403: if ($cdom eq '' || $cnum eq '') {
7404: return unless ($env{'request.course.id'});
7405: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7406: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7407: }
7408: my %commblocks;
7409: my $hashid=$cdom.'_'.$cnum;
7410: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7411: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7412: %commblocks = %{$blocksref};
7413: } else {
7414: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7415: my $cachetime = 600;
7416: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7417: }
7418: return %commblocks;
7419: }
7420:
1.1172.2.66 raeburn 7421: sub get_commblock_resources {
7422: my ($blocks) = @_;
7423: my %blockers = ();
7424: return %blockers unless ($env{'request.course.id'});
7425: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7426: my %commblocks;
7427: if (ref($blocks) eq 'HASH') {
7428: %commblocks = %{$blocks};
7429: } else {
7430: %commblocks = &get_comm_blocks();
7431: }
1.1172.2.66 raeburn 7432: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7433: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7434: return %blockers unless (ref($navmap));
7435: my $now = time;
1.1162 raeburn 7436: foreach my $block (keys(%commblocks)) {
7437: if ($block =~ /^(\d+)____(\d+)$/) {
7438: my ($start,$end) = ($1,$2);
7439: if ($start <= $now && $end >= $now) {
7440: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7441: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7442: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7443: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7444: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7445: }
7446: }
7447: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7448: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7449: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7450: }
7451: }
7452: }
7453: }
7454: }
7455: } elsif ($block =~ /^firstaccess____(.+)$/) {
7456: my $item = $1;
1.1163 raeburn 7457: my @to_test;
1.1162 raeburn 7458: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7459: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7460: my @interval;
7461: my $type = 'map';
7462: if ($item eq 'course') {
7463: $type = 'course';
7464: @interval=&EXT("resource.0.interval");
7465: } else {
7466: if ($item =~ /___\d+___/) {
7467: $type = 'resource';
7468: @interval=&EXT("resource.0.interval",$item);
7469: if (ref($navmap)) {
7470: my $res = $navmap->getBySymb($item);
7471: push(@to_test,$res);
7472: }
1.1162 raeburn 7473: } else {
1.1172.2.66 raeburn 7474: my $mapsymb = &symbread($item,1);
7475: if ($mapsymb) {
7476: if (ref($navmap)) {
7477: my $mapres = $navmap->getBySymb($mapsymb);
7478: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7479: foreach my $res (@to_test) {
7480: my $symb = $res->symb();
7481: next if ($symb eq $mapsymb);
7482: if ($symb ne '') {
7483: @interval=&EXT("resource.0.interval",$symb);
7484: if ($interval[1] eq 'map') {
7485: last;
1.1162 raeburn 7486: }
7487: }
7488: }
7489: }
7490: }
7491: }
1.1172.2.66 raeburn 7492: }
7493: if ($interval[0] =~ /^\d+$/) {
7494: my $first_access;
7495: if ($type eq 'resource') {
7496: $first_access=&get_first_access($interval[1],$item);
7497: } elsif ($type eq 'map') {
7498: $first_access=&get_first_access($interval[1],undef,$item);
7499: } else {
7500: $first_access=&get_first_access($interval[1]);
7501: }
7502: if ($first_access) {
7503: my $timesup = $first_access+$interval[0];
7504: if ($timesup > $now) {
7505: my $activeblock;
7506: foreach my $res (@to_test) {
7507: if ($res->answerable()) {
7508: $activeblock = 1;
7509: last;
7510: }
7511: }
7512: if ($activeblock) {
7513: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7514: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7515: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7516: }
7517: }
7518: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7519: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7520: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7521: }
1.1162 raeburn 7522: }
7523: }
7524: }
7525: }
7526: }
7527: }
7528: }
7529: }
7530: }
1.1172.2.66 raeburn 7531: return %blockers;
1.1162 raeburn 7532: }
7533:
1.1172.2.66 raeburn 7534: sub has_comm_blocking {
7535: my ($priv,$symb,$uri,$blocks) = @_;
7536: my @blockers;
7537: return unless ($env{'request.course.id'});
7538: return unless ($priv eq 'bre');
7539: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7540: return if ($env{'request.state'} eq 'construct');
7541: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7542: return unless (keys(%cachedblockers) > 0);
7543: my (%possibles,@symbs);
7544: if (!$symb) {
7545: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7546: }
1.1172.2.66 raeburn 7547: if ($symb) {
7548: @symbs = ($symb);
7549: } elsif (keys(%possibles)) {
7550: @symbs = keys(%possibles);
7551: }
7552: my $noblock;
7553: foreach my $symb (@symbs) {
7554: last if ($noblock);
7555: my ($map,$resid,$resurl)=&decode_symb($symb);
7556: foreach my $block (keys(%cachedblockers)) {
7557: if ($block =~ /^firstaccess____(.+)$/) {
7558: my $item = $1;
7559: if (($item eq $map) || ($item eq $symb)) {
7560: $noblock = 1;
7561: last;
7562: }
1.1162 raeburn 7563: }
1.1172.2.66 raeburn 7564: if (ref($cachedblockers{$block}) eq 'HASH') {
7565: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7566: if ($cachedblockers{$block}{'resources'}{$symb}) {
7567: unless (grep(/^\Q$block\E$/,@blockers)) {
7568: push(@blockers,$block);
7569: }
7570: }
7571: }
7572: }
7573: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7574: if ($cachedblockers{$block}{'maps'}{$map}) {
7575: unless (grep(/^\Q$block\E$/,@blockers)) {
7576: push(@blockers,$block);
7577: }
7578: }
1.1162 raeburn 7579: }
7580: }
7581: }
1.1172.2.66 raeburn 7582: return if ($noblock);
7583: return @blockers;
7584: }
1.1162 raeburn 7585: }
7586:
1.1172.2.66 raeburn 7587: # -------------------------------- Deversion and split uri into path an filename
7588:
1.1133 foxr 7589: #
1.1172.2.66 raeburn 7590: # Removes the version from a URI and
1.1133 foxr 7591: # splits it in to its filename and path to the filename.
7592: # Seems like File::Basename could have done this more clearly.
7593: # Parameters:
7594: # $uri - input URI
7595: # Returns:
7596: # Two element list consisting of
7597: # $pathname - the URI up to and excluding the trailing /
7598: # $filename - The part of the URI following the last /
7599: # NOTE:
7600: # Another realization of this is simply:
7601: # use File::Basename;
7602: # ...
7603: # $uri = shift;
7604: # $filename = basename($uri);
7605: # $path = dirname($uri);
7606: # return ($filename, $path);
7607: #
7608: # The implementation below is probably faster however.
7609: #
1.710 albertel 7610: sub split_uri_for_cond {
7611: my $uri=&deversion(&declutter(shift));
7612: my @uriparts=split(/\//,$uri);
7613: my $filename=pop(@uriparts);
7614: my $pathname=join('/',@uriparts);
7615: return ($pathname,$filename);
7616: }
1.232 www 7617: # --------------------------------------------------- Is a resource on the map?
7618:
7619: sub is_on_map {
1.710 albertel 7620: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7621: #Trying to find the conditional for the file
1.620 albertel 7622: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7623: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7624: if ($match) {
1.289 bowersj2 7625: return (1,$1);
7626: } else {
1.434 www 7627: return (0,0);
1.289 bowersj2 7628: }
1.12 www 7629: }
7630:
1.427 www 7631: # --------------------------------------------------------- Get symb from alias
7632:
7633: sub get_symb_from_alias {
7634: my $symb=shift;
7635: my ($map,$resid,$url)=&decode_symb($symb);
7636: # Already is a symb
7637: if ($url) { return $symb; }
7638: # Must be an alias
7639: my $aliassymb='';
7640: my %bighash;
1.620 albertel 7641: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7642: &GDBM_READER(),0640)) {
7643: my $rid=$bighash{'mapalias_'.$symb};
7644: if ($rid) {
7645: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7646: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7647: $resid,$bighash{'src_'.$rid});
1.427 www 7648: }
7649: untie %bighash;
7650: }
7651: return $aliassymb;
7652: }
7653:
1.12 www 7654: # ----------------------------------------------------------------- Define Role
7655:
7656: sub definerole {
7657: if (allowed('mcr','/')) {
7658: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7659: foreach my $role (split(':',$sysrole)) {
7660: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7661: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7662: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7663: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7664: return "refused:s:$crole&$cqual";
7665: }
7666: }
1.191 harris41 7667: }
1.800 albertel 7668: foreach my $role (split(':',$domrole)) {
7669: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7670: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7671: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7672: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7673: return "refused:d:$crole&$cqual";
7674: }
7675: }
1.191 harris41 7676: }
1.800 albertel 7677: foreach my $role (split(':',$courole)) {
7678: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7679: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7680: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7681: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7682: return "refused:c:$crole&$cqual";
7683: }
7684: }
1.191 harris41 7685: }
1.620 albertel 7686: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7687: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7688: "rolesdef_$rolename=".
7689: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7690: return reply($command,$env{'user.home'});
1.12 www 7691: } else {
7692: return 'refused';
7693: }
1.105 harris41 7694: }
7695:
7696: # ---------------- Make a metadata query against the network of library servers
7697:
7698: sub metadata_query {
1.1172.2.33 raeburn 7699: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7700: my %rhash;
1.845 albertel 7701: my %libserv = &all_library();
1.244 matthew 7702: my @server_list = (defined($server_array) ? @$server_array
7703: : keys(%libserv) );
7704: for my $server (@server_list) {
1.1172.2.33 raeburn 7705: my $domains = '';
7706: if (ref($domains_hash) eq 'HASH') {
7707: $domains = $domains_hash->{$server};
7708: }
1.118 harris41 7709: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7710: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7711: $rhash{$server}=$reply;
7712: }
7713: else {
7714: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7715: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7716: $server);
7717: $rhash{$server}=$reply;
7718: }
1.112 harris41 7719: }
1.118 harris41 7720: return \%rhash;
1.240 www 7721: }
7722:
7723: # ----------------------------------------- Send log queries and wait for reply
7724:
7725: sub log_query {
7726: my ($uname,$udom,$query,%filters)=@_;
7727: my $uhome=&homeserver($uname,$udom);
7728: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7729: my $uhost=&hostname($uhome);
1.800 albertel 7730: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7731: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7732: $uhome);
1.479 albertel 7733: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7734: return get_query_reply($queryid);
7735: }
7736:
1.818 raeburn 7737: # -------------------------- Update MySQL table for portfolio file
7738:
7739: sub update_portfolio_table {
1.821 raeburn 7740: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7741: if ($group ne '') {
7742: $file_name =~s /^\Q$group\E//;
7743: }
1.818 raeburn 7744: my $homeserver = &homeserver($uname,$udom);
7745: my $queryid=
1.821 raeburn 7746: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7747: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7748: my $reply = &get_query_reply($queryid);
7749: return $reply;
7750: }
7751:
1.899 raeburn 7752: # -------------------------- Update MySQL allusers table
7753:
7754: sub update_allusers_table {
7755: my ($uname,$udom,$names) = @_;
7756: my $homeserver = &homeserver($uname,$udom);
7757: my $queryid=
7758: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7759: 'lastname='.&escape($names->{'lastname'}).'%%'.
7760: 'firstname='.&escape($names->{'firstname'}).'%%'.
7761: 'middlename='.&escape($names->{'middlename'}).'%%'.
7762: 'generation='.&escape($names->{'generation'}).'%%'.
7763: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7764: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7765: return;
1.899 raeburn 7766: }
7767:
1.508 raeburn 7768: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7769:
7770: sub fetch_enrollment_query {
1.511 raeburn 7771: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 7772: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7773: my $maxtries = 1;
1.508 raeburn 7774: if ($context eq 'automated') {
7775: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 7776: $sleep = 2;
7777: $loopmax = 100;
1.547 raeburn 7778: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7779: } else {
7780: $homeserver = &homeserver($cnum,$dom);
7781: }
1.838 albertel 7782: my $host=&hostname($homeserver);
1.506 raeburn 7783: my $cmd = '';
1.1000 raeburn 7784: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7785: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7786: }
7787: $cmd =~ s/%%$//;
7788: $cmd = &escape($cmd);
7789: my $query = 'fetchenrollment';
1.620 albertel 7790: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7791: unless ($queryid=~/^\Q$host\E\_/) {
7792: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7793: return 'error: '.$queryid;
7794: }
1.1172.2.79 raeburn 7795: my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547 raeburn 7796: my $tries = 1;
7797: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 7798: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7799: $tries ++;
7800: }
1.526 raeburn 7801: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7802: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7803: } else {
1.901 albertel 7804: my @responses = split(/:/,$reply);
1.1172.2.82! raeburn 7805: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 7806: foreach my $line (@responses) {
7807: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7808: $$replyref{$key} = $value;
7809: }
7810: } else {
1.1117 foxr 7811: my $pathname = LONCAPA::tempdir();
1.800 albertel 7812: foreach my $line (@responses) {
7813: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7814: $$replyref{$key} = $value;
7815: if ($value > 0) {
1.800 albertel 7816: foreach my $item (@{$$affiliatesref{$key}}) {
7817: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7818: my $destname = $pathname.'/'.$filename;
7819: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7820: if ($xml_classlist =~ /^error/) {
7821: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7822: } else {
1.506 raeburn 7823: if ( open(FILE,">$destname") ) {
7824: print FILE &unescape($xml_classlist);
7825: close(FILE);
1.526 raeburn 7826: } else {
7827: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7828: }
7829: }
7830: }
7831: }
7832: }
7833: }
7834: return 'ok';
7835: }
7836: return 'error';
7837: }
7838:
1.242 www 7839: sub get_query_reply {
1.1172.2.79 raeburn 7840: my ($queryid,$sleep,$loopmax) = @_;
7841: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
7842: $sleep = 0.2;
7843: }
7844: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
7845: $loopmax = 100;
7846: }
1.1117 foxr 7847: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7848: my $reply='';
1.1172.2.79 raeburn 7849: for (1..$loopmax) {
7850: sleep($sleep);
1.240 www 7851: if (-e $replyfile.'.end') {
1.448 albertel 7852: if (open(my $fh,$replyfile)) {
1.904 albertel 7853: $reply = join('',<$fh>);
7854: close($fh);
1.240 www 7855: } else { return 'error: reply_file_error'; }
1.242 www 7856: return &unescape($reply);
7857: }
1.240 www 7858: }
1.242 www 7859: return 'timeout:'.$queryid;
1.240 www 7860: }
7861:
7862: sub courselog_query {
1.241 www 7863: #
7864: # possible filters:
7865: # url: url or symb
7866: # username
7867: # domain
7868: # action: view, submit, grade
7869: # start: timestamp
7870: # end: timestamp
7871: #
1.240 www 7872: my (%filters)=@_;
1.620 albertel 7873: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7874: if ($filters{'url'}) {
7875: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7876: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7877: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7878: }
1.620 albertel 7879: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7880: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7881: return &log_query($cname,$cdom,'courselog',%filters);
7882: }
7883:
7884: sub userlog_query {
1.858 raeburn 7885: #
7886: # possible filters:
7887: # action: log check role
7888: # start: timestamp
7889: # end: timestamp
7890: #
1.240 www 7891: my ($uname,$udom,%filters)=@_;
7892: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7893: }
7894:
1.506 raeburn 7895: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7896:
7897: sub auto_run {
1.508 raeburn 7898: my ($cnum,$cdom) = @_;
1.876 raeburn 7899: my $response = 0;
7900: my $settings;
7901: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7902: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7903: $settings = $domconfig{'autoenroll'};
7904: if ($settings->{'run'} eq '1') {
7905: $response = 1;
7906: }
7907: } else {
1.934 raeburn 7908: my $homeserver;
7909: if (&is_course($cdom,$cnum)) {
7910: $homeserver = &homeserver($cnum,$cdom);
7911: } else {
7912: $homeserver = &domain($cdom,'primary');
7913: }
7914: if ($homeserver ne 'no_host') {
7915: $response = &reply('autorun:'.$cdom,$homeserver);
7916: }
1.876 raeburn 7917: }
1.506 raeburn 7918: return $response;
7919: }
1.776 albertel 7920:
1.506 raeburn 7921: sub auto_get_sections {
1.508 raeburn 7922: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7923: my $homeserver;
7924: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7925: $homeserver = &homeserver($cnum,$cdom);
7926: }
7927: if (!defined($homeserver)) {
7928: if ($cdom =~ /^$match_domain$/) {
7929: $homeserver = &domain($cdom,'primary');
7930: }
7931: }
7932: my @secs;
7933: if (defined($homeserver)) {
7934: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7935: unless ($response eq 'refused') {
7936: @secs = split(/:/,$response);
7937: }
1.506 raeburn 7938: }
7939: return @secs;
7940: }
1.776 albertel 7941:
1.506 raeburn 7942: sub auto_new_course {
1.1099 raeburn 7943: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7944: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7945: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7946: return $response;
7947: }
1.776 albertel 7948:
1.506 raeburn 7949: sub auto_validate_courseID {
1.508 raeburn 7950: my ($cnum,$cdom,$inst_course_id) = @_;
7951: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7952: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7953: return $response;
7954: }
1.776 albertel 7955:
1.1007 raeburn 7956: sub auto_validate_instcode {
1.1020 raeburn 7957: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7958: my ($homeserver,$response);
7959: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7960: $homeserver = &homeserver($cnum,$cdom);
7961: }
7962: if (!defined($homeserver)) {
7963: if ($cdom =~ /^$match_domain$/) {
7964: $homeserver = &domain($cdom,'primary');
7965: }
7966: }
1.1065 raeburn 7967: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7968: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7969: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7970: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7971: }
7972:
1.506 raeburn 7973: sub auto_create_password {
1.873 raeburn 7974: my ($cnum,$cdom,$authparam,$udom) = @_;
7975: my ($homeserver,$response);
1.506 raeburn 7976: my $create_passwd = 0;
7977: my $authchk = '';
1.873 raeburn 7978: if ($udom =~ /^$match_domain$/) {
7979: $homeserver = &domain($udom,'primary');
7980: }
7981: if ($homeserver eq '') {
7982: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7983: $homeserver = &homeserver($cnum,$cdom);
7984: }
7985: }
7986: if ($homeserver eq '') {
7987: $authchk = 'nodomain';
1.506 raeburn 7988: } else {
1.873 raeburn 7989: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7990: if ($response eq 'refused') {
7991: $authchk = 'refused';
7992: } else {
1.901 albertel 7993: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7994: }
1.506 raeburn 7995: }
7996: return ($authparam,$create_passwd,$authchk);
7997: }
7998:
1.706 raeburn 7999: sub auto_photo_permission {
8000: my ($cnum,$cdom,$students) = @_;
8001: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8002: my ($outcome,$perm_reqd,$conditions) =
8003: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8004: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8005: return (undef,undef);
8006: }
1.706 raeburn 8007: return ($outcome,$perm_reqd,$conditions);
8008: }
8009:
8010: sub auto_checkphotos {
8011: my ($uname,$udom,$pid) = @_;
8012: my $homeserver = &homeserver($uname,$udom);
8013: my ($result,$resulttype);
8014: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8015: &escape($uname).':'.&escape($pid),
8016: $homeserver));
1.709 albertel 8017: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8018: return (undef,undef);
8019: }
1.706 raeburn 8020: if ($outcome) {
8021: ($result,$resulttype) = split(/:/,$outcome);
8022: }
8023: return ($result,$resulttype);
8024: }
8025:
8026: sub auto_photochoice {
8027: my ($cnum,$cdom) = @_;
8028: my $homeserver = &homeserver($cnum,$cdom);
8029: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8030: &escape($cdom),
8031: $homeserver)));
1.709 albertel 8032: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8033: return (undef,undef);
8034: }
1.706 raeburn 8035: return ($update,$comment);
8036: }
8037:
8038: sub auto_photoupdate {
8039: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8040: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8041: my $host=&hostname($homeserver);
1.706 raeburn 8042: my $cmd = '';
8043: my $maxtries = 1;
1.800 albertel 8044: foreach my $affiliate (keys(%{$affiliatesref})) {
8045: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8046: }
8047: $cmd =~ s/%%$//;
8048: $cmd = &escape($cmd);
8049: my $query = 'institutionalphotos';
8050: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8051: unless ($queryid=~/^\Q$host\E\_/) {
8052: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8053: return 'error: '.$queryid;
8054: }
8055: my $reply = &get_query_reply($queryid);
8056: my $tries = 1;
8057: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8058: $reply = &get_query_reply($queryid);
8059: $tries ++;
8060: }
8061: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8062: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8063: } else {
8064: my @responses = split(/:/,$reply);
8065: my $outcome = shift(@responses);
8066: foreach my $item (@responses) {
8067: my ($key,$value) = split(/=/,$item);
8068: $$photo{$key} = $value;
8069: }
8070: return $outcome;
8071: }
8072: return 'error';
8073: }
8074:
1.521 raeburn 8075: sub auto_instcode_format {
1.793 albertel 8076: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8077: $cat_order) = @_;
1.521 raeburn 8078: my $courses = '';
1.772 raeburn 8079: my @homeservers;
1.521 raeburn 8080: if ($caller eq 'global') {
1.841 albertel 8081: my %servers = &get_servers($codedom,'library');
8082: foreach my $tryserver (keys(%servers)) {
8083: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8084: push(@homeservers,$tryserver);
8085: }
1.584 raeburn 8086: }
1.1022 raeburn 8087: } elsif ($caller eq 'requests') {
8088: if ($codedom =~ /^$match_domain$/) {
8089: my $chome = &domain($codedom,'primary');
8090: unless ($chome eq 'no_host') {
8091: push(@homeservers,$chome);
8092: }
8093: }
1.521 raeburn 8094: } else {
1.772 raeburn 8095: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8096: }
1.793 albertel 8097: foreach my $code (keys(%{$instcodes})) {
8098: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8099: }
8100: chop($courses);
1.772 raeburn 8101: my $ok_response = 0;
8102: my $response;
8103: while (@homeservers > 0 && $ok_response == 0) {
8104: my $server = shift(@homeservers);
8105: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8106: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8107: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8108: split(/:/,$response);
1.772 raeburn 8109: %{$codes} = (%{$codes},&str2hash($codes_str));
8110: push(@{$codetitles},&str2array($codetitles_str));
8111: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8112: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8113: $ok_response = 1;
8114: }
8115: }
8116: if ($ok_response) {
1.521 raeburn 8117: return 'ok';
1.772 raeburn 8118: } else {
8119: return $response;
1.521 raeburn 8120: }
8121: }
8122:
1.792 raeburn 8123: sub auto_instcode_defaults {
8124: my ($domain,$returnhash,$code_order) = @_;
8125: my @homeservers;
1.841 albertel 8126:
8127: my %servers = &get_servers($domain,'library');
8128: foreach my $tryserver (keys(%servers)) {
8129: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8130: push(@homeservers,$tryserver);
8131: }
1.792 raeburn 8132: }
1.841 albertel 8133:
1.792 raeburn 8134: my $response;
1.841 albertel 8135: foreach my $server (@homeservers) {
1.792 raeburn 8136: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8137: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8138:
8139: foreach my $pair (split(/\&/,$response)) {
8140: my ($name,$value)=split(/\=/,$pair);
8141: if ($name eq 'code_order') {
8142: @{$code_order} = split(/\&/,&unescape($value));
8143: } else {
8144: $returnhash->{&unescape($name)}=&unescape($value);
8145: }
8146: }
8147: return 'ok';
1.792 raeburn 8148: }
1.841 albertel 8149:
8150: return $response;
1.1003 raeburn 8151: }
8152:
8153: sub auto_possible_instcodes {
1.1007 raeburn 8154: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8155: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8156: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8157: return;
8158: }
1.1003 raeburn 8159: my (@homeservers,$uhome);
8160: if (defined(&domain($domain,'primary'))) {
8161: $uhome=&domain($domain,'primary');
8162: push(@homeservers,&domain($domain,'primary'));
8163: } else {
8164: my %servers = &get_servers($domain,'library');
8165: foreach my $tryserver (keys(%servers)) {
8166: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8167: push(@homeservers,$tryserver);
8168: }
8169: }
8170: }
8171: my $response;
8172: foreach my $server (@homeservers) {
8173: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8174: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8175: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8176: split(':',$response);
8177: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8178: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8179: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8180: my ($name,$value)=split('=',$item);
8181: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8182: }
8183: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8184: my ($name,$value)=split('=',$item);
8185: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8186: }
8187: return 'ok';
8188: }
8189: return $response;
8190: }
1.792 raeburn 8191:
1.1010 raeburn 8192: sub auto_courserequest_checks {
8193: my ($dom) = @_;
1.1020 raeburn 8194: my ($homeserver,%validations);
8195: if ($dom =~ /^$match_domain$/) {
8196: $homeserver = &domain($dom,'primary');
8197: }
8198: unless ($homeserver eq 'no_host') {
8199: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8200: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8201: my @items = split(/&/,$response);
8202: foreach my $item (@items) {
8203: my ($key,$value) = split('=',$item);
8204: $validations{&unescape($key)} = &thaw_unescape($value);
8205: }
8206: }
8207: }
1.1010 raeburn 8208: return %validations;
8209: }
8210:
1.1020 raeburn 8211: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8212: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8213: my ($homeserver,$response);
8214: if ($dom =~ /^$match_domain$/) {
8215: $homeserver = &domain($dom,'primary');
8216: }
1.1172.2.43 raeburn 8217: unless ($homeserver eq 'no_host') {
8218: my $customdata;
8219: if (ref($custominfo) eq 'HASH') {
8220: $customdata = &freeze_escape($custominfo);
8221: }
1.1020 raeburn 8222: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8223: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8224: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8225: $customdata,$homeserver));
1.1020 raeburn 8226: }
8227: return $response;
8228: }
8229:
1.777 albertel 8230: sub auto_validate_class_sec {
1.918 raeburn 8231: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8232: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8233: my $ownerlist;
8234: if (ref($owners) eq 'ARRAY') {
8235: $ownerlist = join(',',@{$owners});
8236: } else {
8237: $ownerlist = $owners;
8238: }
1.773 raeburn 8239: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8240: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8241: return $response;
8242: }
8243:
1.1172.2.38 raeburn 8244: sub auto_crsreq_update {
8245: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8246: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8247: my ($homeserver,%crsreqresponse);
8248: if ($cdom =~ /^$match_domain$/) {
8249: $homeserver = &domain($cdom,'primary');
8250: }
8251: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8252: my $info;
8253: if (ref($inbound) eq 'HASH') {
8254: $info = &freeze_escape($inbound);
8255: }
8256: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8257: ':'.&escape($action).':'.&escape($ownername).':'.
8258: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8259: &escape($title).':'.&escape($code).':'.
8260: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8261: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8262: my @items = split(/&/,$response);
8263: foreach my $item (@items) {
8264: my ($key,$value) = split('=',$item);
8265: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8266: }
8267: }
8268: }
8269: return \%crsreqresponse;
8270: }
8271:
1.1172.2.78 raeburn 8272: sub auto_export_grades {
8273: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8274: my ($homeserver,%exportresponse);
8275: if ($cdom =~ /^$match_domain$/) {
8276: $homeserver = &domain($cdom,'primary');
8277: }
8278: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8279: my $info;
8280: if (ref($inforef) eq 'HASH') {
8281: $info = &freeze_escape($inforef);
8282: }
8283: if (ref($gradesref) eq 'HASH') {
8284: my $grades = &freeze_escape($gradesref);
8285: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8286: $info.':'.$grades,$homeserver);
8287: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8288: my @items = split(/&/,$response);
8289: foreach my $item (@items) {
8290: my ($key,$value) = split('=',$item);
8291: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8292: }
8293: }
8294: }
8295: }
8296: return \%exportresponse;
8297: }
8298:
1.1172.2.68 raeburn 8299: sub check_instcode_cloning {
8300: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8301: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8302: return;
8303: }
8304: my $canclone;
8305: if (@{$code_order} > 0) {
8306: my $instcoderegexp ='^';
8307: my @clonecodes = split(/\&/,$cloner);
8308: foreach my $item (@{$code_order}) {
8309: if (grep(/^\Q$item\E=/,@clonecodes)) {
8310: foreach my $pair (@clonecodes) {
8311: my ($key,$val) = split(/\=/,$pair,2);
8312: $val = &unescape($val);
8313: if ($key eq $item) {
8314: $instcoderegexp .= '('.$val.')';
8315: last;
8316: }
8317: }
8318: } else {
8319: $instcoderegexp .= $codedefaults->{$item};
8320: }
8321: }
8322: $instcoderegexp .= '$';
8323: my (@from,@to);
8324: eval {
8325: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8326: (@to) = ($clonetocode =~ /$instcoderegexp/);
8327: };
8328: if ((@from > 0) && (@to > 0)) {
8329: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8330: if (!@diffs) {
8331: $canclone = 1;
8332: }
8333: }
8334: }
8335: return $canclone;
8336: }
8337:
8338: sub default_instcode_cloning {
8339: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8340: my (%codedefaults,@code_order,$canclone);
8341: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8342: %codedefaults = %{$codedefaultsref};
8343: @code_order = @{$codeorderref};
8344: } elsif ($clonedom) {
8345: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8346: }
8347: if (($domdefclone) && (@code_order)) {
8348: my @clonecodes = split(/\+/,$domdefclone);
8349: my $instcoderegexp ='^';
8350: foreach my $item (@code_order) {
8351: if (grep(/^\Q$item\E$/,@clonecodes)) {
8352: $instcoderegexp .= '('.$codedefaults{$item}.')';
8353: } else {
8354: $instcoderegexp .= $codedefaults{$item};
8355: }
8356: }
8357: $instcoderegexp .= '$';
8358: my (@from,@to);
8359: eval {
8360: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8361: (@to) = ($clonetocode =~ /$instcoderegexp/);
8362: };
8363: if ((@from > 0) && (@to > 0)) {
8364: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8365: if (!@diffs) {
8366: $canclone = 1;
8367: }
8368: }
8369: }
8370: return $canclone;
8371: }
8372:
1.679 raeburn 8373: # ------------------------------------------------------- Course Group routines
8374:
8375: sub get_coursegroups {
1.809 raeburn 8376: my ($cdom,$cnum,$group,$namespace) = @_;
8377: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8378: }
8379:
1.679 raeburn 8380: sub modify_coursegroup {
8381: my ($cdom,$cnum,$groupsettings) = @_;
8382: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8383: }
8384:
1.809 raeburn 8385: sub toggle_coursegroup_status {
8386: my ($cdom,$cnum,$group,$action) = @_;
8387: my ($from_namespace,$to_namespace);
8388: if ($action eq 'delete') {
8389: $from_namespace = 'coursegroups';
8390: $to_namespace = 'deleted_groups';
8391: } else {
8392: $from_namespace = 'deleted_groups';
8393: $to_namespace = 'coursegroups';
8394: }
8395: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8396: if (my $tmp = &error(%curr_group)) {
8397: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8398: return ('read error',$tmp);
8399: } else {
8400: my %savedsettings = %curr_group;
1.809 raeburn 8401: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8402: my $deloutcome;
8403: if ($result eq 'ok') {
1.809 raeburn 8404: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8405: } else {
8406: return ('write error',$result);
8407: }
8408: if ($deloutcome eq 'ok') {
8409: return 'ok';
8410: } else {
8411: return ('delete error',$deloutcome);
8412: }
8413: }
8414: }
8415:
1.679 raeburn 8416: sub modify_group_roles {
1.957 raeburn 8417: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8418: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8419: my $role = 'gr/'.&escape($userprivs);
8420: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8421: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8422: if ($result eq 'ok') {
8423: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8424: }
1.679 raeburn 8425: return $result;
8426: }
8427:
8428: sub modify_coursegroup_membership {
8429: my ($cdom,$cnum,$membership) = @_;
8430: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8431: return $result;
8432: }
8433:
1.682 raeburn 8434: sub get_active_groups {
8435: my ($udom,$uname,$cdom,$cnum) = @_;
8436: my $now = time;
8437: my %groups = ();
8438: foreach my $key (keys(%env)) {
1.811 albertel 8439: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8440: my ($start,$end) = split(/\./,$env{$key});
8441: if (($end!=0) && ($end<$now)) { next; }
8442: if (($start!=0) && ($start>$now)) { next; }
8443: if ($1 eq $cdom && $2 eq $cnum) {
8444: $groups{$3} = $env{$key} ;
8445: }
8446: }
8447: }
8448: return %groups;
8449: }
8450:
1.683 raeburn 8451: sub get_group_membership {
8452: my ($cdom,$cnum,$group) = @_;
8453: return(&dump('groupmembership',$cdom,$cnum,$group));
8454: }
8455:
8456: sub get_users_groups {
8457: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8458: my @usersgroups;
1.683 raeburn 8459: my $cachetime=1800;
8460:
8461: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8462: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8463: if (defined($cached)) {
1.734 albertel 8464: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8465: } else {
8466: $grouplist = '';
1.816 raeburn 8467: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8468: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8469: my $access_end = $env{'course.'.$courseid.
8470: '.default_enrollment_end_date'};
8471: my $now = time;
8472: foreach my $key (keys(%roleshash)) {
8473: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8474: my $group = $1;
8475: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8476: my $start = $2;
8477: my $end = $1;
8478: if ($start == -1) { next; } # deleted from group
8479: if (($start!=0) && ($start>$now)) { next; }
8480: if (($end!=0) && ($end<$now)) {
8481: if ($access_end && $access_end < $now) {
8482: if ($access_end - $end < 86400) {
8483: push(@usersgroups,$group);
1.733 raeburn 8484: }
8485: }
1.817 raeburn 8486: next;
1.733 raeburn 8487: }
1.817 raeburn 8488: push(@usersgroups,$group);
1.683 raeburn 8489: }
8490: }
8491: }
1.817 raeburn 8492: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8493: $grouplist = join(':',@usersgroups);
8494: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8495: }
1.733 raeburn 8496: return @usersgroups;
1.683 raeburn 8497: }
8498:
8499: sub devalidate_getgroups_cache {
8500: my ($udom,$uname,$cdom,$cnum)=@_;
8501: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8502:
1.683 raeburn 8503: my $hashid="$udom:$uname:$courseid";
8504: &devalidate_cache_new('getgroups',$hashid);
8505: }
8506:
1.12 www 8507: # ------------------------------------------------------------------ Plain Text
8508:
8509: sub plaintext {
1.988 raeburn 8510: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8511: if ($short =~ m{^cr/}) {
1.758 albertel 8512: return (split('/',$short))[-1];
8513: }
1.742 raeburn 8514: if (!defined($cid)) {
8515: $cid = $env{'request.course.id'};
8516: }
8517: my %rolenames = (
1.1008 raeburn 8518: Course => 'std',
8519: Community => 'alt1',
1.742 raeburn 8520: );
1.1037 raeburn 8521: if ($cid ne '') {
8522: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8523: unless ($forcedefault) {
8524: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8525: &Apache::lonlocal::mt_escape(\$roletext);
8526: return &Apache::lonlocal::mt($roletext);
8527: }
8528: }
8529: }
8530: if ((defined($type)) && (defined($rolenames{$type})) &&
8531: (defined($rolenames{$type})) &&
8532: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8533: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8534: } elsif ($cid ne '') {
8535: my $crstype = $env{'course.'.$cid.'.type'};
8536: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8537: (defined($prp{$short}{$rolenames{$crstype}}))) {
8538: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8539: }
1.742 raeburn 8540: }
1.1037 raeburn 8541: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8542: }
8543:
8544: # ----------------------------------------------------------------- Assign Role
8545:
8546: sub assignrole {
1.957 raeburn 8547: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8548: $context)=@_;
1.21 www 8549: my $mrole;
8550: if ($role =~ /^cr\//) {
1.393 www 8551: my $cwosec=$url;
1.811 albertel 8552: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8553: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8554: my $refused = 1;
8555: if ($context eq 'requestcourses') {
8556: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8557: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8558: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8559: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8560: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8561: if ($crsenv{'internal.courseowner'} eq
8562: $env{'user.name'}.':'.$env{'user.domain'}) {
8563: $refused = '';
8564: }
8565: }
8566: }
8567: }
8568: }
8569: if ($refused) {
8570: &logthis('Refused custom assignrole: '.
8571: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8572: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8573: return 'refused';
8574: }
1.104 www 8575: }
1.21 www 8576: $mrole='cr';
1.678 raeburn 8577: } elsif ($role =~ /^gr\//) {
8578: my $cwogrp=$url;
1.811 albertel 8579: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8580: unless (&allowed('mdg',$cwogrp)) {
8581: &logthis('Refused group assignrole: '.
8582: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8583: $env{'user.name'}.' at '.$env{'user.domain'});
8584: return 'refused';
8585: }
8586: $mrole='gr';
1.21 www 8587: } else {
1.82 www 8588: my $cwosec=$url;
1.811 albertel 8589: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8590: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8591: my $refused;
8592: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8593: if (!(&allowed('c'.$role,$url))) {
8594: $refused = 1;
8595: }
8596: } else {
8597: $refused = 1;
8598: }
1.947 raeburn 8599: if ($refused) {
1.1045 raeburn 8600: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8601: if (!$selfenroll && $context eq 'course') {
8602: my %crsenv;
8603: if ($role eq 'cc' || $role eq 'co') {
8604: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8605: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8606: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8607: if ($crsenv{'internal.courseowner'} eq
8608: $env{'user.name'}.':'.$env{'user.domain'}) {
8609: $refused = '';
8610: }
8611: }
8612: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8613: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8614: if ($crsenv{'internal.courseowner'} eq
8615: $env{'user.name'}.':'.$env{'user.domain'}) {
8616: $refused = '';
8617: }
8618: }
8619: }
8620: }
8621: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8622: $refused = '';
1.1017 raeburn 8623: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8624: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8625: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8626: my $wrongcc;
8627: if ($cnum =~ /^$match_community$/) {
8628: $wrongcc = 1 if ($role eq 'cc');
8629: } else {
8630: $wrongcc = 1 if ($role eq 'co');
8631: }
8632: unless ($wrongcc) {
8633: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8634: if ($crsenv{'internal.courseowner'} eq
8635: $env{'user.name'}.':'.$env{'user.domain'}) {
8636: $refused = '';
8637: }
1.1017 raeburn 8638: }
8639: }
1.1172.2.9 raeburn 8640: } elsif ($context eq 'requestauthor') {
8641: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8642: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8643: if ($env{'environment.requestauthor'} eq 'automatic') {
8644: $refused = '';
8645: } else {
8646: my %domdefaults = &get_domain_defaults($udom);
8647: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8648: my $checkbystatus;
8649: if ($env{'user.adv'}) {
8650: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8651: if ($disposition eq 'automatic') {
8652: $refused = '';
8653: } elsif ($disposition eq '') {
8654: $checkbystatus = 1;
8655: }
8656: } else {
8657: $checkbystatus = 1;
8658: }
8659: if ($checkbystatus) {
8660: if ($env{'environment.inststatus'}) {
8661: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8662: foreach my $type (@inststatuses) {
8663: if (($type ne '') &&
8664: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8665: $refused = '';
8666: }
8667: }
8668: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8669: $refused = '';
8670: }
8671: }
8672: }
8673: }
8674: }
1.1017 raeburn 8675: }
8676: if ($refused) {
1.947 raeburn 8677: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8678: ' '.$role.' '.$end.' '.$start.' by '.
8679: $env{'user.name'}.' at '.$env{'user.domain'});
8680: return 'refused';
8681: }
1.932 raeburn 8682: }
1.1131 raeburn 8683: } elsif ($role eq 'au') {
8684: if ($url ne '/'.$udom.'/') {
8685: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8686: ' to assign author role for '.$uname.':'.$udom.
8687: ' in domain: '.$url.' refused (wrong domain).');
8688: return 'refused';
8689: }
1.104 www 8690: }
1.21 www 8691: $mrole=$role;
8692: }
1.620 albertel 8693: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8694: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8695: if ($end) { $command.='_'.$end; }
1.21 www 8696: if ($start) {
8697: if ($end) {
1.81 www 8698: $command.='_'.$start;
1.21 www 8699: } else {
1.81 www 8700: $command.='_0_'.$start;
1.21 www 8701: }
8702: }
1.739 raeburn 8703: my $origstart = $start;
8704: my $origend = $end;
1.957 raeburn 8705: my $delflag;
1.357 www 8706: # actually delete
8707: if ($deleteflag) {
1.373 www 8708: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8709: # modify command to delete the role
1.620 albertel 8710: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8711: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8712: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8713: # set start and finish to negative values for userrolelog
8714: $start=-1;
8715: $end=-1;
1.957 raeburn 8716: $delflag = 1;
1.357 www 8717: }
8718: }
8719: # send command
1.349 www 8720: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8721: # log new user role if status is ok
1.349 www 8722: if ($answer eq 'ok') {
1.663 raeburn 8723: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8724: if (($role eq 'cc') || ($role eq 'in') ||
8725: ($role eq 'ep') || ($role eq 'ad') ||
8726: ($role eq 'ta') || ($role eq 'st') ||
8727: ($role=~/^cr/) || ($role eq 'gr') ||
8728: ($role eq 'co')) {
1.1172.2.13 raeburn 8729: # for course roles, perform group memberships changes triggered by role change.
8730: unless ($role =~ /^gr/) {
8731: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8732: $origstart,$selfenroll,$context);
8733: }
1.1172.2.9 raeburn 8734: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8735: $selfenroll,$context);
8736: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8737: ($role eq 'au') || ($role eq 'dc')) {
8738: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8739: $context);
8740: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8741: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8742: $context);
8743: }
1.1053 raeburn 8744: if ($role eq 'cc') {
8745: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8746: }
1.349 www 8747: }
8748: return $answer;
1.169 harris41 8749: }
8750:
1.1053 raeburn 8751: sub autoupdate_coowners {
8752: my ($url,$end,$start,$uname,$udom) = @_;
8753: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8754: if (($cdom ne '') && ($cnum ne '')) {
8755: my $now = time;
8756: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8757: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8758: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8759: my $instcode = $coursehash{'internal.coursecode'};
8760: if ($instcode ne '') {
1.1056 raeburn 8761: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8762: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8763: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8764: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8765: if ($result eq 'valid') {
8766: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8767: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8768: push(@newcoowners,$coowner);
8769: }
8770: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8771: push(@newcoowners,$uname.':'.$udom);
8772: }
8773: @newcoowners = sort(@newcoowners);
8774: } else {
8775: push(@newcoowners,$uname.':'.$udom);
8776: }
8777: } else {
8778: if ($coursehash{'internal.co-owners'}) {
8779: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8780: unless ($coowner eq $uname.':'.$udom) {
8781: push(@newcoowners,$coowner);
8782: }
8783: }
8784: unless (@newcoowners > 0) {
8785: $delcoowners = 1;
8786: $coowners = '';
8787: }
8788: }
8789: }
8790: if (@newcoowners || $delcoowners) {
8791: &store_coowners($cdom,$cnum,$coursehash{'home'},
8792: $delcoowners,@newcoowners);
8793: }
8794: }
8795: }
8796: }
8797: }
8798: }
8799: }
8800:
8801: sub store_coowners {
8802: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8803: my $cid = $cdom.'_'.$cnum;
8804: my ($coowners,$delresult,$putresult);
8805: if (@newcoowners) {
8806: $coowners = join(',',@newcoowners);
8807: my %coownershash = (
8808: 'internal.co-owners' => $coowners,
8809: );
8810: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8811: if ($putresult eq 'ok') {
8812: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8813: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8814: }
8815: }
8816: }
8817: if ($delcoowners) {
8818: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8819: if ($delresult eq 'ok') {
8820: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8821: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8822: }
8823: }
8824: }
8825: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8826: my %crsinfo =
8827: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8828: if (ref($crsinfo{$cid}) eq 'HASH') {
8829: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8830: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8831: }
8832: }
8833: }
8834:
1.169 harris41 8835: # -------------------------------------------------- Modify user authentication
1.197 www 8836: # Overrides without validation
8837:
1.169 harris41 8838: sub modifyuserauth {
8839: my ($udom,$uname,$umode,$upass)=@_;
8840: my $uhome=&homeserver($uname,$udom);
1.197 www 8841: unless (&allowed('mau',$udom)) { return 'refused'; }
8842: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8843: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8844: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8845: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8846: &escape($upass),$uhome);
1.620 albertel 8847: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8848: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8849: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8850: &log($udom,,$uname,$uhome,
1.620 albertel 8851: 'Authentication changed by '.$env{'user.domain'}.', '.
8852: $env{'user.name'}.', '.$umode.
1.197 www 8853: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8854: unless ($reply eq 'ok') {
1.197 www 8855: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8856: return 'error: '.$reply;
8857: }
1.170 harris41 8858: return 'ok';
1.80 www 8859: }
8860:
1.81 www 8861: # --------------------------------------------------------------- Modify a user
1.80 www 8862:
1.81 www 8863: sub modifyuser {
1.206 matthew 8864: my ($udom, $uname, $uid,
8865: $umode, $upass, $first,
8866: $middle, $last, $gene,
1.1058 raeburn 8867: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8868: $udom= &LONCAPA::clean_domain($udom);
8869: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8870: my $showcandelete = 'none';
8871: if (ref($candelete) eq 'ARRAY') {
8872: if (@{$candelete} > 0) {
8873: $showcandelete = join(', ',@{$candelete});
8874: }
8875: }
1.81 www 8876: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8877: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8878: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8879: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8880: ' desiredhome not specified').
1.620 albertel 8881: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8882: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8883: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8884: my $newuser;
8885: if ($uhome eq 'no_host') {
8886: $newuser = 1;
8887: }
1.80 www 8888: # ----------------------------------------------------------------- Create User
1.406 albertel 8889: if (($uhome eq 'no_host') &&
8890: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8891: my $unhome='';
1.844 albertel 8892: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8893: $unhome = $desiredhome;
1.620 albertel 8894: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8895: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8896: } else { # load balancing routine for determining $unhome
1.81 www 8897: my $loadm=10000000;
1.841 albertel 8898: my %servers = &get_servers($udom,'library');
8899: foreach my $tryserver (keys(%servers)) {
8900: my $answer=reply('load',$tryserver);
8901: if (($answer=~/\d+/) && ($answer<$loadm)) {
8902: $loadm=$answer;
8903: $unhome=$tryserver;
8904: }
1.80 www 8905: }
8906: }
8907: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8908: return 'error: unable to find a home server for '.$uname.
8909: ' in domain '.$udom;
1.80 www 8910: }
8911: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8912: &escape($upass),$unhome);
8913: unless ($reply eq 'ok') {
8914: return 'error: '.$reply;
8915: }
1.230 stredwic 8916: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8917: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8918: return 'error: unable verify users home machine.';
1.80 www 8919: }
1.209 matthew 8920: } # End of creation of new user
1.80 www 8921: # ---------------------------------------------------------------------- Add ID
8922: if ($uid) {
8923: $uid=~tr/A-Z/a-z/;
8924: my %uidhash=&idrget($udom,$uname);
1.196 www 8925: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8926: && (!$forceid)) {
1.80 www 8927: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8928: return 'error: user id "'.$uid.'" does not match '.
8929: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8930: }
8931: } else {
8932: &idput($udom,($uname => $uid));
8933: }
8934: }
8935: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8936: my @tmp=&get('environment',
1.899 raeburn 8937: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8938: 'permanentemail','inststatus'],
1.134 albertel 8939: $udom,$uname);
1.1075 raeburn 8940: my (%names,%oldnames);
1.313 matthew 8941: if ($tmp[0] =~ m/^error:.*/) {
8942: %names=();
8943: } else {
8944: %names = @tmp;
1.1075 raeburn 8945: %oldnames = %names;
1.313 matthew 8946: }
1.388 www 8947: #
1.1058 raeburn 8948: # If name, email and/or uid are blank (e.g., because an uploaded file
8949: # of users did not contain them), do not overwrite existing values
8950: # unless field is in $candelete array ref.
8951: #
8952:
8953: my @fields = ('firstname','middlename','lastname','generation',
8954: 'permanentemail','id');
8955: my %newvalues;
8956: if (ref($candelete) eq 'ARRAY') {
8957: foreach my $field (@fields) {
8958: if (grep(/^\Q$field\E$/,@{$candelete})) {
8959: if ($field eq 'firstname') {
8960: $names{$field} = $first;
8961: } elsif ($field eq 'middlename') {
8962: $names{$field} = $middle;
8963: } elsif ($field eq 'lastname') {
8964: $names{$field} = $last;
8965: } elsif ($field eq 'generation') {
8966: $names{$field} = $gene;
8967: } elsif ($field eq 'permanentemail') {
8968: $names{$field} = $email;
8969: } elsif ($field eq 'id') {
8970: $names{$field} = $uid;
8971: }
8972: }
8973: }
8974: }
1.388 www 8975: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8976: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8977: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8978: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8979: if ($email) {
8980: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8981: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8982: }
1.899 raeburn 8983: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8984: if (defined($inststatus)) {
8985: $names{'inststatus'} = '';
8986: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8987: if (ref($usertypes) eq 'HASH') {
8988: my @okstatuses;
8989: foreach my $item (split(/:/,$inststatus)) {
8990: if (defined($usertypes->{$item})) {
8991: push(@okstatuses,$item);
8992: }
8993: }
8994: if (@okstatuses) {
8995: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8996: }
8997: }
8998: }
1.1075 raeburn 8999: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9000: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9001: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9002: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9003: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9004: } else {
9005: $logmsg .= ' during self creation';
9006: }
1.1075 raeburn 9007: my $changed;
9008: if ($newuser) {
9009: $changed = 1;
9010: } else {
9011: foreach my $field (@fields) {
9012: if ($names{$field} ne $oldnames{$field}) {
9013: $changed = 1;
9014: last;
9015: }
9016: }
9017: }
9018: unless ($changed) {
9019: $logmsg = 'No changes in user information needed for: '.$logmsg;
9020: &logthis($logmsg);
9021: return 'ok';
9022: }
9023: my $reply = &put('environment', \%names, $udom,$uname);
9024: if ($reply ne 'ok') {
9025: return 'error: '.$reply;
9026: }
1.1087 raeburn 9027: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9028: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9029: }
1.1075 raeburn 9030: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9031: &devalidate_cache_new('namescache',$uname.':'.$udom);
9032: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9033: &logthis($logmsg);
1.134 albertel 9034: return 'ok';
1.80 www 9035: }
9036:
1.81 www 9037: # -------------------------------------------------------------- Modify student
1.80 www 9038:
1.81 www 9039: sub modifystudent {
9040: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9041: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9042: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9043: if (!$cid) {
1.620 albertel 9044: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9045: return 'not_in_class';
9046: }
1.80 www 9047: }
9048: # --------------------------------------------------------------- Make the user
1.81 www 9049: my $reply=&modifyuser
1.209 matthew 9050: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9051: $desiredhome,$email,$inststatus);
1.80 www 9052: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9053: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9054: # student's environment
1.297 matthew 9055: $uid = undef if (!$forceid);
1.455 albertel 9056: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9057: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9058: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9059: return $reply;
9060: }
9061:
9062: sub modify_student_enrollment {
1.1172.2.23 raeburn 9063: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9064: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9065: my ($cdom,$cnum,$chome);
9066: if (!$cid) {
1.620 albertel 9067: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9068: return 'not_in_class';
9069: }
1.620 albertel 9070: $cdom=$env{'course.'.$cid.'.domain'};
9071: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9072: } else {
9073: ($cdom,$cnum)=split(/_/,$cid);
9074: }
1.620 albertel 9075: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9076: if (!$chome) {
1.457 raeburn 9077: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9078: }
1.455 albertel 9079: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9080: # Make sure the user exists
1.81 www 9081: my $uhome=&homeserver($uname,$udom);
9082: if (($uhome eq '') || ($uhome eq 'no_host')) {
9083: return 'error: no such user';
9084: }
1.297 matthew 9085: # Get student data if we were not given enough information
9086: if (!defined($first) || $first eq '' ||
9087: !defined($last) || $last eq '' ||
9088: !defined($uid) || $uid eq '' ||
9089: !defined($middle) || $middle eq '' ||
9090: !defined($gene) || $gene eq '') {
1.294 matthew 9091: # They did not supply us with enough data to enroll the student, so
9092: # we need to pick up more information.
1.297 matthew 9093: my %tmp = &get('environment',
1.294 matthew 9094: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9095: ,$udom,$uname);
9096:
1.800 albertel 9097: #foreach my $key (keys(%tmp)) {
9098: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9099: #}
1.294 matthew 9100: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9101: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9102: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9103: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9104: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9105: }
1.556 albertel 9106: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9107: my $user = "$uname:$udom";
9108: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9109: my $reply=cput('classlist',
1.1148 raeburn 9110: {$user =>
1.1172.2.76 raeburn 9111: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9112: $cdom,$cnum);
1.1148 raeburn 9113: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9114: &devalidate_getsection_cache($udom,$uname,$cid);
9115: } else {
1.81 www 9116: return 'error: '.$reply;
9117: }
1.297 matthew 9118: # Add student role to user
1.83 www 9119: my $uurl='/'.$cid;
1.81 www 9120: $uurl=~s/\_/\//g;
9121: if ($usec) {
9122: $uurl.='/'.$usec;
9123: }
1.1148 raeburn 9124: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9125: $selfenroll,$context);
9126: if ($result ne 'ok') {
9127: if ($old_entry{$user} ne '') {
9128: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9129: } else {
9130: $reply = &del('classlist',[$user],$cdom,$cnum);
9131: }
9132: }
9133: return $result;
1.21 www 9134: }
9135:
1.556 albertel 9136: sub format_name {
9137: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9138: my $name;
9139: if ($first ne 'lastname') {
9140: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9141: } else {
9142: if ($lastname=~/\S/) {
9143: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9144: $name=~s/\s+,/,/;
9145: } else {
9146: $name.= $firstname.' '.$middlename.' '.$generation;
9147: }
9148: }
9149: $name=~s/^\s+//;
9150: $name=~s/\s+$//;
9151: $name=~s/\s+/ /g;
9152: return $name;
9153: }
9154:
1.84 www 9155: # ------------------------------------------------- Write to course preferences
9156:
9157: sub writecoursepref {
9158: my ($courseid,%prefs)=@_;
9159: $courseid=~s/^\///;
9160: $courseid=~s/\_/\//g;
9161: my ($cdomain,$cnum)=split(/\//,$courseid);
9162: my $chome=homeserver($cnum,$cdomain);
9163: if (($chome eq '') || ($chome eq 'no_host')) {
9164: return 'error: no such course';
9165: }
9166: my $cstring='';
1.800 albertel 9167: foreach my $pref (keys(%prefs)) {
9168: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9169: }
1.84 www 9170: $cstring=~s/\&$//;
9171: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9172: }
9173:
9174: # ---------------------------------------------------------- Make/modify course
9175:
9176: sub createcourse {
1.741 raeburn 9177: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9178: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9179: $url=&declutter($url);
9180: my $cid='';
1.1028 raeburn 9181: if ($context eq 'requestcourses') {
9182: my $can_create = 0;
9183: my ($ownername,$ownerdom) = split(':',$course_owner);
9184: if ($udom eq $ownerdom) {
9185: if (&usertools_access($ownername,$ownerdom,$category,undef,
9186: $context)) {
9187: $can_create = 1;
9188: }
9189: } else {
9190: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9191: $category);
9192: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9193: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9194: if (@curr > 0) {
9195: my @options = qw(approval validate autolimit);
9196: my $optregex = join('|',@options);
9197: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9198: $can_create = 1;
9199: }
9200: }
9201: }
9202: }
9203: if ($can_create) {
9204: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9205: unless (&allowed('ccc',$udom)) {
9206: return 'refused';
9207: }
1.1017 raeburn 9208: }
9209: } else {
9210: return 'refused';
9211: }
1.1028 raeburn 9212: } elsif (!&allowed('ccc',$udom)) {
9213: return 'refused';
1.84 www 9214: }
1.1011 raeburn 9215: # --------------------------------------------------------------- Get Unique ID
9216: my $uname;
9217: if ($cnum =~ /^$match_courseid$/) {
9218: my $chome=&homeserver($cnum,$udom,'true');
9219: if (($chome eq '') || ($chome eq 'no_host')) {
9220: $uname = $cnum;
9221: } else {
1.1038 raeburn 9222: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9223: }
9224: } else {
1.1038 raeburn 9225: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9226: }
9227: return $uname if ($uname =~ /^error/);
9228: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9229: if (!defined($course_server)) {
9230: if (defined(&domain($udom,'primary'))) {
9231: $course_server = &domain($udom,'primary');
9232: } else {
9233: $course_server = $env{'user.home'};
9234: }
9235: }
9236: my %host_servers =
9237: &Apache::lonnet::get_servers($udom,'library');
9238: unless ($host_servers{$course_server}) {
9239: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9240: }
1.84 www 9241: # ------------------------------------------------------------- Make the course
9242: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9243: $course_server);
1.84 www 9244: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9245: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9246: if (($uhome eq '') || ($uhome eq 'no_host')) {
9247: return 'error: no such course';
9248: }
1.271 www 9249: # ----------------------------------------------------------------- Course made
1.516 raeburn 9250: # log existence
1.1029 raeburn 9251: my $now = time;
1.918 raeburn 9252: my $newcourse = {
9253: $udom.'_'.$uname => {
1.921 raeburn 9254: description => $description,
9255: inst_code => $inst_code,
9256: owner => $course_owner,
9257: type => $crstype,
1.1029 raeburn 9258: creator => $env{'user.name'}.':'.
9259: $env{'user.domain'},
9260: created => $now,
9261: context => $context,
1.918 raeburn 9262: },
9263: };
1.921 raeburn 9264: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9265: # set toplevel url
1.271 www 9266: my $topurl=$url;
9267: unless ($nonstandard) {
9268: # ------------------------------------------ For standard courses, make top url
9269: my $mapurl=&clutter($url);
1.278 www 9270: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9271: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9272: <map>
9273: <resource id="1" type="start"></resource>
9274: <resource id="2" src="$mapurl"></resource>
9275: <resource id="3" type="finish"></resource>
9276: <link index="1" from="1" to="2"></link>
9277: <link index="2" from="2" to="3"></link>
9278: </map>
9279: ENDINITMAP
9280: $topurl=&declutter(
1.638 albertel 9281: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9282: );
9283: }
9284: # ----------------------------------------------------------- Write preferences
1.84 www 9285: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9286: ('description' => $description,
9287: 'url' => $topurl,
9288: 'internal.creator' => $env{'user.name'}.':'.
9289: $env{'user.domain'},
9290: 'internal.created' => $now,
9291: 'internal.creationcontext' => $context)
9292: );
1.84 www 9293: return '/'.$udom.'/'.$uname;
9294: }
9295:
1.1011 raeburn 9296: # ------------------------------------------------------------------- Create ID
9297: sub generate_coursenum {
1.1038 raeburn 9298: my ($udom,$crstype) = @_;
1.1011 raeburn 9299: my $domdesc = &domain($udom);
9300: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9301: my $first;
9302: if ($crstype eq 'Community') {
9303: $first = '0';
9304: } else {
9305: $first = int(1+rand(9));
9306: }
9307: my $uname=$first.
1.1011 raeburn 9308: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9309: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9310: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9311: # ----------------------------------------------- Make sure that does not exist
9312: my $uhome=&homeserver($uname,$udom,'true');
9313: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9314: if ($crstype eq 'Community') {
9315: $first = '0';
9316: } else {
9317: $first = int(1+rand(9));
9318: }
9319: $uname=$first.
1.1011 raeburn 9320: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9321: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9322: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9323: $uhome=&homeserver($uname,$udom,'true');
9324: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9325: return 'error: unable to generate unique course-ID';
9326: }
9327: }
9328: return $uname;
9329: }
9330:
1.813 albertel 9331: sub is_course {
1.1167 droeschl 9332: my ($cdom, $cnum) = scalar(@_) == 1 ?
9333: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9334:
9335: return unless $cdom and $cnum;
9336:
9337: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9338: '.');
9339:
1.1172.2.23 raeburn 9340: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9341: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9342: }
9343:
1.1015 raeburn 9344: sub store_userdata {
9345: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9346: my $result;
1.1016 raeburn 9347: if ($datakey ne '') {
1.1013 raeburn 9348: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9349: if ($udom eq '' || $uname eq '') {
9350: $udom = $env{'user.domain'};
9351: $uname = $env{'user.name'};
9352: }
9353: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9354: if (($uhome eq '') || ($uhome eq 'no_host')) {
9355: $result = 'error: no_host';
9356: } else {
9357: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9358: $storehash->{'host'} = $perlvar{'lonHostID'};
9359:
9360: my $namevalue='';
9361: foreach my $key (keys(%{$storehash})) {
9362: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9363: }
9364: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9365: unless ($namespace eq 'courserequests') {
9366: $datakey = &escape($datakey);
9367: }
1.1105 raeburn 9368: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9369: $namevalue,$uhome);
1.1013 raeburn 9370: }
9371: } else {
9372: $result = 'error: data to store was not a hash reference';
9373: }
9374: } else {
9375: $result= 'error: invalid requestkey';
9376: }
9377: return $result;
9378: }
9379:
1.21 www 9380: # ---------------------------------------------------------- Assign Custom Role
9381:
9382: sub assigncustomrole {
1.957 raeburn 9383: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9384: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9385: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9386: }
9387:
9388: # ----------------------------------------------------------------- Revoke Role
9389:
9390: sub revokerole {
1.957 raeburn 9391: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9392: my $now=time;
1.965 raeburn 9393: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9394: }
9395:
9396: # ---------------------------------------------------------- Revoke Custom Role
9397:
9398: sub revokecustomrole {
1.957 raeburn 9399: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9400: my $now=time;
1.357 www 9401: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9402: $deleteflag,$selfenroll,$context);
1.17 www 9403: }
9404:
1.533 banghart 9405: # ------------------------------------------------------------ Disk usage
1.535 albertel 9406: sub diskusage {
1.955 raeburn 9407: my ($udom,$uname,$directorypath,$getpropath)=@_;
9408: $directorypath =~ s/\/$//;
9409: my $listing=&reply('du2:'.&escape($directorypath).':'
9410: .&escape($getpropath).':'.&escape($uname).':'
9411: .&escape($udom),homeserver($uname,$udom));
9412: if ($listing eq 'unknown_cmd') {
9413: if ($getpropath) {
9414: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9415: }
9416: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9417: }
1.514 albertel 9418: return $listing;
1.512 banghart 9419: }
9420:
1.566 banghart 9421: sub is_locked {
1.1096 raeburn 9422: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9423: my @check;
9424: my $is_locked;
1.1093 raeburn 9425: push (@check,$file_name);
1.613 albertel 9426: my %locked = &get('file_permissions',\@check,
1.620 albertel 9427: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9428: my ($tmp)=keys(%locked);
9429: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9430:
1.566 banghart 9431: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9432: $is_locked = 'false';
9433: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9434: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9435: $is_locked = 'true';
1.1096 raeburn 9436: if (ref($which) eq 'ARRAY') {
9437: push(@{$which},$entry);
9438: } else {
9439: last;
9440: }
1.745 raeburn 9441: }
9442: }
1.566 banghart 9443: } else {
9444: $is_locked = 'false';
9445: }
1.1093 raeburn 9446: return $is_locked;
1.566 banghart 9447: }
9448:
1.759 albertel 9449: sub declutter_portfile {
9450: my ($file) = @_;
1.833 albertel 9451: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9452: return $file;
9453: }
9454:
1.559 banghart 9455: # ------------------------------------------------------------- Mark as Read Only
9456:
9457: sub mark_as_readonly {
9458: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9459: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9460: my ($tmp)=keys(%current_permissions);
9461: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9462: foreach my $file (@{$files}) {
1.759 albertel 9463: $file = &declutter_portfile($file);
1.561 banghart 9464: push(@{$current_permissions{$file}},$what);
1.559 banghart 9465: }
1.613 albertel 9466: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9467: return;
9468: }
9469:
1.572 banghart 9470: # ------------------------------------------------------------Save Selected Files
9471:
9472: sub save_selected_files {
9473: my ($user, $path, @files) = @_;
9474: my $filename = $user."savedfiles";
1.573 banghart 9475: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9476: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9477: foreach my $file (@files) {
1.620 albertel 9478: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9479: }
9480: foreach my $file (@other_files) {
1.574 banghart 9481: print (OUT $file."\n");
1.572 banghart 9482: }
1.574 banghart 9483: close (OUT);
1.572 banghart 9484: return 'ok';
9485: }
9486:
1.574 banghart 9487: sub clear_selected_files {
9488: my ($user) = @_;
9489: my $filename = $user."savedfiles";
1.1117 foxr 9490: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9491: print (OUT undef);
9492: close (OUT);
9493: return ("ok");
9494: }
9495:
1.572 banghart 9496: sub files_in_path {
9497: my ($user, $path) = @_;
9498: my $filename = $user."savedfiles";
9499: my %return_files;
1.1117 foxr 9500: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9501: while (my $line_in = <IN>) {
1.574 banghart 9502: chomp ($line_in);
9503: my @paths_and_file = split (m!/!, $line_in);
9504: my $file_part = pop (@paths_and_file);
9505: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9506: $path_part.='/';
9507: my $path_and_file = $path_part.$file_part;
9508: if ($path_part eq $path) {
9509: $return_files{$file_part}= 'selected';
9510: }
9511: }
1.574 banghart 9512: close (IN);
9513: return (\%return_files);
1.572 banghart 9514: }
9515:
9516: # called in portfolio select mode, to show files selected NOT in current directory
9517: sub files_not_in_path {
9518: my ($user, $path) = @_;
9519: my $filename = $user."savedfiles";
9520: my @return_files;
9521: my $path_part;
1.1117 foxr 9522: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9523: while (my $line = <IN>) {
1.572 banghart 9524: #ok, I know it's clunky, but I want it to work
1.800 albertel 9525: my @paths_and_file = split(m|/|, $line);
9526: my $file_part = pop(@paths_and_file);
9527: chomp($file_part);
9528: my $path_part = join('/', @paths_and_file);
1.572 banghart 9529: $path_part .= '/';
9530: my $path_and_file = $path_part.$file_part;
9531: if ($path_part ne $path) {
1.800 albertel 9532: push(@return_files, ($path_and_file));
1.572 banghart 9533: }
9534: }
1.800 albertel 9535: close(OUT);
1.574 banghart 9536: return (@return_files);
1.572 banghart 9537: }
9538:
1.745 raeburn 9539: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9540:
1.745 raeburn 9541: sub get_portfile_permissions {
9542: my ($domain,$user) = @_;
1.613 albertel 9543: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9544: my ($tmp)=keys(%current_permissions);
9545: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9546: return \%current_permissions;
9547: }
9548:
9549: #---------------------------------------------Get portfolio file access controls
9550:
1.749 raeburn 9551: sub get_access_controls {
1.745 raeburn 9552: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9553: my %access;
9554: my $real_file = $file;
9555: $file =~ s/\.meta$//;
1.745 raeburn 9556: if (defined($file)) {
1.749 raeburn 9557: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9558: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9559: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9560: }
9561: }
1.745 raeburn 9562: } else {
1.749 raeburn 9563: foreach my $key (keys(%{$current_permissions})) {
9564: if ($key =~ /\0accesscontrol$/) {
9565: if (defined($group)) {
9566: if ($key !~ m-^\Q$group\E/-) {
9567: next;
9568: }
9569: }
9570: my ($fullpath) = split(/\0/,$key);
9571: if (ref($$current_permissions{$key}) eq 'HASH') {
9572: foreach my $control (keys(%{$$current_permissions{$key}})) {
9573: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9574: }
9575: }
9576: }
9577: }
9578: }
9579: return %access;
9580: }
9581:
9582: sub modify_access_controls {
9583: my ($file_name,$changes,$domain,$user)=@_;
9584: my ($outcome,$deloutcome);
9585: my %store_permissions;
9586: my %new_values;
9587: my %new_control;
9588: my %translation;
9589: my @deletions = ();
9590: my $now = time;
9591: if (exists($$changes{'activate'})) {
9592: if (ref($$changes{'activate'}) eq 'HASH') {
9593: my @newitems = sort(keys(%{$$changes{'activate'}}));
9594: my $numnew = scalar(@newitems);
9595: for (my $i=0; $i<$numnew; $i++) {
9596: my $newkey = $newitems[$i];
9597: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9598: if ($newkey =~ /^\d+:/) {
9599: $newkey =~ s/^(\d+)/$newid/;
9600: $translation{$1} = $newid;
9601: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9602: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9603: $translation{$1} = $newid;
9604: }
1.749 raeburn 9605: $new_values{$file_name."\0".$newkey} =
9606: $$changes{'activate'}{$newitems[$i]};
9607: $new_control{$newkey} = $now;
9608: }
9609: }
9610: }
9611: my %todelete;
9612: my %changed_items;
9613: foreach my $action ('delete','update') {
9614: if (exists($$changes{$action})) {
9615: if (ref($$changes{$action}) eq 'HASH') {
9616: foreach my $key (keys(%{$$changes{$action}})) {
9617: my ($itemnum) = ($key =~ /^([^:]+):/);
9618: if ($action eq 'delete') {
9619: $todelete{$itemnum} = 1;
9620: } else {
9621: $changed_items{$itemnum} = $key;
9622: }
9623: }
1.745 raeburn 9624: }
9625: }
1.749 raeburn 9626: }
9627: # get lock on access controls for file.
9628: my $lockhash = {
9629: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9630: ':'.$env{'user.domain'},
9631: };
9632: my $tries = 0;
9633: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9634:
1.1172.2.79 raeburn 9635: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9636: $tries ++;
1.1172.2.79 raeburn 9637: sleep(0.1);
1.749 raeburn 9638: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9639: }
9640: if ($gotlock eq 'ok') {
9641: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9642: my ($tmp)=keys(%curr_permissions);
9643: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9644: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9645: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9646: if (ref($curr_controls) eq 'HASH') {
9647: foreach my $control_item (keys(%{$curr_controls})) {
9648: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9649: if (defined($todelete{$itemnum})) {
9650: push(@deletions,$file_name."\0".$control_item);
9651: } else {
9652: if (defined($changed_items{$itemnum})) {
9653: $new_control{$changed_items{$itemnum}} = $now;
9654: push(@deletions,$file_name."\0".$control_item);
9655: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9656: } else {
9657: $new_control{$control_item} = $$curr_controls{$control_item};
9658: }
9659: }
1.745 raeburn 9660: }
9661: }
9662: }
1.970 raeburn 9663: my ($group);
9664: if (&is_course($domain,$user)) {
9665: ($group,my $file) = split(/\//,$file_name,2);
9666: }
1.749 raeburn 9667: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9668: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9669: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9670: # remove lock
9671: my @del_lock = ($file_name."\0".'locked_access_records');
9672: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9673: my $sqlresult =
1.970 raeburn 9674: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9675: $group);
1.749 raeburn 9676: } else {
9677: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9678: }
1.749 raeburn 9679: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9680: }
9681:
1.827 raeburn 9682: sub make_public_indefinitely {
9683: my ($requrl) = @_;
9684: my $now = time;
9685: my $action = 'activate';
9686: my $aclnum = 0;
9687: if (&is_portfolio_url($requrl)) {
9688: my (undef,$udom,$unum,$file_name,$group) =
9689: &parse_portfolio_url($requrl);
9690: my $current_perms = &get_portfile_permissions($udom,$unum);
9691: my %access_controls = &get_access_controls($current_perms,
9692: $group,$file_name);
9693: foreach my $key (keys(%{$access_controls{$file_name}})) {
9694: my ($num,$scope,$end,$start) =
9695: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9696: if ($scope eq 'public') {
9697: if ($start <= $now && $end == 0) {
9698: $action = 'none';
9699: } else {
9700: $action = 'update';
9701: $aclnum = $num;
9702: }
9703: last;
9704: }
9705: }
9706: if ($action eq 'none') {
9707: return 'ok';
9708: } else {
9709: my %changes;
9710: my $newend = 0;
9711: my $newstart = $now;
9712: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9713: $changes{$action}{$newkey} = {
9714: type => 'public',
9715: time => {
9716: start => $newstart,
9717: end => $newend,
9718: },
9719: };
9720: my ($outcome,$deloutcome,$new_values,$translation) =
9721: &modify_access_controls($file_name,\%changes,$udom,$unum);
9722: return $outcome;
9723: }
9724: } else {
9725: return 'invalid';
9726: }
9727: }
9728:
1.745 raeburn 9729: #------------------------------------------------------Get Marked as Read Only
9730:
9731: sub get_marked_as_readonly {
9732: my ($domain,$user,$what,$group) = @_;
9733: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9734: my @readonly_files;
1.629 banghart 9735: my $cmp1=$what;
9736: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9737: while (my ($file_name,$value) = each(%{$current_permissions})) {
9738: if (defined($group)) {
9739: if ($file_name !~ m-^\Q$group\E/-) {
9740: next;
9741: }
9742: }
1.561 banghart 9743: if (ref($value) eq "ARRAY"){
9744: foreach my $stored_what (@{$value}) {
1.629 banghart 9745: my $cmp2=$stored_what;
1.759 albertel 9746: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9747: $cmp2=join('',@{$stored_what});
1.745 raeburn 9748: }
1.629 banghart 9749: if ($cmp1 eq $cmp2) {
1.561 banghart 9750: push(@readonly_files, $file_name);
1.745 raeburn 9751: last;
1.563 banghart 9752: } elsif (!defined($what)) {
9753: push(@readonly_files, $file_name);
1.745 raeburn 9754: last;
1.561 banghart 9755: }
9756: }
1.745 raeburn 9757: }
1.561 banghart 9758: }
9759: return @readonly_files;
9760: }
1.577 banghart 9761: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9762:
1.577 banghart 9763: sub get_marked_as_readonly_hash {
1.745 raeburn 9764: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9765: my %readonly_files;
1.745 raeburn 9766: while (my ($file_name,$value) = each(%{$current_permissions})) {
9767: if (defined($group)) {
9768: if ($file_name !~ m-^\Q$group\E/-) {
9769: next;
9770: }
9771: }
1.577 banghart 9772: if (ref($value) eq "ARRAY"){
9773: foreach my $stored_what (@{$value}) {
1.745 raeburn 9774: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9775: foreach my $lock_descriptor(@{$stored_what}) {
9776: if ($lock_descriptor eq 'graded') {
9777: $readonly_files{$file_name} = 'graded';
9778: } elsif ($lock_descriptor eq 'handback') {
9779: $readonly_files{$file_name} = 'handback';
9780: } else {
9781: if (!exists($readonly_files{$file_name})) {
9782: $readonly_files{$file_name} = 'locked';
9783: }
9784: }
1.745 raeburn 9785: }
1.750 banghart 9786: }
1.577 banghart 9787: }
9788: }
9789: }
9790: return %readonly_files;
9791: }
1.559 banghart 9792: # ------------------------------------------------------------ Unmark as Read Only
9793:
9794: sub unmark_as_readonly {
1.629 banghart 9795: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9796: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9797: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9798: $file_name = &declutter_portfile($file_name);
1.634 albertel 9799: my $symb_crs = $what;
9800: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9801: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9802: my ($tmp)=keys(%current_permissions);
9803: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9804: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9805: foreach my $file (@readonly_files) {
1.759 albertel 9806: my $clean_file = &declutter_portfile($file);
9807: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9808: my $current_locks = $current_permissions{$file};
1.563 banghart 9809: my @new_locks;
9810: my @del_keys;
9811: if (ref($current_locks) eq "ARRAY"){
9812: foreach my $locker (@{$current_locks}) {
1.632 albertel 9813: my $compare=$locker;
1.749 raeburn 9814: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9815: $compare=join('',@{$locker});
1.746 raeburn 9816: if ($compare ne $symb_crs) {
9817: push(@new_locks, $locker);
9818: }
1.563 banghart 9819: }
9820: }
1.650 albertel 9821: if (scalar(@new_locks) > 0) {
1.563 banghart 9822: $current_permissions{$file} = \@new_locks;
9823: } else {
9824: push(@del_keys, $file);
1.613 albertel 9825: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9826: delete($current_permissions{$file});
1.563 banghart 9827: }
9828: }
1.561 banghart 9829: }
1.613 albertel 9830: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9831: return;
9832: }
1.512 banghart 9833:
1.17 www 9834: # ------------------------------------------------------------ Directory lister
9835:
9836: sub dirlist {
1.955 raeburn 9837: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9838: $uri=~s/^\///;
9839: $uri=~s/\/$//;
1.253 stredwic 9840: my ($udom, $uname);
1.955 raeburn 9841: if ($getuserdir) {
1.253 stredwic 9842: $udom = $userdomain;
9843: $uname = $username;
1.955 raeburn 9844: } else {
9845: (undef,$udom,$uname)=split(/\//,$uri);
9846: if(defined($userdomain)) {
9847: $udom = $userdomain;
9848: }
9849: if(defined($username)) {
9850: $uname = $username;
9851: }
1.253 stredwic 9852: }
1.955 raeburn 9853: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9854:
1.955 raeburn 9855: $dirRoot = $perlvar{'lonDocRoot'};
9856: if (defined($getpropath)) {
9857: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9858: $dirRoot =~ s/\/$//;
1.955 raeburn 9859: } elsif (defined($getuserdir)) {
9860: my $subdir=$uname.'__';
9861: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9862: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9863: ."/$udom/$subdir/$uname";
9864: } elsif (defined($alternateRoot)) {
9865: $dirRoot = $alternateRoot;
1.751 banghart 9866: }
1.253 stredwic 9867:
9868: if($udom) {
9869: if($uname) {
1.1135 raeburn 9870: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9871: if ($uhome eq 'no_host') {
9872: return ([],'no_host');
9873: }
1.955 raeburn 9874: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9875: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9876: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9877: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9878: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9879: } else {
9880: @listing_results = map { &unescape($_); } split(/:/,$listing);
9881: }
1.605 matthew 9882: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9883: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9884: @listing_results = split(/:/,$listing);
9885: } else {
9886: @listing_results = map { &unescape($_); } split(/:/,$listing);
9887: }
1.1135 raeburn 9888: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9889: ($listing eq 'rejected') || ($listing eq 'refused') ||
9890: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9891: return ([],$listing);
9892: } else {
9893: return (\@listing_results);
1.1135 raeburn 9894: }
1.955 raeburn 9895: } elsif(!$alternateRoot) {
1.1136 raeburn 9896: my (%allusers,%listerror);
1.841 albertel 9897: my %servers = &get_servers($udom,'library');
1.955 raeburn 9898: foreach my $tryserver (keys(%servers)) {
9899: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9900: &escape($udom),$tryserver);
9901: if ($listing eq 'unknown_cmd') {
9902: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9903: $udom, $tryserver);
9904: } else {
9905: @listing_results = map { &unescape($_); } split(/:/,$listing);
9906: }
1.841 albertel 9907: if ($listing eq 'unknown_cmd') {
9908: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9909: $udom, $tryserver);
9910: @listing_results = split(/:/,$listing);
9911: } else {
9912: @listing_results =
9913: map { &unescape($_); } split(/:/,$listing);
9914: }
1.1136 raeburn 9915: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9916: ($listing eq 'rejected') || ($listing eq 'refused') ||
9917: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9918: $listerror{$tryserver} = $listing;
9919: } else {
1.841 albertel 9920: foreach my $line (@listing_results) {
9921: my ($entry) = split(/&/,$line,2);
9922: $allusers{$entry} = 1;
9923: }
9924: }
1.253 stredwic 9925: }
1.1136 raeburn 9926: my @alluserslist=();
1.800 albertel 9927: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9928: push(@alluserslist,$user.'&user');
1.253 stredwic 9929: }
1.1172.2.80 raeburn 9930: if (!%listerror) {
9931: # no errors
9932: return (\@alluserslist);
9933: } elsif (scalar(keys(%servers)) == 1) {
9934: # one library server, one error
9935: my ($key) = keys(%listerror);
9936: return (\@alluserslist, $listerror{$key});
9937: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
9938: # con_lost indicates that we might miss data from at least one
9939: # library server
9940: return (\@alluserslist, 'con_lost');
9941: } else {
9942: # multiple library servers and no con_lost -> data should be
9943: # complete.
9944: return (\@alluserslist);
9945: }
9946:
1.253 stredwic 9947: } else {
1.1136 raeburn 9948: return ([],'missing username');
1.253 stredwic 9949: }
1.955 raeburn 9950: } elsif(!defined($getpropath)) {
1.1136 raeburn 9951: my $path = $perlvar{'lonDocRoot'}.'/res/';
9952: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9953: return (\@all_domains);
1.955 raeburn 9954: } else {
1.1136 raeburn 9955: return ([],'missing domain');
1.275 stredwic 9956: }
9957: }
9958:
9959: # --------------------------------------------- GetFileTimestamp
9960: # This function utilizes dirlist and returns the date stamp for
9961: # when it was last modified. It will also return an error of -1
9962: # if an error occurs
9963:
9964: sub GetFileTimestamp {
1.955 raeburn 9965: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9966: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9967: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9968: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9969: undef,$getuserdir);
9970: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9971: return -1;
9972: }
9973: if (ref($fileref) eq 'ARRAY') {
9974: my @stats = split('&',$fileref->[0]);
1.375 matthew 9975: # @stats contains first the filename, then the stat output
9976: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9977: } else {
9978: return -1;
1.253 stredwic 9979: }
1.26 www 9980: }
9981:
1.712 albertel 9982: sub stat_file {
9983: my ($uri) = @_;
1.787 albertel 9984: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9985:
1.955 raeburn 9986: my ($udom,$uname,$file);
1.712 albertel 9987: if ($uri =~ m-^/(uploaded|editupload)/-) {
9988: ($udom,$uname,$file) =
1.811 albertel 9989: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9990: $file = 'userfiles/'.$file;
9991: }
9992: if ($uri =~ m-^/res/-) {
9993: ($udom,$uname) =
1.807 albertel 9994: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9995: $file = $uri;
9996: }
9997:
9998: if (!$udom || !$uname || !$file) {
9999: # unable to handle the uri
10000: return ();
10001: }
1.956 raeburn 10002: my $getpropath;
10003: if ($file =~ /^userfiles\//) {
10004: $getpropath = 1;
10005: }
1.1136 raeburn 10006: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10007: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10008: return ();
10009: } else {
10010: if (ref($listref) eq 'ARRAY') {
10011: my @stats = split('&',$listref->[0]);
10012: shift(@stats); #filename is first
10013: return @stats;
10014: }
1.712 albertel 10015: }
10016: return ();
10017: }
10018:
1.26 www 10019: # -------------------------------------------------------- Value of a Condition
10020:
1.713 albertel 10021: # gets the value of a specific preevaluated condition
10022: # stored in the string $env{user.state.<cid>}
10023: # or looks up a condition reference in the bighash and if if hasn't
10024: # already been evaluated recurses into docondval to get the value of
10025: # the condition, then memoizing it to
10026: # $env{user.state.<cid>.<condition>}
1.40 www 10027: sub directcondval {
10028: my $number=shift;
1.620 albertel 10029: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10030: &Apache::lonuserstate::evalstate();
10031: }
1.713 albertel 10032: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10033: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10034: } elsif ($number =~ /^_/) {
10035: my $sub_condition;
10036: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10037: &GDBM_READER(),0640)) {
10038: $sub_condition=$bighash{'conditions'.$number};
10039: untie(%bighash);
10040: }
10041: my $value = &docondval($sub_condition);
1.949 raeburn 10042: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10043: return $value;
10044: }
1.620 albertel 10045: if ($env{'user.state.'.$env{'request.course.id'}}) {
10046: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10047: } else {
10048: return 2;
10049: }
10050: }
10051:
1.713 albertel 10052: # get the collection of conditions for this resource
1.26 www 10053: sub condval {
10054: my $condidx=shift;
1.54 www 10055: my $allpathcond='';
1.713 albertel 10056: foreach my $cond (split(/\|/,$condidx)) {
10057: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10058: $allpathcond.=
10059: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10060: }
1.191 harris41 10061: }
1.54 www 10062: $allpathcond=~s/\|$//;
1.713 albertel 10063: return &docondval($allpathcond);
10064: }
10065:
10066: #evaluates an expression of conditions
10067: sub docondval {
10068: my ($allpathcond) = @_;
10069: my $result=0;
10070: if ($env{'request.course.id'}
10071: && defined($allpathcond)) {
10072: my $operand='|';
10073: my @stack;
10074: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10075: if ($chunk eq '(') {
10076: push @stack,($operand,$result);
10077: } elsif ($chunk eq ')') {
10078: my $before=pop @stack;
10079: if (pop @stack eq '&') {
10080: $result=$result>$before?$before:$result;
10081: } else {
10082: $result=$result>$before?$result:$before;
10083: }
10084: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10085: $operand=$chunk;
10086: } else {
10087: my $new=directcondval($chunk);
10088: if ($operand eq '&') {
10089: $result=$result>$new?$new:$result;
10090: } else {
10091: $result=$result>$new?$result:$new;
10092: }
10093: }
10094: }
1.26 www 10095: }
10096: return $result;
1.421 albertel 10097: }
10098:
10099: # ---------------------------------------------------- Devalidate courseresdata
10100:
10101: sub devalidatecourseresdata {
10102: my ($coursenum,$coursedomain)=@_;
10103: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10104: &devalidate_cache_new('courseres',$hashid);
1.28 www 10105: }
10106:
1.763 www 10107:
1.200 www 10108: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10109: #
10110: # Parameters:
10111: # $coursenum - Number of the course.
10112: # $coursedomain - Domain at which the course was created.
10113: # Returns:
10114: # A hash of the course parameters along (I think) with timestamps
10115: # and version info.
1.877 foxr 10116:
1.624 albertel 10117: sub get_courseresdata {
10118: my ($coursenum,$coursedomain)=@_;
1.200 www 10119: my $coursehom=&homeserver($coursenum,$coursedomain);
10120: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10121: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10122: my %dumpreply;
1.417 albertel 10123: unless (defined($cached)) {
1.624 albertel 10124: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10125: $result=\%dumpreply;
1.251 albertel 10126: my ($tmp) = keys(%dumpreply);
10127: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10128: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10129: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10130: return $tmp;
1.416 albertel 10131: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10132: $result=undef;
1.599 albertel 10133: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10134: }
10135: }
1.624 albertel 10136: return $result;
10137: }
10138:
1.633 albertel 10139: sub devalidateuserresdata {
10140: my ($uname,$udom)=@_;
10141: my $hashid="$udom:$uname";
10142: &devalidate_cache_new('userres',$hashid);
10143: }
10144:
1.624 albertel 10145: sub get_userresdata {
10146: my ($uname,$udom)=@_;
10147: #most student don\'t have any data set, check if there is some data
10148: if (&EXT_cache_status($udom,$uname)) { return undef; }
10149:
10150: my $hashid="$udom:$uname";
10151: my ($result,$cached)=&is_cached_new('userres',$hashid);
10152: if (!defined($cached)) {
10153: my %resourcedata=&dump('resourcedata',$udom,$uname);
10154: $result=\%resourcedata;
10155: &do_cache_new('userres',$hashid,$result,600);
10156: }
10157: my ($tmp)=keys(%$result);
10158: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10159: return $result;
10160: }
10161: #error 2 occurs when the .db doesn't exist
10162: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10163: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10164: &logthis("<font color=\"blue\">WARNING:".
10165: " Trying to get resource data for ".
10166: $uname." at ".$udom.": ".
10167: $tmp."</font>");
10168: }
1.624 albertel 10169: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10170: #&EXT_cache_set($udom,$uname);
10171: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10172: undef($tmp); # not really an error so don't send it back
1.624 albertel 10173: }
10174: return $tmp;
10175: }
1.879 foxr 10176: #----------------------------------------------- resdata - return resource data
10177: # Purpose:
10178: # Return resource data for either users or for a course.
10179: # Parameters:
10180: # $name - Course/user name.
10181: # $domain - Name of the domain the user/course is registered on.
10182: # $type - Type of thing $name is (must be 'course' or 'user'
10183: # @which - Array of names of resources desired.
10184: # Returns:
10185: # The value of the first reasource in @which that is found in the
10186: # resource hash.
10187: # Exceptional Conditions:
10188: # If the $type passed in is not valid (not the string 'course' or
10189: # 'user', an undefined reference is returned.
10190: # If none of the resources are found, an undef is returned
1.624 albertel 10191: sub resdata {
10192: my ($name,$domain,$type,@which)=@_;
10193: my $result;
10194: if ($type eq 'course') {
10195: $result=&get_courseresdata($name,$domain);
10196: } elsif ($type eq 'user') {
10197: $result=&get_userresdata($name,$domain);
10198: }
10199: if (!ref($result)) { return $result; }
1.251 albertel 10200: foreach my $item (@which) {
1.927 albertel 10201: if (defined($result->{$item->[0]})) {
10202: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10203: }
1.250 albertel 10204: }
1.291 albertel 10205: return undef;
1.200 www 10206: }
10207:
1.1172.2.31 raeburn 10208: sub get_numsuppfiles {
10209: my ($cnum,$cdom,$ignorecache)=@_;
10210: my $hashid=$cnum.':'.$cdom;
10211: my ($suppcount,$cached);
10212: unless ($ignorecache) {
10213: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10214: }
10215: unless (defined($cached)) {
10216: my $chome=&homeserver($cnum,$cdom);
10217: unless ($chome eq 'no_host') {
10218: ($suppcount,my $errors) = (0,0);
10219: my $suppmap = 'supplemental.sequence';
10220: ($suppcount,$errors) =
10221: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10222: }
10223: &do_cache_new('suppcount',$hashid,$suppcount,600);
10224: }
10225: return $suppcount;
10226: }
10227:
1.379 matthew 10228: #
10229: # EXT resource caching routines
10230: #
10231:
10232: sub clear_EXT_cache_status {
1.383 albertel 10233: &delenv('cache.EXT.');
1.379 matthew 10234: }
10235:
10236: sub EXT_cache_status {
10237: my ($target_domain,$target_user) = @_;
1.383 albertel 10238: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10239: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10240: # We know already the user has no data
10241: return 1;
10242: } else {
10243: return 0;
10244: }
10245: }
10246:
10247: sub EXT_cache_set {
10248: my ($target_domain,$target_user) = @_;
1.383 albertel 10249: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10250: #&appenv({$cachename => time});
1.379 matthew 10251: }
10252:
1.28 www 10253: # --------------------------------------------------------- Value of a Variable
1.58 www 10254: sub EXT {
1.715 albertel 10255:
1.1172.2.28 raeburn 10256: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10257: unless ($varname) { return ''; }
1.218 albertel 10258: #get real user name/domain, courseid and symb
10259: my $courseid;
1.359 albertel 10260: my $publicuser;
1.427 www 10261: if ($symbparm) {
10262: $symbparm=&get_symb_from_alias($symbparm);
10263: }
1.218 albertel 10264: if (!($uname && $udom)) {
1.790 albertel 10265: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10266: if (!$symbparm) { $symbparm=$cursymb; }
10267: } else {
1.620 albertel 10268: $courseid=$env{'request.course.id'};
1.218 albertel 10269: }
1.48 www 10270: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10271: my $rest;
1.320 albertel 10272: if (defined($therest[0])) {
1.48 www 10273: $rest=join('.',@therest);
10274: } else {
10275: $rest='';
10276: }
1.320 albertel 10277:
1.57 www 10278: my $qualifierrest=$qualifier;
10279: if ($rest) { $qualifierrest.='.'.$rest; }
10280: my $spacequalifierrest=$space;
10281: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10282: if ($realm eq 'user') {
1.48 www 10283: # --------------------------------------------------------------- user.resource
10284: if ($space eq 'resource') {
1.651 albertel 10285: if ( (defined($Apache::lonhomework::parsing_a_problem)
10286: || defined($Apache::lonhomework::parsing_a_task))
10287: &&
1.744 albertel 10288: ($symbparm eq &symbread()) ) {
10289: # if we are in the middle of processing the resource the
10290: # get the value we are planning on committing
10291: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10292: return $Apache::lonhomework::results{$qualifierrest};
10293: } else {
10294: return $Apache::lonhomework::history{$qualifierrest};
10295: }
1.335 albertel 10296: } else {
1.359 albertel 10297: my %restored;
1.620 albertel 10298: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10299: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10300: } else {
10301: %restored=&restore($symbparm,$courseid,$udom,$uname);
10302: }
1.335 albertel 10303: return $restored{$qualifierrest};
10304: }
1.48 www 10305: # ----------------------------------------------------------------- user.access
10306: } elsif ($space eq 'access') {
1.218 albertel 10307: # FIXME - not supporting calls for a specific user
1.48 www 10308: return &allowed($qualifier,$rest);
10309: # ------------------------------------------ user.preferences, user.environment
10310: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10311: if (($uname eq $env{'user.name'}) &&
10312: ($udom eq $env{'user.domain'})) {
10313: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10314: } else {
1.359 albertel 10315: my %returnhash;
10316: if (!$publicuser) {
10317: %returnhash=&userenvironment($udom,$uname,
10318: $qualifierrest);
10319: }
1.218 albertel 10320: return $returnhash{$qualifierrest};
10321: }
1.48 www 10322: # ----------------------------------------------------------------- user.course
10323: } elsif ($space eq 'course') {
1.218 albertel 10324: # FIXME - not supporting calls for a specific user
1.620 albertel 10325: return $env{join('.',('request.course',$qualifier))};
1.48 www 10326: # ------------------------------------------------------------------- user.role
10327: } elsif ($space eq 'role') {
1.218 albertel 10328: # FIXME - not supporting calls for a specific user
1.620 albertel 10329: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10330: if ($qualifier eq 'value') {
10331: return $role;
10332: } elsif ($qualifier eq 'extent') {
10333: return $where;
10334: }
10335: # ----------------------------------------------------------------- user.domain
10336: } elsif ($space eq 'domain') {
1.218 albertel 10337: return $udom;
1.48 www 10338: # ------------------------------------------------------------------- user.name
10339: } elsif ($space eq 'name') {
1.218 albertel 10340: return $uname;
1.48 www 10341: # ---------------------------------------------------- Any other user namespace
1.29 www 10342: } else {
1.359 albertel 10343: my %reply;
10344: if (!$publicuser) {
10345: %reply=&get($space,[$qualifierrest],$udom,$uname);
10346: }
10347: return $reply{$qualifierrest};
1.48 www 10348: }
1.236 www 10349: } elsif ($realm eq 'query') {
10350: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10351: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10352: [$spacequalifierrest]);
1.620 albertel 10353: return $env{'form.'.$spacequalifierrest};
1.236 www 10354: } elsif ($realm eq 'request') {
1.48 www 10355: # ------------------------------------------------------------- request.browser
10356: if ($space eq 'browser') {
1.1145 bisitz 10357: return $env{'browser.'.$qualifier};
1.57 www 10358: # ------------------------------------------------------------ request.filename
10359: } else {
1.620 albertel 10360: return $env{'request.'.$spacequalifierrest};
1.29 www 10361: }
1.28 www 10362: } elsif ($realm eq 'course') {
1.48 www 10363: # ---------------------------------------------------------- course.description
1.620 albertel 10364: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10365: } elsif ($realm eq 'resource') {
1.165 www 10366:
1.620 albertel 10367: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10368: if (!$symbparm) { $symbparm=&symbread(); }
10369: }
1.693 albertel 10370:
1.1172.2.30 raeburn 10371: if ($qualifier eq '') {
10372: if ($space eq 'title') {
10373: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10374: return &gettitle($symbparm);
10375: }
1.693 albertel 10376:
1.1172.2.30 raeburn 10377: if ($space eq 'map') {
10378: my ($map) = &decode_symb($symbparm);
10379: return &symbread($map);
10380: }
10381: if ($space eq 'maptitle') {
10382: my ($map) = &decode_symb($symbparm);
10383: return &gettitle($map);
10384: }
10385: if ($space eq 'filename') {
10386: if ($symbparm) {
10387: return &clutter((&decode_symb($symbparm))[2]);
10388: }
10389: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10390: }
1.1172.2.30 raeburn 10391:
10392: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10393: if ($space eq 'visibleparts') {
10394: my $navmap = Apache::lonnavmaps::navmap->new();
10395: my $item;
10396: if (ref($navmap)) {
10397: my $res = $navmap->getBySymb($symbparm);
10398: my $parts = $res->parts();
10399: if (ref($parts) eq 'ARRAY') {
10400: $item = join(',',@{$parts});
10401: }
10402: undef($navmap);
10403: }
10404: return $item;
10405: }
10406: }
10407: }
1.693 albertel 10408:
10409: my ($section, $group, @groups);
1.593 albertel 10410: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10411: if (($courseid eq '') && ($cid)) {
10412: $courseid = $cid;
10413: }
10414: if (($symbparm && $courseid) &&
10415: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10416:
1.218 albertel 10417: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10418:
1.60 www 10419: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10420: my $symbp=$symbparm;
1.735 albertel 10421: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10422:
10423: my $symbparm=$symbp.'.'.$spacequalifierrest;
10424: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10425:
1.620 albertel 10426: if (($env{'user.name'} eq $uname) &&
10427: ($env{'user.domain'} eq $udom)) {
10428: $section=$env{'request.course.sec'};
1.733 raeburn 10429: @groups = split(/:/,$env{'request.course.groups'});
10430: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10431: } else {
1.539 albertel 10432: if (! defined($usection)) {
1.551 albertel 10433: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10434: } else {
10435: $section = $usection;
10436: }
1.733 raeburn 10437: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10438: }
10439:
10440: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10441: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10442: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10443:
1.593 albertel 10444: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10445: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10446: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10447:
1.60 www 10448: # ----------------------------------------------------------- first, check user
1.624 albertel 10449:
10450: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10451: ([$courselevelr,'resource'],
10452: [$courselevelm,'map' ],
10453: [$courselevel, 'course' ]));
1.931 albertel 10454: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10455:
1.594 albertel 10456: # ------------------------------------------------ second, check some of course
1.684 raeburn 10457: my $coursereply;
1.691 raeburn 10458: if (@groups > 0) {
10459: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10460: $mapparm,$spacequalifierrest);
1.927 albertel 10461: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10462: }
1.96 www 10463:
1.684 raeburn 10464: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10465: $env{'course.'.$courseid.'.domain'},
10466: 'course',
10467: ([$seclevelr, 'resource'],
10468: [$seclevelm, 'map' ],
10469: [$seclevel, 'course' ],
10470: [$courselevelr,'resource']));
10471: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10472:
1.60 www 10473: # ------------------------------------------------------ third, check map parms
1.218 albertel 10474: my %parmhash=();
10475: my $thisparm='';
10476: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10477: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10478: &GDBM_READER(),0640)) {
1.218 albertel 10479: $thisparm=$parmhash{$symbparm};
10480: untie(%parmhash);
10481: }
1.927 albertel 10482: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10483: }
1.594 albertel 10484: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10485:
1.218 albertel 10486: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10487: my $filename;
10488: if (!$symbparm) { $symbparm=&symbread(); }
10489: if ($symbparm) {
1.409 www 10490: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10491: } else {
1.620 albertel 10492: $filename=$env{'request.filename'};
1.282 albertel 10493: }
10494: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10495: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10496: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10497: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10498:
1.927 albertel 10499: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10500: if ($symbparm && defined($courseid) &&
1.620 albertel 10501: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10502: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10503: $env{'course.'.$courseid.'.domain'},
10504: 'course',
1.927 albertel 10505: ([$courselevelm,'map' ],
10506: [$courselevel, 'course']));
10507: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10508: }
1.145 www 10509: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10510: unless ($space eq '0') {
1.336 albertel 10511: my @parts=split(/_/,$space);
10512: my $id=pop(@parts);
10513: my $part=join('_',@parts);
10514: if ($part eq '') { $part='0'; }
1.927 albertel 10515: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10516: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10517: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10518: }
1.395 albertel 10519: if ($recurse) { return undef; }
10520: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10521: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10522: # ---------------------------------------------------- Any other user namespace
10523: } elsif ($realm eq 'environment') {
10524: # ----------------------------------------------------------------- environment
1.620 albertel 10525: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10526: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10527: } else {
1.770 albertel 10528: if ($uname eq 'anonymous' && $udom eq '') {
10529: return '';
10530: }
1.219 albertel 10531: my %returnhash=&userenvironment($udom,$uname,
10532: $spacequalifierrest);
10533: return $returnhash{$spacequalifierrest};
10534: }
1.28 www 10535: } elsif ($realm eq 'system') {
1.48 www 10536: # ----------------------------------------------------------------- system.time
10537: if ($space eq 'time') {
10538: return time;
10539: }
1.696 albertel 10540: } elsif ($realm eq 'server') {
10541: # ----------------------------------------------------------------- system.time
10542: if ($space eq 'name') {
10543: return $ENV{'SERVER_NAME'};
10544: }
1.28 www 10545: }
1.48 www 10546: return '';
1.61 www 10547: }
10548:
1.927 albertel 10549: sub get_reply {
10550: my ($reply_value) = @_;
1.940 raeburn 10551: if (ref($reply_value) eq 'ARRAY') {
10552: if (wantarray) {
10553: return @$reply_value;
10554: }
10555: return $reply_value->[0];
10556: } else {
10557: return $reply_value;
1.927 albertel 10558: }
10559: }
10560:
1.691 raeburn 10561: sub check_group_parms {
10562: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10563: my @groupitems = ();
10564: my $resultitem;
1.927 albertel 10565: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10566: foreach my $group (@{$groups}) {
10567: foreach my $level (@levels) {
1.927 albertel 10568: my $item = $courseid.'.['.$group.'].'.$level->[0];
10569: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10570: }
10571: }
10572: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10573: $env{'course.'.$courseid.'.domain'},
10574: 'course',@groupitems);
10575: return $coursereply;
10576: }
10577:
10578: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10579: my ($courseid,@groups) = @_;
10580: @groups = sort(@groups);
1.691 raeburn 10581: return @groups;
10582: }
10583:
1.395 albertel 10584: sub packages_tab_default {
10585: my ($uri,$varname)=@_;
10586: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10587:
10588: my (@extension,@specifics,$do_default);
10589: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10590: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10591: if ($pack_type eq 'default') {
10592: $do_default=1;
10593: } elsif ($pack_type eq 'extension') {
10594: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10595: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10596: # only look at packages defaults for packages that this id is
1.738 albertel 10597: push(@specifics,[$package,$pack_type,$pack_part]);
10598: }
10599: }
10600: # first look for a package that matches the requested part id
10601: foreach my $package (@specifics) {
10602: my (undef,$pack_type,$pack_part)=@{$package};
10603: next if ($pack_part ne $part);
10604: if (defined($packagetab{"$pack_type&$name&default"})) {
10605: return $packagetab{"$pack_type&$name&default"};
10606: }
10607: }
10608: # look for any possible matching non extension_ package
10609: foreach my $package (@specifics) {
10610: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10611: if (defined($packagetab{"$pack_type&$name&default"})) {
10612: return $packagetab{"$pack_type&$name&default"};
10613: }
1.585 albertel 10614: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10615: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10616: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10617: }
10618: }
1.738 albertel 10619: # look for any posible extension_ match
10620: foreach my $package (@extension) {
10621: my ($package,$pack_type)=@{$package};
10622: if (defined($packagetab{"$pack_type&$name&default"})) {
10623: return $packagetab{"$pack_type&$name&default"};
10624: }
10625: if (defined($packagetab{$package."&$name&default"})) {
10626: return $packagetab{$package."&$name&default"};
10627: }
10628: }
10629: # look for a global default setting
10630: if ($do_default && defined($packagetab{"default&$name&default"})) {
10631: return $packagetab{"default&$name&default"};
10632: }
1.395 albertel 10633: return undef;
10634: }
10635:
1.334 albertel 10636: sub add_prefix_and_part {
10637: my ($prefix,$part)=@_;
10638: my $keyroot;
10639: if (defined($prefix) && $prefix !~ /^__/) {
10640: # prefix that has a part already
10641: $keyroot=$prefix;
10642: } elsif (defined($prefix)) {
10643: # prefix that is missing a part
10644: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10645: } else {
10646: # no prefix at all
10647: if (defined($part)) { $keyroot='_'.$part; }
10648: }
10649: return $keyroot;
10650: }
10651:
1.71 www 10652: # ---------------------------------------------------------------- Get metadata
10653:
1.599 albertel 10654: my %metaentry;
1.1070 www 10655: my %importedpartids;
1.71 www 10656: sub metadata {
1.176 www 10657: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10658: $uri=&declutter($uri);
1.288 albertel 10659: # if it is a non metadata possible uri return quickly
1.529 albertel 10660: if (($uri eq '') ||
10661: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10662: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10663: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10664: return undef;
10665: }
1.1172.2.49 raeburn 10666: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10667: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10668: return undef;
1.288 albertel 10669: }
1.73 www 10670: my $filename=$uri;
10671: $uri=~s/\.meta$//;
1.172 www 10672: #
10673: # Is the metadata already cached?
1.177 www 10674: # Look at timestamp of caching
1.172 www 10675: # Everything is cached by the main uri, libraries are never directly cached
10676: #
1.428 albertel 10677: if (!defined($liburi)) {
1.599 albertel 10678: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10679: if (defined($cached)) { return $result->{':'.$what}; }
10680: }
10681: {
1.1069 www 10682: # Imported parts would go here
1.1070 www 10683: my %importedids=();
10684: my @origfileimportpartids=();
1.1069 www 10685: my $importedparts=0;
1.172 www 10686: #
10687: # Is this a recursive call for a library?
10688: #
1.599 albertel 10689: # if (! exists($metacache{$uri})) {
10690: # $metacache{$uri}={};
10691: # }
1.924 albertel 10692: my $cachetime = 60*60;
1.171 www 10693: if ($liburi) {
10694: $liburi=&declutter($liburi);
10695: $filename=$liburi;
1.401 bowersj2 10696: } else {
1.599 albertel 10697: &devalidate_cache_new('meta',$uri);
10698: undef(%metaentry);
1.401 bowersj2 10699: }
1.140 www 10700: my %metathesekeys=();
1.73 www 10701: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10702: my $metastring;
1.1140 www 10703: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10704: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10705: $metastring =
1.929 albertel 10706: &Apache::lonnet::ssi_body($which,
1.924 albertel 10707: ('grade_target' => 'meta'));
10708: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10709: } elsif (($uri !~ m -^(editupload)/-) &&
10710: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10711: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10712: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10713: $metastring=&getfile($file);
1.489 albertel 10714: }
1.208 albertel 10715: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10716: my $token;
1.140 www 10717: undef %metathesekeys;
1.71 www 10718: while ($token=$parser->get_token) {
1.339 albertel 10719: if ($token->[0] eq 'S') {
10720: if (defined($token->[2]->{'package'})) {
1.172 www 10721: #
10722: # This is a package - get package info
10723: #
1.339 albertel 10724: my $package=$token->[2]->{'package'};
10725: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10726: if (defined($token->[2]->{'id'})) {
10727: $keyroot.='_'.$token->[2]->{'id'};
10728: }
1.599 albertel 10729: if ($metaentry{':packages'}) {
10730: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10731: } else {
1.599 albertel 10732: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10733: }
1.736 albertel 10734: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10735: my $part=$keyroot;
10736: $part=~s/^\_//;
1.736 albertel 10737: if ($pack_entry=~/^\Q$package\E\&/ ||
10738: $pack_entry=~/^\Q$package\E_0\&/) {
10739: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10740: # ignore package.tab specified default values
10741: # here &package_tab_default() will fetch those
10742: if ($subp eq 'default') { next; }
1.736 albertel 10743: my $value=$packagetab{$pack_entry};
1.432 albertel 10744: my $unikey;
10745: if ($pack =~ /_0$/) {
10746: $unikey='parameter_0_'.$name;
10747: $part=0;
10748: } else {
10749: $unikey='parameter'.$keyroot.'_'.$name;
10750: }
1.339 albertel 10751: if ($subp eq 'display') {
10752: $value.=' [Part: '.$part.']';
10753: }
1.599 albertel 10754: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10755: $metathesekeys{$unikey}=1;
1.599 albertel 10756: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10757: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10758: }
1.599 albertel 10759: if (defined($metaentry{':'.$unikey.'.default'})) {
10760: $metaentry{':'.$unikey}=
10761: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10762: }
1.339 albertel 10763: }
10764: }
10765: } else {
1.172 www 10766: #
10767: # This is not a package - some other kind of start tag
1.339 albertel 10768: #
10769: my $entry=$token->[1];
1.1068 www 10770: my $unikey='';
1.175 www 10771:
1.339 albertel 10772: if ($entry eq 'import') {
1.175 www 10773: #
10774: # Importing a library here
1.339 albertel 10775: #
1.1067 www 10776: my $location=$parser->get_text('/import');
10777: my $dir=$filename;
10778: $dir=~s|[^/]*$||;
10779: $location=&filelocation($dir,$location);
1.1069 www 10780:
1.1068 www 10781: my $importmode=$token->[2]->{'importmode'};
10782: if ($importmode eq 'problem') {
1.1069 www 10783: # Import as problem/response
1.1068 www 10784: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10785: } elsif ($importmode eq 'part') {
10786: # Import as part(s)
1.1069 www 10787: $importedparts=1;
10788: # We need to get the original file and the imported file to get the part order correct
10789: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10790: # Load and inspect original file
1.1070 www 10791: if ($#origfileimportpartids<0) {
10792: undef(%importedpartids);
10793: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10794: my $origfile=&getfile($origfilelocation);
10795: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10796: }
10797:
1.1069 www 10798: # Load and inspect imported file
10799: my $impfile=&getfile($location);
10800: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10801: if ($#impfilepartids>=0) {
10802: # This problem had parts
1.1070 www 10803: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10804: } else {
10805: # Importing by turning a single problem into a problem part
10806: # It gets the import-tags ID as part-ID
10807: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10808: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10809: }
1.1068 www 10810: } else {
10811: # Normal import
10812: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10813: if (defined($token->[2]->{'id'})) {
10814: $unikey.='_'.$token->[2]->{'id'};
10815: }
1.1067 www 10816: }
10817:
1.339 albertel 10818: if ($depthcount<20) {
1.736 albertel 10819: my $metadata =
10820: &metadata($uri,'keys', $location,$unikey,
10821: $depthcount+1);
10822: foreach my $meta (split(',',$metadata)) {
10823: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10824: $metathesekeys{$meta}=1;
1.339 albertel 10825: }
1.1068 www 10826:
10827: }
1.1067 www 10828: } else {
10829: #
10830: # Not importing, some other kind of non-package, non-library start tag
10831: #
10832: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10833: if (defined($token->[2]->{'id'})) {
10834: $unikey.='_'.$token->[2]->{'id'};
10835: }
1.339 albertel 10836: if (defined($token->[2]->{'name'})) {
10837: $unikey.='_'.$token->[2]->{'name'};
10838: }
10839: $metathesekeys{$unikey}=1;
1.736 albertel 10840: foreach my $param (@{$token->[3]}) {
10841: $metaentry{':'.$unikey.'.'.$param} =
10842: $token->[2]->{$param};
1.339 albertel 10843: }
10844: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10845: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10846: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10847: # only ws inside the tag, and not in default, so use default
10848: # as value
1.599 albertel 10849: $metaentry{':'.$unikey}=$default;
1.908 albertel 10850: } elsif ( $internaltext =~ /\S/ ) {
10851: # something interesting inside the tag
10852: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10853: } else {
1.908 albertel 10854: # no interesting values, don't set a default
1.339 albertel 10855: }
1.172 www 10856: # end of not-a-package not-a-library import
1.339 albertel 10857: }
1.172 www 10858: # end of not-a-package start tag
1.339 albertel 10859: }
1.172 www 10860: # the next is the end of "start tag"
1.339 albertel 10861: }
10862: }
1.483 albertel 10863: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10864: $extension = lc($extension);
10865: if ($extension eq 'htm') { $extension='html'; }
10866:
1.737 albertel 10867: foreach my $key (keys(%packagetab)) {
1.483 albertel 10868: #no specific packages #how's our extension
10869: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10870: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10871: \%metathesekeys);
10872: }
1.883 albertel 10873:
10874: if (!exists($metaentry{':packages'})
10875: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10876: foreach my $key (keys(%packagetab)) {
1.483 albertel 10877: #no specific packages well let's get default then
10878: if ($key!~/^default&/) { next; }
1.488 albertel 10879: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10880: \%metathesekeys);
10881: }
10882: }
1.338 www 10883: # are there custom rights to evaluate
1.599 albertel 10884: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10885:
1.338 www 10886: #
10887: # Importing a rights file here
1.339 albertel 10888: #
10889: unless ($depthcount) {
1.599 albertel 10890: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10891: my $dir=$filename;
10892: $dir=~s|[^/]*$||;
10893: $location=&filelocation($dir,$location);
1.736 albertel 10894: my $rights_metadata =
10895: &metadata($uri,'keys',$location,'_rights',
10896: $depthcount+1);
10897: foreach my $rights (split(',',$rights_metadata)) {
10898: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10899: $metathesekeys{$rights}=1;
1.339 albertel 10900: }
10901: }
10902: }
1.737 albertel 10903: # uniqifiy package listing
10904: my %seen;
10905: my @uniq_packages =
10906: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10907: $metaentry{':packages'} = join(',',@uniq_packages);
10908:
1.1070 www 10909: if ($importedparts) {
10910: # We had imported parts and need to rebuild partorder
10911: $metaentry{':partorder'}='';
10912: $metathesekeys{'partorder'}=1;
10913: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10914: if ($origfileimportpartids[$index] eq 'part') {
10915: # original part, part of the problem
10916: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10917: } else {
10918: # we have imported parts at this position
10919: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10920: }
10921: }
10922: $metaentry{':partorder'}=~s/^\,//;
10923: }
10924:
1.737 albertel 10925: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10926: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10927: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10928: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10929: # this is the end of "was not already recently cached
1.71 www 10930: }
1.599 albertel 10931: return $metaentry{':'.$what};
1.261 albertel 10932: }
10933:
1.488 albertel 10934: sub metadata_create_package_def {
1.483 albertel 10935: my ($uri,$key,$package,$metathesekeys)=@_;
10936: my ($pack,$name,$subp)=split(/\&/,$key);
10937: if ($subp eq 'default') { next; }
10938:
1.599 albertel 10939: if (defined($metaentry{':packages'})) {
10940: $metaentry{':packages'}.=','.$package;
1.483 albertel 10941: } else {
1.599 albertel 10942: $metaentry{':packages'}=$package;
1.483 albertel 10943: }
10944: my $value=$packagetab{$key};
10945: my $unikey;
10946: $unikey='parameter_0_'.$name;
1.599 albertel 10947: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10948: $$metathesekeys{$unikey}=1;
1.599 albertel 10949: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10950: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10951: }
1.599 albertel 10952: if (defined($metaentry{':'.$unikey.'.default'})) {
10953: $metaentry{':'.$unikey}=
10954: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10955: }
10956: }
10957:
1.261 albertel 10958: sub metadata_generate_part0 {
10959: my ($metadata,$metacache,$uri) = @_;
10960: my %allnames;
1.737 albertel 10961: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10962: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10963: my $part=$$metacache{':'.$metakey.'.part'};
10964: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10965: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10966: $allnames{$name}=$part;
10967: }
10968: }
10969: }
10970: foreach my $name (keys(%allnames)) {
10971: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10972: my $key=":parameter_0_$name";
1.261 albertel 10973: $$metacache{"$key.part"}='0';
10974: $$metacache{"$key.name"}=$name;
1.428 albertel 10975: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10976: $allnames{$name}.'_'.$name.
10977: '.type'};
1.428 albertel 10978: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10979: '.display'};
1.644 www 10980: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10981: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10982: $$metacache{"$key.display"}=$olddis;
10983: }
1.71 www 10984: }
10985:
1.764 albertel 10986: # ------------------------------------------------------ Devalidate title cache
10987:
10988: sub devalidate_title_cache {
10989: my ($url)=@_;
10990: if (!$env{'request.course.id'}) { return; }
10991: my $symb=&symbread($url);
10992: if (!$symb) { return; }
10993: my $key=$env{'request.course.id'}."\0".$symb;
10994: &devalidate_cache_new('title',$key);
10995: }
10996:
1.1014 droeschl 10997: # ------------------------------------------------- Get the title of a course
10998:
10999: sub current_course_title {
11000: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11001: }
1.301 www 11002: # ------------------------------------------------- Get the title of a resource
11003:
11004: sub gettitle {
11005: my $urlsymb=shift;
11006: my $symb=&symbread($urlsymb);
1.534 albertel 11007: if ($symb) {
1.620 albertel 11008: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11009: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11010: if (defined($cached)) {
11011: return $result;
11012: }
1.534 albertel 11013: my ($map,$resid,$url)=&decode_symb($symb);
11014: my $title='';
1.907 albertel 11015: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11016: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11017: } else {
11018: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11019: &GDBM_READER(),0640)) {
11020: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11021: $title=$bighash{'title_'.$mapid.'.'.$resid};
11022: untie(%bighash);
11023: }
1.534 albertel 11024: }
11025: $title=~s/\&colon\;/\:/gs;
11026: if ($title) {
1.1159 www 11027: # Remember both $symb and $title for dynamic metadata
11028: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11029: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11030: # Cache this title and then return it
1.599 albertel 11031: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11032: }
11033: $urlsymb=$url;
11034: }
11035: my $title=&metadata($urlsymb,'title');
11036: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11037: return $title;
1.301 www 11038: }
1.613 albertel 11039:
1.614 albertel 11040: sub get_slot {
11041: my ($which,$cnum,$cdom)=@_;
11042: if (!$cnum || !$cdom) {
1.790 albertel 11043: (undef,my $courseid)=&whichuser();
1.620 albertel 11044: $cdom=$env{'course.'.$courseid.'.domain'};
11045: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11046: }
1.703 albertel 11047: my $key=join("\0",'slots',$cdom,$cnum,$which);
11048: my %slotinfo;
11049: if (exists($remembered{$key})) {
11050: $slotinfo{$which} = $remembered{$key};
11051: } else {
11052: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11053: &Apache::lonhomework::showhash(%slotinfo);
11054: my ($tmp)=keys(%slotinfo);
11055: if ($tmp=~/^error:/) { return (); }
11056: $remembered{$key} = $slotinfo{$which};
11057: }
1.616 albertel 11058: if (ref($slotinfo{$which}) eq 'HASH') {
11059: return %{$slotinfo{$which}};
11060: }
11061: return $slotinfo{$which};
1.614 albertel 11062: }
1.1150 raeburn 11063:
11064: sub get_reservable_slots {
11065: my ($cnum,$cdom,$uname,$udom) = @_;
11066: my $now = time;
11067: my $reservable_info;
11068: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11069: if (exists($remembered{$key})) {
11070: $reservable_info = $remembered{$key};
11071: } else {
11072: my %resv;
11073: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11074: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11075: $reservable_info = \%resv;
11076: $remembered{$key} = $reservable_info;
11077: }
11078: return $reservable_info;
11079: }
11080:
11081: sub get_course_slots {
11082: my ($cnum,$cdom) = @_;
11083: my $hashid=$cnum.':'.$cdom;
11084: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11085: if (defined($cached)) {
11086: if (ref($result) eq 'HASH') {
11087: return %{$result};
11088: }
11089: } else {
11090: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11091: my ($tmp) = keys(%slots);
11092: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11093: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11094: return %slots;
11095: }
11096: }
11097: return;
11098: }
11099:
11100: sub devalidate_slots_cache {
11101: my ($cnum,$cdom)=@_;
11102: my $hashid=$cnum.':'.$cdom;
11103: &devalidate_cache_new('allslots',$hashid);
11104: }
11105:
1.1172.2.8 raeburn 11106: sub get_coursechange {
11107: my ($cdom,$cnum) = @_;
11108: if ($cdom eq '' || $cnum eq '') {
11109: return unless ($env{'request.course.id'});
11110: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11111: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11112: }
11113: my $hashid=$cdom.'_'.$cnum;
11114: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11115: if ((defined($cached)) && ($change ne '')) {
11116: return $change;
11117: } else {
11118: my %crshash;
11119: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11120: if ($crshash{'internal.contentchange'} eq '') {
11121: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11122: if ($change eq '') {
11123: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11124: $change = $crshash{'internal.created'};
11125: }
11126: } else {
11127: $change = $crshash{'internal.contentchange'};
11128: }
11129: my $cachetime = 600;
11130: &do_cache_new('crschange',$hashid,$change,$cachetime);
11131: }
11132: return $change;
11133: }
11134:
11135: sub devalidate_coursechange_cache {
11136: my ($cnum,$cdom)=@_;
11137: my $hashid=$cnum.':'.$cdom;
11138: &devalidate_cache_new('crschange',$hashid);
11139: }
11140:
1.31 www 11141: # ------------------------------------------------- Update symbolic store links
11142:
11143: sub symblist {
11144: my ($mapname,%newhash)=@_;
1.438 www 11145: $mapname=&deversion(&declutter($mapname));
1.31 www 11146: my %hash;
1.620 albertel 11147: if (($env{'request.course.fn'}) && (%newhash)) {
11148: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11149: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11150: foreach my $url (keys(%newhash)) {
1.711 albertel 11151: next if ($url eq 'last_known'
11152: && $env{'form.no_update_last_known'});
11153: $hash{declutter($url)}=&encode_symb($mapname,
11154: $newhash{$url}->[1],
11155: $newhash{$url}->[0]);
1.191 harris41 11156: }
1.31 www 11157: if (untie(%hash)) {
11158: return 'ok';
11159: }
11160: }
11161: }
11162: return 'error';
1.212 www 11163: }
11164:
11165: # --------------------------------------------------------------- Verify a symb
11166:
11167: sub symbverify {
1.1172.2.11 raeburn 11168: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11169: my $thisfn=$thisurl;
1.439 www 11170: $thisfn=&declutter($thisfn);
1.215 www 11171: # direct jump to resource in page or to a sequence - will construct own symbs
11172: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11173: # check URL part
1.409 www 11174: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11175:
1.431 www 11176: unless ($url eq $thisfn) { return 0; }
1.213 www 11177:
1.216 www 11178: $symb=&symbclean($symb);
1.510 www 11179: $thisurl=&deversion($thisurl);
1.439 www 11180: $thisfn=&deversion($thisfn);
1.213 www 11181:
11182: my %bighash;
11183: my $okay=0;
1.431 www 11184:
1.620 albertel 11185: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11186: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11187: my $noclutter;
1.1032 raeburn 11188: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11189: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11190: if ($map =~ m{^uploaded/.+\.page$}) {
11191: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11192: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11193: $noclutter = 1;
11194: }
11195: }
11196: my $ids;
11197: if ($noclutter) {
11198: $ids=$bighash{'ids_'.$thisurl};
11199: } else {
11200: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11201: }
1.1102 raeburn 11202: unless ($ids) {
1.1172.2.13 raeburn 11203: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11204: $ids=$bighash{$idkey};
1.216 www 11205: }
11206: if ($ids) {
11207: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11208: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11209: $symb =~ s/\?.+$//;
11210: }
1.800 albertel 11211: foreach my $id (split(/\,/,$ids)) {
11212: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11213: if (
11214: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11215: eq $symb) {
1.1172.2.11 raeburn 11216: if (ref($encstate)) {
11217: $$encstate = $bighash{'encrypted_'.$id};
11218: }
1.1172.2.13 raeburn 11219: if (($env{'request.role.adv'}) ||
11220: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11221: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11222: $okay=1;
11223: last;
11224: }
11225: }
11226: }
1.216 www 11227: }
1.213 www 11228: untie(%bighash);
11229: }
11230: return $okay;
1.31 www 11231: }
11232:
1.210 www 11233: # --------------------------------------------------------------- Clean-up symb
11234:
11235: sub symbclean {
11236: my $symb=shift;
1.568 albertel 11237: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11238: # remove version from map
11239: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11240:
1.210 www 11241: # remove version from URL
11242: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11243:
1.507 www 11244: # remove wrapper
11245:
1.510 www 11246: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11247: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11248: return $symb;
1.409 www 11249: }
11250:
11251: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11252:
11253: sub encode_symb {
11254: my ($map,$resid,$url)=@_;
11255: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11256: }
1.409 www 11257:
11258: sub decode_symb {
1.568 albertel 11259: my $symb=shift;
11260: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11261: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11262: return (&fixversion($map),$resid,&fixversion($url));
11263: }
11264:
11265: sub fixversion {
11266: my $fn=shift;
1.609 banghart 11267: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11268: my %bighash;
11269: my $uri=&clutter($fn);
1.620 albertel 11270: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11271: # is this cached?
1.599 albertel 11272: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11273: if (defined($cached)) { return $result; }
11274: # unfortunately not cached, or expired
1.620 albertel 11275: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11276: &GDBM_READER(),0640)) {
11277: if ($bighash{'version_'.$uri}) {
11278: my $version=$bighash{'version_'.$uri};
1.444 www 11279: unless (($version eq 'mostrecent') ||
11280: ($version==&getversion($uri))) {
1.440 www 11281: $uri=~s/\.(\w+)$/\.$version\.$1/;
11282: }
11283: }
11284: untie %bighash;
1.413 www 11285: }
1.599 albertel 11286: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11287: }
11288:
11289: sub deversion {
11290: my $url=shift;
11291: $url=~s/\.\d+\.(\w+)$/\.$1/;
11292: return $url;
1.210 www 11293: }
11294:
1.31 www 11295: # ------------------------------------------------------ Return symb list entry
11296:
11297: sub symbread {
1.1172.2.66 raeburn 11298: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11299: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11300: if (defined($env{$cache_str})) {
11301: if ($ignorecachednull) {
11302: return $env{$cache_str} unless ($env{$cache_str} eq '');
11303: } else {
11304: return $env{$cache_str};
11305: }
11306: }
1.242 www 11307: # no filename provided? try from environment
1.1172.2.54 raeburn 11308: unless ($thisfn) {
1.620 albertel 11309: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11310: return $env{$cache_str}=&symbclean($env{'request.symb'});
11311: }
11312: $thisfn=$env{'request.filename'};
1.44 www 11313: }
1.569 albertel 11314: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11315: # is that filename actually a symb? Verify, clean, and return
11316: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11317: if (&symbverify($thisfn,$1)) {
1.620 albertel 11318: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11319: }
1.242 www 11320: }
1.44 www 11321: $thisfn=declutter($thisfn);
1.31 www 11322: my %hash;
1.37 www 11323: my %bighash;
11324: my $syval='';
1.620 albertel 11325: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11326: my $targetfn = $thisfn;
1.609 banghart 11327: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11328: $targetfn = 'adm/wrapper/'.$thisfn;
11329: }
1.687 albertel 11330: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11331: $targetfn=$1;
11332: }
1.620 albertel 11333: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11334: &GDBM_READER(),0640)) {
1.481 raeburn 11335: $syval=$hash{$targetfn};
1.37 www 11336: untie(%hash);
11337: }
11338: # ---------------------------------------------------------- There was an entry
11339: if ($syval) {
1.601 albertel 11340: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11341: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11342: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11343: #return $env{$cache_str}='';
1.601 albertel 11344: #}
11345: #$syval.=$1;
11346: #}
1.37 www 11347: } else {
11348: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11349: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11350: &GDBM_READER(),0640)) {
1.37 www 11351: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11352: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11353: unless ($ids) {
11354: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11355: }
11356: unless ($ids) {
11357: # alias?
11358: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11359: }
1.37 www 11360: if ($ids) {
11361: # ------------------------------------------------------------------- Has ID(s)
11362: my @possibilities=split(/\,/,$ids);
1.39 www 11363: if ($#possibilities==0) {
11364: # ----------------------------------------------- There is only one possibility
1.37 www 11365: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11366: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11367: $resid,$thisfn);
1.1172.2.66 raeburn 11368: if (ref($possibles) eq 'HASH') {
11369: $possibles->{$syval} = 1;
11370: }
11371: if ($checkforblock) {
11372: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11373: if (@blockers) {
11374: $syval = '';
11375: return;
11376: }
11377: }
11378: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11379: # ------------------------------------------ There is more than one possibility
11380: my $realpossible=0;
1.800 albertel 11381: foreach my $id (@possibilities) {
11382: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11383: my $canaccess;
11384: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11385: $canaccess = 1;
11386: } else {
11387: $canaccess = &allowed('bre',$file);
11388: }
11389: if ($canaccess) {
11390: my ($mapid,$resid)=split(/\./,$id);
11391: if ($bighash{'map_type_'.$mapid} ne 'page') {
11392: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11393: $resid,$thisfn);
11394: if (ref($possibles) eq 'HASH') {
11395: $possibles->{$syval} = 1;
11396: }
11397: if ($checkforblock) {
11398: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11399: unless (@blockers > 0) {
11400: $syval = $poss_syval;
11401: $realpossible++;
11402: }
11403: } else {
11404: $syval = $poss_syval;
11405: $realpossible++;
11406: }
11407: }
1.39 www 11408: }
1.191 harris41 11409: }
1.39 www 11410: if ($realpossible!=1) { $syval=''; }
1.249 www 11411: } else {
11412: $syval='';
1.37 www 11413: }
11414: }
1.1172.2.66 raeburn 11415: untie(%bighash);
1.481 raeburn 11416: }
1.31 www 11417: }
1.62 www 11418: if ($syval) {
1.620 albertel 11419: return $env{$cache_str}=$syval;
1.62 www 11420: }
1.31 www 11421: }
1.949 raeburn 11422: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11423: return $env{$cache_str}='';
1.31 www 11424: }
11425:
11426: # ---------------------------------------------------------- Return random seed
11427:
1.32 www 11428: sub numval {
11429: my $txt=shift;
11430: $txt=~tr/A-J/0-9/;
11431: $txt=~tr/a-j/0-9/;
11432: $txt=~tr/K-T/0-9/;
11433: $txt=~tr/k-t/0-9/;
11434: $txt=~tr/U-Z/0-5/;
11435: $txt=~tr/u-z/0-5/;
11436: $txt=~s/\D//g;
1.564 albertel 11437: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11438: return int($txt);
1.368 albertel 11439: }
11440:
1.484 albertel 11441: sub numval2 {
11442: my $txt=shift;
11443: $txt=~tr/A-J/0-9/;
11444: $txt=~tr/a-j/0-9/;
11445: $txt=~tr/K-T/0-9/;
11446: $txt=~tr/k-t/0-9/;
11447: $txt=~tr/U-Z/0-5/;
11448: $txt=~tr/u-z/0-5/;
11449: $txt=~s/\D//g;
11450: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11451: my $total;
11452: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11453: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11454: return int($total);
11455: }
11456:
1.575 albertel 11457: sub numval3 {
11458: use integer;
11459: my $txt=shift;
11460: $txt=~tr/A-J/0-9/;
11461: $txt=~tr/a-j/0-9/;
11462: $txt=~tr/K-T/0-9/;
11463: $txt=~tr/k-t/0-9/;
11464: $txt=~tr/U-Z/0-5/;
11465: $txt=~tr/u-z/0-5/;
11466: $txt=~s/\D//g;
11467: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11468: my $total;
11469: foreach my $val (@txts) { $total+=$val; }
11470: if ($_64bit) { $total=(($total<<32)>>32); }
11471: return $total;
11472: }
11473:
1.675 albertel 11474: sub digest {
11475: my ($data)=@_;
11476: my $digest=&Digest::MD5::md5($data);
11477: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11478: my ($e,$f);
11479: {
11480: use integer;
11481: $e=($a+$b);
11482: $f=($c+$d);
11483: if ($_64bit) {
11484: $e=(($e<<32)>>32);
11485: $f=(($f<<32)>>32);
11486: }
11487: }
11488: if (wantarray) {
11489: return ($e,$f);
11490: } else {
11491: my $g;
11492: {
11493: use integer;
11494: $g=($e+$f);
11495: if ($_64bit) {
11496: $g=(($g<<32)>>32);
11497: }
11498: }
11499: return $g;
11500: }
11501: }
11502:
1.368 albertel 11503: sub latest_rnd_algorithm_id {
1.675 albertel 11504: return '64bit5';
1.366 albertel 11505: }
1.32 www 11506:
1.503 albertel 11507: sub get_rand_alg {
11508: my ($courseid)=@_;
1.790 albertel 11509: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11510: if ($courseid) {
1.620 albertel 11511: return $env{"course.$courseid.rndseed"};
1.503 albertel 11512: }
11513: return &latest_rnd_algorithm_id();
11514: }
11515:
1.562 albertel 11516: sub validCODE {
11517: my ($CODE)=@_;
11518: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11519: return 0;
11520: }
11521:
1.491 albertel 11522: sub getCODE {
1.620 albertel 11523: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11524: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11525: defined($Apache::lonhomework::parsing_a_task) ) &&
11526: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11527: return $Apache::lonhomework::history{'resource.CODE'};
11528: }
11529: return undef;
11530: }
1.1133 foxr 11531: #
11532: # Determines the random seed for a specific context:
11533: #
11534: # parameters:
11535: # symb - in course context the symb for the seed.
11536: # course_id - The course id of the form domain_coursenum.
11537: # domain - Domain for the user.
11538: # course - Course for the user.
11539: # cenv - environment of the course.
11540: #
11541: # NOTE:
11542: # All parameters are picked out of the environment if missing
11543: # or not defined.
11544: # If a symb cannot be determined the current time is used instead.
11545: #
11546: # For a given well defined symb, courside, domain, username,
11547: # and course environment, the seed is reproducible.
11548: #
1.31 www 11549: sub rndseed {
1.1133 foxr 11550: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11551: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11552: if (!defined($symb)) {
1.366 albertel 11553: unless ($symb=$wsymb) { return time; }
11554: }
1.1146 foxr 11555: if (!defined $courseid) {
11556: $courseid=$wcourseid;
11557: }
11558: if (!defined $domain) { $domain=$wdomain; }
11559: if (!defined $username) { $username=$wusername }
1.1133 foxr 11560:
11561: my $which;
11562: if (defined($cenv->{'rndseed'})) {
11563: $which = $cenv->{'rndseed'};
11564: } else {
11565: $which =&get_rand_alg($courseid);
11566: }
1.491 albertel 11567: if (defined(&getCODE())) {
1.675 albertel 11568: if ($which eq '64bit5') {
11569: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11570: } elsif ($which eq '64bit4') {
1.575 albertel 11571: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11572: } else {
11573: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11574: }
1.675 albertel 11575: } elsif ($which eq '64bit5') {
11576: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11577: } elsif ($which eq '64bit4') {
11578: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11579: } elsif ($which eq '64bit3') {
11580: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11581: } elsif ($which eq '64bit2') {
11582: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11583: } elsif ($which eq '64bit') {
11584: return &rndseed_64bit($symb,$courseid,$domain,$username);
11585: }
11586: return &rndseed_32bit($symb,$courseid,$domain,$username);
11587: }
11588:
11589: sub rndseed_32bit {
11590: my ($symb,$courseid,$domain,$username)=@_;
11591: {
11592: use integer;
11593: my $symbchck=unpack("%32C*",$symb) << 27;
11594: my $symbseed=numval($symb) << 22;
11595: my $namechck=unpack("%32C*",$username) << 17;
11596: my $nameseed=numval($username) << 12;
11597: my $domainseed=unpack("%32C*",$domain) << 7;
11598: my $courseseed=unpack("%32C*",$courseid);
11599: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11600: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11601: #&logthis("rndseed :$num:$symb");
1.564 albertel 11602: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11603: return $num;
11604: }
11605: }
11606:
11607: sub rndseed_64bit {
11608: my ($symb,$courseid,$domain,$username)=@_;
11609: {
11610: use integer;
11611: my $symbchck=unpack("%32S*",$symb) << 21;
11612: my $symbseed=numval($symb) << 10;
11613: my $namechck=unpack("%32S*",$username);
11614:
11615: my $nameseed=numval($username) << 21;
11616: my $domainseed=unpack("%32S*",$domain) << 10;
11617: my $courseseed=unpack("%32S*",$courseid);
11618:
11619: my $num1=$symbchck+$symbseed+$namechck;
11620: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11621: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11622: #&logthis("rndseed :$num:$symb");
1.564 albertel 11623: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11624: return "$num1,$num2";
1.155 albertel 11625: }
1.366 albertel 11626: }
11627:
1.443 albertel 11628: sub rndseed_64bit2 {
11629: my ($symb,$courseid,$domain,$username)=@_;
11630: {
11631: use integer;
11632: # strings need to be an even # of cahracters long, it it is odd the
11633: # last characters gets thrown away
11634: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11635: my $symbseed=numval($symb) << 10;
11636: my $namechck=unpack("%32S*",$username.' ');
11637:
11638: my $nameseed=numval($username) << 21;
1.501 albertel 11639: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11640: my $courseseed=unpack("%32S*",$courseid.' ');
11641:
11642: my $num1=$symbchck+$symbseed+$namechck;
11643: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11644: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11645: #&logthis("rndseed :$num:$symb");
1.803 albertel 11646: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11647: return "$num1,$num2";
11648: }
11649: }
11650:
11651: sub rndseed_64bit3 {
11652: my ($symb,$courseid,$domain,$username)=@_;
11653: {
11654: use integer;
11655: # strings need to be an even # of cahracters long, it it is odd the
11656: # last characters gets thrown away
11657: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11658: my $symbseed=numval2($symb) << 10;
11659: my $namechck=unpack("%32S*",$username.' ');
11660:
11661: my $nameseed=numval2($username) << 21;
1.443 albertel 11662: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11663: my $courseseed=unpack("%32S*",$courseid.' ');
11664:
11665: my $num1=$symbchck+$symbseed+$namechck;
11666: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11667: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11668: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11669: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11670:
1.503 albertel 11671: return "$num1:$num2";
1.443 albertel 11672: }
11673: }
11674:
1.575 albertel 11675: sub rndseed_64bit4 {
11676: my ($symb,$courseid,$domain,$username)=@_;
11677: {
11678: use integer;
11679: # strings need to be an even # of cahracters long, it it is odd the
11680: # last characters gets thrown away
11681: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11682: my $symbseed=numval3($symb) << 10;
11683: my $namechck=unpack("%32S*",$username.' ');
11684:
11685: my $nameseed=numval3($username) << 21;
11686: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11687: my $courseseed=unpack("%32S*",$courseid.' ');
11688:
11689: my $num1=$symbchck+$symbseed+$namechck;
11690: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11691: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11692: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11693: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11694:
1.575 albertel 11695: return "$num1:$num2";
11696: }
11697: }
11698:
1.675 albertel 11699: sub rndseed_64bit5 {
11700: my ($symb,$courseid,$domain,$username)=@_;
11701: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11702: return "$num1:$num2";
11703: }
11704:
1.366 albertel 11705: sub rndseed_CODE_64bit {
11706: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11707: {
1.366 albertel 11708: use integer;
1.443 albertel 11709: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11710: my $symbseed=numval2($symb);
1.491 albertel 11711: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11712: my $CODEseed=numval(&getCODE());
1.443 albertel 11713: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11714: my $num1=$symbseed+$CODEchck;
11715: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11716: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11717: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11718: if ($_64bit) { $num1=(($num1<<32)>>32); }
11719: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11720: return "$num1:$num2";
1.366 albertel 11721: }
11722: }
11723:
1.575 albertel 11724: sub rndseed_CODE_64bit4 {
11725: my ($symb,$courseid,$domain,$username)=@_;
11726: {
11727: use integer;
11728: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11729: my $symbseed=numval3($symb);
11730: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11731: my $CODEseed=numval3(&getCODE());
11732: my $courseseed=unpack("%32S*",$courseid.' ');
11733: my $num1=$symbseed+$CODEchck;
11734: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11735: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11736: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11737: if ($_64bit) { $num1=(($num1<<32)>>32); }
11738: if ($_64bit) { $num2=(($num2<<32)>>32); }
11739: return "$num1:$num2";
11740: }
11741: }
11742:
1.675 albertel 11743: sub rndseed_CODE_64bit5 {
11744: my ($symb,$courseid,$domain,$username)=@_;
11745: my $code = &getCODE();
11746: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11747: return "$num1:$num2";
11748: }
11749:
1.366 albertel 11750: sub setup_random_from_rndseed {
11751: my ($rndseed)=@_;
1.503 albertel 11752: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11753: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11754: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11755: &Math::Random::random_set_seed_from_phrase($rndseed);
11756: } else {
11757: &Math::Random::random_set_seed($num1,$num2);
11758: }
1.366 albertel 11759: } else {
11760: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11761: }
1.36 albertel 11762: }
11763:
1.474 albertel 11764: sub latest_receipt_algorithm_id {
1.835 albertel 11765: return 'receipt3';
1.474 albertel 11766: }
11767:
1.480 www 11768: sub recunique {
11769: my $fucourseid=shift;
11770: my $unique;
1.835 albertel 11771: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11772: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11773: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11774: } else {
11775: $unique=$perlvar{'lonReceipt'};
11776: }
11777: return unpack("%32C*",$unique);
11778: }
11779:
11780: sub recprefix {
11781: my $fucourseid=shift;
11782: my $prefix;
1.835 albertel 11783: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11784: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11785: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11786: } else {
11787: $prefix=$perlvar{'lonHostID'};
11788: }
11789: return unpack("%32C*",$prefix);
11790: }
11791:
1.76 www 11792: sub ireceipt {
1.474 albertel 11793: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11794:
11795: my $return =&recprefix($fucourseid).'-';
11796:
11797: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11798: $env{'request.state'} eq 'construct') {
11799: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11800: return $return;
11801: }
11802:
1.76 www 11803: my $cuname=unpack("%32C*",$funame);
11804: my $cudom=unpack("%32C*",$fudom);
11805: my $cucourseid=unpack("%32C*",$fucourseid);
11806: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11807: my $cunique=&recunique($fucourseid);
1.474 albertel 11808: my $cpart=unpack("%32S*",$part);
1.835 albertel 11809: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11810:
1.790 albertel 11811: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11812:
11813: $return.= ($cunique%$cuname+
11814: $cunique%$cudom+
11815: $cusymb%$cuname+
11816: $cusymb%$cudom+
11817: $cucourseid%$cuname+
11818: $cucourseid%$cudom+
11819: $cpart%$cuname+
11820: $cpart%$cudom);
11821: } else {
11822: $return.= ($cunique%$cuname+
11823: $cunique%$cudom+
11824: $cusymb%$cuname+
11825: $cusymb%$cudom+
11826: $cucourseid%$cuname+
11827: $cucourseid%$cudom);
11828: }
11829: return $return;
1.76 www 11830: }
11831:
11832: sub receipt {
1.474 albertel 11833: my ($part)=@_;
1.790 albertel 11834: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11835: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11836: }
1.260 ng 11837:
1.790 albertel 11838: sub whichuser {
11839: my ($passedsymb)=@_;
11840: my ($symb,$courseid,$domain,$name,$publicuser);
11841: if (defined($env{'form.grade_symb'})) {
11842: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11843: my $allowed=&allowed('vgr',$tmp_courseid);
11844: if (!$allowed &&
11845: exists($env{'request.course.sec'}) &&
11846: $env{'request.course.sec'} !~ /^\s*$/) {
11847: $allowed=&allowed('vgr',$tmp_courseid.
11848: '/'.$env{'request.course.sec'});
11849: }
11850: if ($allowed) {
11851: ($symb)=&get_env_multiple('form.grade_symb');
11852: $courseid=$tmp_courseid;
11853: ($domain)=&get_env_multiple('form.grade_domain');
11854: ($name)=&get_env_multiple('form.grade_username');
11855: return ($symb,$courseid,$domain,$name,$publicuser);
11856: }
11857: }
11858: if (!$passedsymb) {
11859: $symb=&symbread();
11860: } else {
11861: $symb=$passedsymb;
11862: }
11863: $courseid=$env{'request.course.id'};
11864: $domain=$env{'user.domain'};
11865: $name=$env{'user.name'};
11866: if ($name eq 'public' && $domain eq 'public') {
11867: if (!defined($env{'form.username'})) {
11868: $env{'form.username'}.=time.rand(10000000);
11869: }
11870: $name.=$env{'form.username'};
11871: }
11872: return ($symb,$courseid,$domain,$name,$publicuser);
11873:
11874: }
11875:
1.36 albertel 11876: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11877: # returns either the contents of the file or
11878: # -1 if the file doesn't exist
1.481 raeburn 11879: #
11880: # if the target is a file that was uploaded via DOCS,
11881: # a check will be made to see if a current copy exists on the local server,
11882: # if it does this will be served, otherwise a copy will be retrieved from
11883: # the home server for the course and stored in /home/httpd/html/userfiles on
11884: # the local server.
1.472 albertel 11885:
1.36 albertel 11886: sub getfile {
1.538 albertel 11887: my ($file) = @_;
1.609 banghart 11888: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11889: &repcopy($file);
11890: return &readfile($file);
11891: }
11892:
11893: sub repcopy_userfile {
11894: my ($file)=@_;
1.1142 raeburn 11895: my $londocroot = $perlvar{'lonDocRoot'};
11896: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11897: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11898: my ($cdom,$cnum,$filename) =
1.811 albertel 11899: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11900: my $uri="/uploaded/$cdom/$cnum/$filename";
11901: if (-e "$file") {
1.828 www 11902: # we already have a local copy, check it out
1.538 albertel 11903: my @fileinfo = stat($file);
1.828 www 11904: my $rtncode;
11905: my $info;
1.538 albertel 11906: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11907: if ($lwpresp ne 'ok') {
1.828 www 11908: # there is no such file anymore, even though we had a local copy
1.482 albertel 11909: if ($rtncode eq '404') {
1.538 albertel 11910: unlink($file);
1.482 albertel 11911: }
11912: return -1;
11913: }
11914: if ($info < $fileinfo[9]) {
1.828 www 11915: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11916: return 'ok';
1.828 www 11917: } else {
11918: # the file is outdated, get rid of it
11919: unlink($file);
1.482 albertel 11920: }
1.828 www 11921: }
11922: # one way or the other, at this point, we don't have the file
11923: # construct the correct path for the file
11924: my @parts = ($cdom,$cnum);
11925: if ($filename =~ m|^(.+)/[^/]+$|) {
11926: push @parts, split(/\//,$1);
11927: }
11928: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11929: foreach my $part (@parts) {
11930: $path .= '/'.$part;
11931: if (!-e $path) {
11932: mkdir($path,0770);
1.482 albertel 11933: }
11934: }
1.828 www 11935: # now the path exists for sure
11936: # get a user agent
11937: my $ua=new LWP::UserAgent;
11938: my $transferfile=$file.'.in.transfer';
11939: # FIXME: this should flock
11940: if (-e $transferfile) { return 'ok'; }
11941: my $request;
11942: $uri=~s/^\///;
1.980 raeburn 11943: my $homeserver = &homeserver($cnum,$cdom);
11944: my $protocol = $protocol{$homeserver};
11945: $protocol = 'http' if ($protocol ne 'https');
11946: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11947: my $response=$ua->request($request,$transferfile);
11948: # did it work?
11949: if ($response->is_error()) {
11950: unlink($transferfile);
11951: &logthis("Userfile repcopy failed for $uri");
11952: return -1;
11953: }
11954: # worked, rename the transfer file
11955: rename($transferfile,$file);
1.607 raeburn 11956: return 'ok';
1.481 raeburn 11957: }
11958:
1.517 albertel 11959: sub tokenwrapper {
11960: my $uri=shift;
1.980 raeburn 11961: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11962: $uri=~s|^/||;
1.620 albertel 11963: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11964: my $token=$1;
1.552 albertel 11965: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11966: if ($udom && $uname && $file) {
11967: $file=~s|(\?\.*)*$||;
1.949 raeburn 11968: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11969: my $homeserver = &homeserver($uname,$udom);
11970: my $protocol = $protocol{$homeserver};
11971: $protocol = 'http' if ($protocol ne 'https');
11972: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11973: (($uri=~/\?/)?'&':'?').'token='.$token.
11974: '&tokenissued='.$perlvar{'lonHostID'};
11975: } else {
11976: return '/adm/notfound.html';
11977: }
11978: }
11979:
1.828 www 11980: # call with reqtype HEAD: get last modification time
11981: # call with reqtype GET: get the file contents
11982: # Do not call this with reqtype GET for large files! It loads everything into memory
11983: #
1.481 raeburn 11984: sub getuploaded {
11985: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11986: $uri=~s/^\///;
1.980 raeburn 11987: my $homeserver = &homeserver($cnum,$cdom);
11988: my $protocol = $protocol{$homeserver};
11989: $protocol = 'http' if ($protocol ne 'https');
11990: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11991: my $ua=new LWP::UserAgent;
11992: my $request=new HTTP::Request($reqtype,$uri);
11993: my $response=$ua->request($request);
11994: $$rtncode = $response->code;
1.482 albertel 11995: if (! $response->is_success()) {
11996: return 'failed';
11997: }
11998: if ($reqtype eq 'HEAD') {
1.486 www 11999: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12000: } elsif ($reqtype eq 'GET') {
12001: $$info = $response->content;
1.472 albertel 12002: }
1.482 albertel 12003: return 'ok';
1.36 albertel 12004: }
12005:
1.481 raeburn 12006: sub readfile {
12007: my $file = shift;
12008: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12009: my $fh;
12010: open($fh,"<$file");
12011: my $a='';
1.800 albertel 12012: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12013: return $a;
12014: }
12015:
1.36 albertel 12016: sub filelocation {
1.590 banghart 12017: my ($dir,$file) = @_;
12018: my $location;
12019: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12020:
12021: if ($file =~ m-^/adm/-) {
12022: $file=~s-^/adm/wrapper/-/-;
12023: $file=~s-^/adm/coursedocs/showdoc/-/-;
12024: }
1.882 albertel 12025:
1.1139 www 12026: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12027: $location = $file;
1.609 banghart 12028: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12029: my ($udom,$uname,$filename)=
1.811 albertel 12030: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12031: my $home=&homeserver($uname,$udom);
12032: my $is_me=0;
12033: my @ids=¤t_machine_ids();
12034: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12035: if ($is_me) {
1.1117 foxr 12036: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12037: } else {
12038: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12039: $udom.'/'.$uname.'/'.$filename;
12040: }
1.882 albertel 12041: } elsif ($file =~ m-^/adm/-) {
12042: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12043: } else {
12044: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12045: $file=~s:^/(res|priv)/:/:;
12046: my $space=$1;
1.590 banghart 12047: if ( !( $file =~ m:^/:) ) {
12048: $location = $dir. '/'.$file;
12049: } else {
1.1142 raeburn 12050: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12051: }
1.59 albertel 12052: }
1.590 banghart 12053: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12054: while ($location=~m{/\.\./}) {
12055: if ($location =~ m{/[^/]+/\.\./}) {
12056: $location=~ s{/[^/]+/\.\./}{/}g;
12057: } else {
12058: $location=~ s{/\.\./}{/}g;
12059: }
12060: } #remove dir/..
1.590 banghart 12061: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12062: return $location;
1.46 www 12063: }
1.36 albertel 12064:
1.46 www 12065: sub hreflocation {
12066: my ($dir,$file)=@_;
1.980 raeburn 12067: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12068: $file=filelocation($dir,$file);
1.700 albertel 12069: } elsif ($file=~m-^/adm/-) {
12070: $file=~s-^/adm/wrapper/-/-;
12071: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12072: }
12073: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12074: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12075: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12076: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12077: {/uploaded/$1/$2/}x;
1.46 www 12078: }
1.913 albertel 12079: if ($file=~ m{^/userfiles/}) {
12080: $file =~ s{^/userfiles/}{/uploaded/};
12081: }
1.462 albertel 12082: return $file;
1.465 albertel 12083: }
12084:
1.1139 www 12085:
12086:
12087:
12088:
1.465 albertel 12089: sub current_machine_domains {
1.853 albertel 12090: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12091: }
12092:
12093: sub machine_domains {
12094: my ($hostname) = @_;
1.465 albertel 12095: my @domains;
1.838 albertel 12096: my %hostname = &all_hostnames();
1.465 albertel 12097: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12098: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12099: if ($hostname eq $name) {
1.844 albertel 12100: push(@domains,&host_domain($id));
1.465 albertel 12101: }
12102: }
12103: return @domains;
12104: }
12105:
12106: sub current_machine_ids {
1.853 albertel 12107: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12108: }
12109:
12110: sub machine_ids {
12111: my ($hostname) = @_;
12112: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12113: my @ids;
1.888 albertel 12114: my %name_to_host = &all_names();
1.889 albertel 12115: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12116: return @{ $name_to_host{$hostname} };
12117: }
12118: return;
1.31 www 12119: }
12120:
1.824 raeburn 12121: sub additional_machine_domains {
12122: my @domains;
12123: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12124: while( my $line = <$fh>) {
12125: $line =~ s/\s//g;
12126: push(@domains,$line);
12127: }
12128: return @domains;
12129: }
12130:
12131: sub default_login_domain {
12132: my $domain = $perlvar{'lonDefDomain'};
12133: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12134: foreach my $posdom (¤t_machine_domains(),
12135: &additional_machine_domains()) {
12136: if (lc($posdom) eq lc($testdomain)) {
12137: $domain=$posdom;
12138: last;
12139: }
12140: }
12141: return $domain;
12142: }
12143:
1.31 www 12144: # ------------------------------------------------------------- Declutters URLs
12145:
12146: sub declutter {
12147: my $thisfn=shift;
1.569 albertel 12148: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12149: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12150: $thisfn=~s{^/home/httpd/html}{};
12151: }
1.31 www 12152: $thisfn=~s/^\///;
1.697 albertel 12153: $thisfn=~s|^adm/wrapper/||;
12154: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12155: $thisfn=~s/^res\///;
1.1172 bisitz 12156: $thisfn=~s/^priv\///;
1.1032 raeburn 12157: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12158: $thisfn=~s/\?.+$//;
12159: }
1.268 www 12160: return $thisfn;
12161: }
12162:
12163: # ------------------------------------------------------------- Clutter up URLs
12164:
12165: sub clutter {
12166: my $thisfn='/'.&declutter(shift);
1.887 albertel 12167: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12168: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12169: $thisfn='/res'.$thisfn;
12170: }
1.1031 raeburn 12171: if ($thisfn !~m|^/adm|) {
12172: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12173: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12174: } else {
12175: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12176: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12177: if ($embstyle eq 'ssi'
12178: || ($embstyle eq 'hdn')
12179: || ($embstyle eq 'rat')
12180: || ($embstyle eq 'prv')
12181: || ($embstyle eq 'ign')) {
12182: #do nothing with these
12183: } elsif (($embstyle eq 'img')
1.695 albertel 12184: || ($embstyle eq 'emb')
12185: || ($embstyle eq 'wrp')) {
12186: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12187: } elsif ($embstyle eq 'unk'
12188: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12189: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12190: } else {
1.718 www 12191: # &logthis("Got a blank emb style");
1.695 albertel 12192: }
1.694 albertel 12193: }
12194: }
1.31 www 12195: return $thisfn;
1.12 www 12196: }
12197:
1.787 albertel 12198: sub clutter_with_no_wrapper {
12199: my $uri = &clutter(shift);
12200: if ($uri =~ m-^/adm/-) {
12201: $uri =~ s-^/adm/wrapper/-/-;
12202: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12203: }
12204: return $uri;
12205: }
12206:
1.557 albertel 12207: sub freeze_escape {
12208: my ($value)=@_;
12209: if (ref($value)) {
12210: $value=&nfreeze($value);
12211: return '__FROZEN__'.&escape($value);
12212: }
12213: return &escape($value);
12214: }
12215:
1.11 www 12216:
1.557 albertel 12217: sub thaw_unescape {
12218: my ($value)=@_;
12219: if ($value =~ /^__FROZEN__/) {
12220: substr($value,0,10,undef);
12221: $value=&unescape($value);
12222: return &thaw($value);
12223: }
12224: return &unescape($value);
12225: }
12226:
1.436 albertel 12227: sub correct_line_ends {
12228: my ($result)=@_;
12229: $$result =~s/\r\n/\n/mg;
12230: $$result =~s/\r/\n/mg;
1.415 albertel 12231: }
1.1 albertel 12232: # ================================================================ Main Program
12233:
1.184 www 12234: sub goodbye {
1.204 albertel 12235: &logthis("Starting Shut down");
1.443 albertel 12236: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12237: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12238: #converted
1.599 albertel 12239: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12240: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12241: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12242: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12243: #1.1 only
1.870 albertel 12244: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12245: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12246: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12247: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12248: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12249: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12250: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12251: &flushcourselogs();
12252: &logthis("Shutting down");
12253: }
12254:
1.852 albertel 12255: sub get_dns {
1.1172.2.17 raeburn 12256: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12257: if (!$ignore_cache) {
12258: my ($content,$cached)=
12259: &Apache::lonnet::is_cached_new('dns',$url);
12260: if ($cached) {
1.1172.2.17 raeburn 12261: &$func($content,$hashref);
1.869 albertel 12262: return;
12263: }
12264: }
12265:
12266: my %alldns;
1.852 albertel 12267: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12268: foreach my $dns (<$config>) {
12269: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12270: my $line = $1;
12271: my ($host,$protocol) = split(/:/,$line);
12272: if ($protocol ne 'https') {
12273: $protocol = 'http';
12274: }
12275: $alldns{$host} = $protocol;
1.869 albertel 12276: }
12277: while (%alldns) {
1.1172.2.52 raeburn 12278: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12279: my $ua=new LWP::UserAgent;
1.1134 raeburn 12280: $ua->timeout(30);
1.979 raeburn 12281: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12282: my $response=$ua->request($request);
1.979 raeburn 12283: delete($alldns{$dns});
1.852 albertel 12284: next if ($response->is_error());
12285: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12286: unless ($nocache) {
1.1172.2.23 raeburn 12287: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12288: }
12289: &$func(\@content,$hashref);
1.869 albertel 12290: return;
1.852 albertel 12291: }
12292: close($config);
1.871 albertel 12293: my $which = (split('/',$url))[3];
12294: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12295: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12296: my @content = <$config>;
1.1172.2.17 raeburn 12297: &$func(\@content,$hashref);
12298: return;
12299: }
12300:
12301: # ------------------------------------------------------Get DNS checksums file
12302: sub parse_dns_checksums_tab {
12303: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12304: my $lonhost = $perlvar{'lonHostID'};
12305: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12306: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12307: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12308: my $webconfdir = '/etc/httpd/conf';
12309: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12310: $webconfdir = '/etc/apache2';
12311: } elsif ($distro =~ /^sles(\d+)$/) {
12312: if ($1 >= 10) {
12313: $webconfdir = '/etc/apache2';
12314: }
12315: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12316: if ($1 >= 10.0) {
12317: $webconfdir = '/etc/apache2';
12318: }
12319: }
1.1172.2.17 raeburn 12320: my ($release,$timestamp) = split(/\-/,$loncaparev);
12321: my (%chksum,%revnum);
12322: if (ref($lines) eq 'ARRAY') {
12323: chomp(@{$lines});
1.1172.2.34 raeburn 12324: my $version = shift(@{$lines});
12325: if ($version eq $release) {
1.1172.2.17 raeburn 12326: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12327: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12328: if ($file =~ m{^/etc/httpd/conf}) {
12329: if ($webconfdir eq '/etc/apache2') {
12330: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12331: }
12332: }
1.1172.2.34 raeburn 12333: $chksum{$file} = $shasum;
12334: $revnum{$file} = $version;
1.1172.2.17 raeburn 12335: }
12336: if (ref($hashref) eq 'HASH') {
12337: %{$hashref} = (
12338: sums => \%chksum,
12339: versions => \%revnum,
12340: );
12341: }
12342: }
12343: }
1.869 albertel 12344: return;
1.852 albertel 12345: }
1.1172.2.17 raeburn 12346:
12347: sub fetch_dns_checksums {
12348: my %checksums;
1.1172.2.34 raeburn 12349: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12350: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12351: my ($release,$timestamp) = split(/\-/,$loncaparev);
12352: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12353: \%checksums);
12354: return \%checksums;
12355: }
12356:
1.327 albertel 12357: # ------------------------------------------------------------ Read domain file
12358: {
1.852 albertel 12359: my $loaded;
1.846 albertel 12360: my %domain;
12361:
1.852 albertel 12362: sub parse_domain_tab {
12363: my ($lines) = @_;
12364: foreach my $line (@$lines) {
12365: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12366:
1.846 albertel 12367: chomp($line);
1.852 albertel 12368: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12369: my %this_domain;
12370: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12371: 'lang_def', 'city', 'longi', 'lati',
12372: 'primary') {
12373: $this_domain{$field} = shift(@elements);
12374: }
12375: $domain{$name} = \%this_domain;
1.852 albertel 12376: }
12377: }
1.864 albertel 12378:
12379: sub reset_domain_info {
12380: undef($loaded);
12381: undef(%domain);
12382: }
12383:
1.852 albertel 12384: sub load_domain_tab {
1.1172.2.70 raeburn 12385: my ($ignore_cache,$nocache) = @_;
12386: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12387: my $fh;
12388: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12389: my @lines = <$fh>;
12390: &parse_domain_tab(\@lines);
1.448 albertel 12391: }
1.852 albertel 12392: close($fh);
12393: $loaded = 1;
1.327 albertel 12394: }
1.846 albertel 12395:
12396: sub domain {
1.852 albertel 12397: &load_domain_tab() if (!$loaded);
12398:
1.846 albertel 12399: my ($name,$what) = @_;
12400: return if ( !exists($domain{$name}) );
12401:
12402: if (!$what) {
12403: return $domain{$name}{'description'};
12404: }
12405: return $domain{$name}{$what};
12406: }
1.974 raeburn 12407:
12408: sub domain_info {
12409: &load_domain_tab() if (!$loaded);
12410: return %domain;
12411: }
12412:
1.327 albertel 12413: }
12414:
12415:
1.1 albertel 12416: # ------------------------------------------------------------- Read hosts file
12417: {
1.838 albertel 12418: my %hostname;
1.844 albertel 12419: my %hostdom;
1.845 albertel 12420: my %libserv;
1.852 albertel 12421: my $loaded;
1.888 albertel 12422: my %name_to_host;
1.1074 raeburn 12423: my %internetdom;
1.1107 raeburn 12424: my %LC_dns_serv;
1.852 albertel 12425:
12426: sub parse_hosts_tab {
12427: my ($file) = @_;
12428: foreach my $configline (@$file) {
12429: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12430: chomp($configline);
12431: if ($configline =~ /^\^/) {
12432: if ($configline =~ /^\^([\w.\-]+)/) {
12433: $LC_dns_serv{$1} = 1;
12434: }
12435: next;
12436: }
1.1074 raeburn 12437: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12438: $name=~s/\s//g;
12439: if ($id && $domain && $role && $name) {
12440: $hostname{$id}=$name;
1.888 albertel 12441: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12442: $hostdom{$id}=$domain;
12443: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12444: if (defined($protocol)) {
12445: if ($protocol eq 'https') {
12446: $protocol{$id} = $protocol;
12447: } else {
12448: $protocol{$id} = 'http';
12449: }
1.968 raeburn 12450: } else {
1.969 raeburn 12451: $protocol{$id} = 'http';
1.968 raeburn 12452: }
1.1074 raeburn 12453: if (defined($intdom)) {
12454: $internetdom{$id} = $intdom;
12455: }
1.852 albertel 12456: }
12457: }
12458: }
1.864 albertel 12459:
12460: sub reset_hosts_info {
1.897 albertel 12461: &purge_remembered();
1.864 albertel 12462: &reset_domain_info();
12463: &reset_hosts_ip_info();
1.892 albertel 12464: undef(%name_to_host);
1.864 albertel 12465: undef(%hostname);
12466: undef(%hostdom);
12467: undef(%libserv);
12468: undef($loaded);
12469: }
1.1 albertel 12470:
1.852 albertel 12471: sub load_hosts_tab {
1.1172.2.70 raeburn 12472: my ($ignore_cache,$nocache) = @_;
12473: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12474: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12475: my @config = <$config>;
12476: &parse_hosts_tab(\@config);
12477: close($config);
12478: $loaded=1;
1.1 albertel 12479: }
1.852 albertel 12480:
1.838 albertel 12481: sub hostname {
1.852 albertel 12482: &load_hosts_tab() if (!$loaded);
12483:
1.838 albertel 12484: my ($lonid) = @_;
12485: return $hostname{$lonid};
12486: }
1.845 albertel 12487:
1.838 albertel 12488: sub all_hostnames {
1.852 albertel 12489: &load_hosts_tab() if (!$loaded);
12490:
1.838 albertel 12491: return %hostname;
12492: }
1.845 albertel 12493:
1.888 albertel 12494: sub all_names {
1.1172.2.70 raeburn 12495: my ($ignore_cache,$nocache) = @_;
12496: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12497:
12498: return %name_to_host;
12499: }
12500:
1.974 raeburn 12501: sub all_host_domain {
12502: &load_hosts_tab() if (!$loaded);
12503: return %hostdom;
12504: }
12505:
1.845 albertel 12506: sub is_library {
1.852 albertel 12507: &load_hosts_tab() if (!$loaded);
12508:
1.845 albertel 12509: return exists($libserv{$_[0]});
12510: }
12511:
12512: sub all_library {
1.852 albertel 12513: &load_hosts_tab() if (!$loaded);
12514:
1.845 albertel 12515: return %libserv;
12516: }
12517:
1.1062 droeschl 12518: sub unique_library {
12519: #2x reverse removes all hostnames that appear more than once
12520: my %unique = reverse &all_library();
12521: return reverse %unique;
12522: }
12523:
1.841 albertel 12524: sub get_servers {
1.852 albertel 12525: &load_hosts_tab() if (!$loaded);
12526:
1.841 albertel 12527: my ($domain,$type) = @_;
12528: my %possible_hosts = ($type eq 'library') ? %libserv
12529: : %hostname;
12530: my %result;
1.842 albertel 12531: if (ref($domain) eq 'ARRAY') {
12532: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12533: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12534: $result{$host} = $hostname;
12535: }
12536: }
12537: } else {
12538: while ( my ($host,$hostname) = each(%possible_hosts)) {
12539: if ($hostdom{$host} eq $domain) {
12540: $result{$host} = $hostname;
12541: }
1.841 albertel 12542: }
12543: }
12544: return %result;
12545: }
1.845 albertel 12546:
1.1062 droeschl 12547: sub get_unique_servers {
12548: my %unique = reverse &get_servers(@_);
12549: return reverse %unique;
12550: }
12551:
1.844 albertel 12552: sub host_domain {
1.852 albertel 12553: &load_hosts_tab() if (!$loaded);
12554:
1.844 albertel 12555: my ($lonid) = @_;
12556: return $hostdom{$lonid};
12557: }
12558:
1.841 albertel 12559: sub all_domains {
1.852 albertel 12560: &load_hosts_tab() if (!$loaded);
12561:
1.841 albertel 12562: my %seen;
12563: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12564: return @uniq;
12565: }
1.1074 raeburn 12566:
12567: sub internet_dom {
12568: &load_hosts_tab() if (!$loaded);
12569:
12570: my ($lonid) = @_;
12571: return $internetdom{$lonid};
12572: }
1.1107 raeburn 12573:
12574: sub is_LC_dns {
12575: &load_hosts_tab() if (!$loaded);
12576:
12577: my ($hostname) = @_;
12578: return exists($LC_dns_serv{$hostname});
12579: }
12580:
1.1 albertel 12581: }
12582:
1.847 albertel 12583: {
12584: my %iphost;
1.856 albertel 12585: my %name_to_ip;
12586: my %lonid_to_ip;
1.869 albertel 12587:
1.847 albertel 12588: sub get_hosts_from_ip {
12589: my ($ip) = @_;
12590: my %iphosts = &get_iphost();
12591: if (ref($iphosts{$ip})) {
12592: return @{$iphosts{$ip}};
12593: }
12594: return;
1.839 albertel 12595: }
1.864 albertel 12596:
12597: sub reset_hosts_ip_info {
12598: undef(%iphost);
12599: undef(%name_to_ip);
12600: undef(%lonid_to_ip);
12601: }
1.856 albertel 12602:
12603: sub get_host_ip {
12604: my ($lonid) = @_;
12605: if (exists($lonid_to_ip{$lonid})) {
12606: return $lonid_to_ip{$lonid};
12607: }
12608: my $name=&hostname($lonid);
12609: my $ip = gethostbyname($name);
12610: return if (!$ip || length($ip) ne 4);
12611: $ip=inet_ntoa($ip);
12612: $name_to_ip{$name} = $ip;
12613: $lonid_to_ip{$lonid} = $ip;
12614: return $ip;
12615: }
1.847 albertel 12616:
12617: sub get_iphost {
1.1172.2.70 raeburn 12618: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12619:
1.869 albertel 12620: if (!$ignore_cache) {
12621: if (%iphost) {
12622: return %iphost;
12623: }
12624: my ($ip_info,$cached)=
12625: &Apache::lonnet::is_cached_new('iphost','iphost');
12626: if ($cached) {
12627: %iphost = %{$ip_info->[0]};
12628: %name_to_ip = %{$ip_info->[1]};
12629: %lonid_to_ip = %{$ip_info->[2]};
12630: return %iphost;
12631: }
12632: }
1.894 albertel 12633:
12634: # get yesterday's info for fallback
12635: my %old_name_to_ip;
12636: my ($ip_info,$cached)=
12637: &Apache::lonnet::is_cached_new('iphost','iphost');
12638: if ($cached) {
12639: %old_name_to_ip = %{$ip_info->[1]};
12640: }
12641:
1.1172.2.70 raeburn 12642: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12643: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12644: my $ip;
12645: if (!exists($name_to_ip{$name})) {
12646: $ip = gethostbyname($name);
12647: if (!$ip || length($ip) ne 4) {
1.894 albertel 12648: if (defined($old_name_to_ip{$name})) {
12649: $ip = $old_name_to_ip{$name};
12650: &logthis("Can't find $name defaulting to old $ip");
12651: } else {
12652: &logthis("Name $name no IP found");
12653: next;
12654: }
12655: } else {
12656: $ip=inet_ntoa($ip);
1.847 albertel 12657: }
12658: $name_to_ip{$name} = $ip;
12659: } else {
12660: $ip = $name_to_ip{$name};
1.653 albertel 12661: }
1.888 albertel 12662: foreach my $id (@{ $name_to_host{$name} }) {
12663: $lonid_to_ip{$id} = $ip;
12664: }
12665: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12666: }
1.1172.2.70 raeburn 12667: unless ($nocache) {
12668: &do_cache_new('iphost','iphost',
12669: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12670: 48*60*60);
12671: }
1.869 albertel 12672:
1.847 albertel 12673: return %iphost;
1.598 albertel 12674: }
12675:
1.992 raeburn 12676: #
12677: # Given a DNS returns the loncapa host name for that DNS
12678: #
12679: sub host_from_dns {
12680: my ($dns) = @_;
12681: my @hosts;
12682: my $ip;
12683:
1.993 raeburn 12684: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12685: $ip = $name_to_ip{$dns};
12686: }
12687: if (!$ip) {
12688: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12689: if (length($ip) == 4) {
12690: $ip = &IO::Socket::inet_ntoa($ip);
12691: }
12692: }
12693: if ($ip) {
12694: @hosts = get_hosts_from_ip($ip);
12695: return $hosts[0];
12696: }
12697: return undef;
1.986 foxr 12698: }
1.992 raeburn 12699:
1.1074 raeburn 12700: sub get_internet_names {
12701: my ($lonid) = @_;
12702: return if ($lonid eq '');
12703: my ($idnref,$cached)=
12704: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12705: if ($cached) {
12706: return $idnref;
12707: }
12708: my $ip = &get_host_ip($lonid);
12709: my @hosts = &get_hosts_from_ip($ip);
12710: my %iphost = &get_iphost();
12711: my (@idns,%seen);
12712: foreach my $id (@hosts) {
12713: my $dom = &host_domain($id);
12714: my $prim_id = &domain($dom,'primary');
12715: my $prim_ip = &get_host_ip($prim_id);
12716: next if ($seen{$prim_ip});
12717: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12718: foreach my $id (@{$iphost{$prim_ip}}) {
12719: my $intdom = &internet_dom($id);
12720: unless (grep(/^\Q$intdom\E$/,@idns)) {
12721: push(@idns,$intdom);
12722: }
12723: }
12724: }
12725: $seen{$prim_ip} = 1;
12726: }
1.1172.2.23 raeburn 12727: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12728: }
12729:
1.986 foxr 12730: }
12731:
1.1079 raeburn 12732: sub all_loncaparevs {
1.1172.2.39 raeburn 12733: 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 12734: }
12735:
1.1172.2.27 raeburn 12736: # ------------------------------------------------------- Read loncaparev table
12737: {
12738: sub load_loncaparevs {
12739: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12740: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12741: while (my $configline=<$config>) {
12742: chomp($configline);
12743: my ($hostid,$loncaparev)=split(/:/,$configline);
12744: $loncaparevs{$hostid}=$loncaparev;
12745: }
12746: close($config);
12747: }
12748: }
12749: }
12750: }
12751:
12752: # ----------------------------------------------------- Read serverhostID table
12753: {
12754: sub load_serverhomeIDs {
12755: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12756: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12757: while (my $configline=<$config>) {
12758: chomp($configline);
12759: my ($name,$id)=split(/:/,$configline);
12760: $serverhomeIDs{$name}=$id;
12761: }
12762: close($config);
12763: }
12764: }
12765: }
12766: }
12767:
12768:
1.862 albertel 12769: BEGIN {
12770:
12771: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12772: unless ($readit) {
12773: {
12774: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12775: %perlvar = (%perlvar,%{$configvars});
12776: }
12777:
12778:
1.1 albertel 12779: # ------------------------------------------------------ Read spare server file
12780: {
1.448 albertel 12781: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12782:
12783: while (my $configline=<$config>) {
12784: chomp($configline);
1.284 matthew 12785: if ($configline) {
1.784 albertel 12786: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12787: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12788: push(@{ $spareid{$type} }, $host);
1.1 albertel 12789: }
12790: }
1.448 albertel 12791: close($config);
1.1 albertel 12792: }
1.11 www 12793: # ------------------------------------------------------------ Read permissions
12794: {
1.448 albertel 12795: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12796:
12797: while (my $configline=<$config>) {
1.448 albertel 12798: chomp($configline);
12799: if ($configline) {
12800: my ($role,$perm)=split(/ /,$configline);
12801: if ($perm ne '') { $pr{$role}=$perm; }
12802: }
1.11 www 12803: }
1.448 albertel 12804: close($config);
1.11 www 12805: }
12806:
12807: # -------------------------------------------- Read plain texts for permissions
12808: {
1.448 albertel 12809: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12810:
12811: while (my $configline=<$config>) {
1.448 albertel 12812: chomp($configline);
12813: if ($configline) {
1.742 raeburn 12814: my ($short,@plain)=split(/:/,$configline);
12815: %{$prp{$short}} = ();
12816: if (@plain > 0) {
12817: $prp{$short}{'std'} = $plain[0];
12818: for (my $i=1; $i<@plain; $i++) {
12819: $prp{$short}{'alt'.$i} = $plain[$i];
12820: }
12821: }
1.448 albertel 12822: }
1.135 www 12823: }
1.448 albertel 12824: close($config);
1.135 www 12825: }
12826:
12827: # ---------------------------------------------------------- Read package table
12828: {
1.448 albertel 12829: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12830:
12831: while (my $configline=<$config>) {
1.483 albertel 12832: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12833: chomp($configline);
12834: my ($short,$plain)=split(/:/,$configline);
12835: my ($pack,$name)=split(/\&/,$short);
12836: if ($plain ne '') {
12837: $packagetab{$pack.'&'.$name.'&name'}=$name;
12838: $packagetab{$short}=$plain;
12839: }
1.11 www 12840: }
1.448 albertel 12841: close($config);
1.329 matthew 12842: }
12843:
1.1172.2.27 raeburn 12844: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12845:
1.1172.2.27 raeburn 12846: &load_loncaparevs();
12847:
12848: # ------------------------------------------------------- Read serverhostID table
12849:
12850: &load_serverhomeIDs();
1.1074 raeburn 12851:
1.1172.2.27 raeburn 12852: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12853: {
12854: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12855: if (-e $file) {
12856: my $parser = HTML::LCParser->new($file);
12857: while (my $token = $parser->get_token()) {
12858: if ($token->[0] eq 'S') {
12859: my $item = $token->[1];
12860: my $name = $token->[2]{'name'};
12861: my $value = $token->[2]{'value'};
12862: if ($item ne '' && $name ne '' && $value ne '') {
12863: my $release = $parser->get_text();
12864: $release =~ s/(^\s*|\s*$ )//gx;
12865: $needsrelease{$item.':'.$name.':'.$value} = $release;
12866: }
12867: }
12868: }
12869: }
1.1073 raeburn 12870: }
12871:
1.1138 raeburn 12872: # ---------------------------------------------------------- Read managers table
12873: {
12874: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12875: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12876: while (my $configline=<$config>) {
12877: chomp($configline);
12878: next if ($configline =~ /^\#/);
12879: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12880: $managerstab{$configline} = 1;
12881: }
12882: }
12883: close($config);
12884: }
12885: }
12886: }
12887:
1.329 matthew 12888: # ------------- set up temporary directory
12889: {
1.1117 foxr 12890: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12891:
1.11 www 12892: }
12893:
1.794 albertel 12894: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12895: 'compress_threshold'=> 20_000,
12896: });
1.185 www 12897:
1.281 www 12898: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12899: $dumpcount=0;
1.958 www 12900: $locknum=0;
1.22 www 12901:
1.163 harris41 12902: &logtouch();
1.672 albertel 12903: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12904: $readit=1;
1.564 albertel 12905: {
12906: use integer;
12907: my $test=(2**32)+1;
1.568 albertel 12908: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12909: &logthis(" Detected 64bit platform ($_64bit)");
12910: }
1.195 www 12911: }
1.1 albertel 12912: }
1.179 www 12913:
1.1 albertel 12914: 1;
1.191 harris41 12915: __END__
12916:
1.243 albertel 12917: =pod
12918:
1.191 harris41 12919: =head1 NAME
12920:
1.243 albertel 12921: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12922:
12923: =head1 SYNOPSIS
12924:
1.243 albertel 12925: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12926:
12927: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12928:
1.243 albertel 12929: Common parameters:
12930:
12931: =over 4
12932:
12933: =item *
12934:
12935: $uname : an internal username (if $cname expecting a course Id specifically)
12936:
12937: =item *
12938:
12939: $udom : a domain (if $cdom expecting a course's domain specifically)
12940:
12941: =item *
12942:
12943: $symb : a resource instance identifier
12944:
12945: =item *
12946:
12947: $namespace : the name of a .db file that contains the data needed or
12948: being set.
12949:
12950: =back
12951:
1.394 bowersj2 12952: =head1 OVERVIEW
1.191 harris41 12953:
1.394 bowersj2 12954: lonnet provides subroutines which interact with the
12955: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12956: about classes, users, and resources.
1.243 albertel 12957:
12958: For many of these objects you can also use this to store data about
12959: them or modify them in various ways.
1.191 harris41 12960:
1.394 bowersj2 12961: =head2 Symbs
1.191 harris41 12962:
1.394 bowersj2 12963: To identify a specific instance of a resource, LON-CAPA uses symbols
12964: or "symbs"X<symb>. These identifiers are built from the URL of the
12965: map, the resource number of the resource in the map, and the URL of
12966: the resource itself. The latter is somewhat redundant, but might help
12967: if maps change.
12968:
12969: An example is
12970:
12971: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12972:
12973: The respective map entry is
12974:
12975: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12976: title="Problem 2">
12977: </resource>
12978:
12979: Symbs are used by the random number generator, as well as to store and
12980: restore data specific to a certain instance of for example a problem.
12981:
12982: =head2 Storing And Retrieving Data
12983:
12984: X<store()>X<cstore()>X<restore()>Three of the most important functions
12985: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12986: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12987: is is the non-critical message twin of cstore. These functions are for
12988: handlers to store a perl hash to a user's permanent data space in an
12989: easy manner, and to retrieve it again on another call. It is expected
12990: that a handler would use this once at the beginning to retrieve data,
12991: and then again once at the end to send only the new data back.
12992:
12993: The data is stored in the user's data directory on the user's
12994: homeserver under the ID of the course.
12995:
12996: The hash that is returned by restore will have all of the previous
12997: value for all of the elements of the hash.
12998:
12999: Example:
13000:
13001: #creating a hash
13002: my %hash;
13003: $hash{'foo'}='bar';
13004:
13005: #storing it
13006: &Apache::lonnet::cstore(\%hash);
13007:
13008: #changing a value
13009: $hash{'foo'}='notbar';
13010:
13011: #adding a new value
13012: $hash{'bar'}='foo';
13013: &Apache::lonnet::cstore(\%hash);
13014:
13015: #retrieving the hash
13016: my %history=&Apache::lonnet::restore();
13017:
13018: #print the hash
13019: foreach my $key (sort(keys(%history))) {
13020: print("\%history{$key} = $history{$key}");
13021: }
13022:
13023: Will print out:
1.191 harris41 13024:
1.394 bowersj2 13025: %history{1:foo} = bar
13026: %history{1:keys} = foo:timestamp
13027: %history{1:timestamp} = 990455579
13028: %history{2:bar} = foo
13029: %history{2:foo} = notbar
13030: %history{2:keys} = foo:bar:timestamp
13031: %history{2:timestamp} = 990455580
13032: %history{bar} = foo
13033: %history{foo} = notbar
13034: %history{timestamp} = 990455580
13035: %history{version} = 2
13036:
13037: Note that the special hash entries C<keys>, C<version> and
13038: C<timestamp> were added to the hash. C<version> will be equal to the
13039: total number of versions of the data that have been stored. The
13040: C<timestamp> attribute will be the UNIX time the hash was
13041: stored. C<keys> is available in every historical section to list which
13042: keys were added or changed at a specific historical revision of a
13043: hash.
13044:
13045: B<Warning>: do not store the hash that restore returns directly. This
13046: will cause a mess since it will restore the historical keys as if the
13047: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13048:
1.394 bowersj2 13049: Calling convention:
1.191 harris41 13050:
1.1172.2.27 raeburn 13051: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13052: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13053:
1.394 bowersj2 13054: For more detailed information, see lonnet specific documentation.
1.191 harris41 13055:
1.394 bowersj2 13056: =head1 RETURN MESSAGES
1.191 harris41 13057:
1.394 bowersj2 13058: =over 4
1.191 harris41 13059:
1.394 bowersj2 13060: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13061:
1.394 bowersj2 13062: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13063: when the connection is brought back up
1.191 harris41 13064:
1.394 bowersj2 13065: =item * B<con_failed>: unable to contact remote host and unable to save message
13066: for later delivery
1.191 harris41 13067:
1.967 bisitz 13068: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13069:
1.394 bowersj2 13070: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13071: that was requested
1.191 harris41 13072:
1.243 albertel 13073: =back
1.191 harris41 13074:
1.243 albertel 13075: =head1 PUBLIC SUBROUTINES
1.191 harris41 13076:
1.243 albertel 13077: =head2 Session Environment Functions
1.191 harris41 13078:
1.243 albertel 13079: =over 4
1.191 harris41 13080:
1.394 bowersj2 13081: =item *
13082: X<appenv()>
1.949 raeburn 13083: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13084: the user envirnoment file, and will be restored for each access this
1.620 albertel 13085: user makes during this session, also modifies the %env for the current
1.949 raeburn 13086: process. Optional rolesarrayref - if defined contains a reference to an array
13087: of roles which are exempt from the restriction on modifying user.role entries
13088: in the user's environment.db and in %env.
1.191 harris41 13089:
13090: =item *
1.394 bowersj2 13091: X<delenv()>
1.987 raeburn 13092: B<delenv($delthis,$regexp)>: removes all items from the session
13093: environment file that begin with $delthis. If the
13094: optional second arg - $regexp - is true, $delthis is treated as a
13095: regular expression, otherwise \Q$delthis\E is used.
13096: The values are also deleted from the current processes %env.
1.191 harris41 13097:
1.795 albertel 13098: =item * get_env_multiple($name)
13099:
13100: gets $name from the %env hash, it seemlessly handles the cases where multiple
13101: values may be defined and end up as an array ref.
13102:
13103: returns an array of values
13104:
1.243 albertel 13105: =back
13106:
13107: =head2 User Information
1.191 harris41 13108:
1.243 albertel 13109: =over 4
1.191 harris41 13110:
13111: =item *
1.394 bowersj2 13112: X<queryauthenticate()>
13113: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13114: authentication scheme
13115:
13116: =item *
1.394 bowersj2 13117: X<authenticate()>
1.1073 raeburn 13118: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13119: authenticate user from domain's lib servers (first use the current
13120: one). C<$upass> should be the users password.
1.1073 raeburn 13121: $checkdefauth is optional (value is 1 if a check should be made to
13122: authenticate user using default authentication method, and allow
13123: account creation if username does not have account in the domain).
13124: $clientcancheckhost is optional (value is 1 if checking whether the
13125: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13126:
13127: =item *
1.394 bowersj2 13128: X<homeserver()>
13129: B<homeserver($uname,$udom)>: find the server which has
13130: the user's directory and files (there must be only one), this caches
13131: the answer, and also caches if there is a borken connection.
1.191 harris41 13132:
13133: =item *
1.394 bowersj2 13134: X<idget()>
13135: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13136: (IDs are a unique resource in a domain, there must be only 1 ID per
13137: username, and only 1 username per ID in a specific domain) (returns
13138: hash: id=>name,id=>name)
1.191 harris41 13139:
13140: =item *
1.394 bowersj2 13141: X<idrget()>
13142: B<idrget($udom,@unames)>: find the IDs behind a list of
13143: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13144:
13145: =item *
1.394 bowersj2 13146: X<idput()>
13147: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13148:
13149: =item *
1.394 bowersj2 13150: X<rolesinit()>
1.1169 droeschl 13151: B<rolesinit($udom,$username)>: get user privileges.
13152: returns user role, first access and timer interval hashes
1.243 albertel 13153:
13154: =item *
1.1171 droeschl 13155: X<privileged()>
13156: B<privileged($username,$domain)>: returns a true if user has a
13157: privileged and active role (i.e. su or dc), false otherwise.
13158:
13159: =item *
1.551 albertel 13160: X<getsection()>
13161: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13162: course $cname, return section name/number or '' for "not in course"
13163: and '-1' for "no section"
13164:
13165: =item *
1.394 bowersj2 13166: X<userenvironment()>
13167: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13168: passed in @what from the requested user's environment, returns a hash
13169:
1.858 raeburn 13170: =item *
13171: X<userlog_query()>
1.859 albertel 13172: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13173: activity.log file. %filters defines filters applied when parsing the
13174: log file. These can be start or end timestamps, or the type of action
13175: - log to look for Login or Logout events, check for Checkin or
13176: Checkout, role for role selection. The response is in the form
13177: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13178: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13179:
1.243 albertel 13180: =back
13181:
13182: =head2 User Roles
13183:
13184: =over 4
13185:
13186: =item *
13187:
1.1172.2.65 raeburn 13188: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13189: returns codes for allowed actions.
13190:
13191: The first argument is required, all others are optional.
13192:
13193: $priv is the privilege being checked.
13194: $uri contains additional information about what is being checked for access (e.g.,
13195: URL, course ID etc.).
13196: $symb is the unique resource instance identifier in a course; if needed,
13197: but not provided, it will be retrieved via a call to &symbread().
13198: $role is the role for which a priv is being checked (only used if priv is evb).
13199: $clientip is the user's IP address (only used when checking for access to portfolio
13200: files).
13201: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13202: prevents recursive calls to &allowed.
13203:
1.243 albertel 13204: F: full access
13205: U,I,K: authentication modes (cxx only)
13206: '': forbidden
13207: 1: user needs to choose course
13208: 2: browse allowed
1.766 albertel 13209: A: passphrase authentication needed
1.1172.2.65 raeburn 13210: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13211:
13212: =item *
13213:
1.1172.2.13 raeburn 13214: constructaccess($url,$setpriv) : check for access to construction space URL
13215:
13216: See if the owner domain and name in the URL match those in the
13217: expected environment. If so, return three element list
13218: ($ownername,$ownerdomain,$ownerhome).
13219:
13220: Otherwise return the null string.
13221:
13222: If second argument 'setpriv' is true, it assigns the privileges,
13223: and returns the same three element list, unless the owner has
13224: blocked "ad hoc" Domain Coordinator access to the Author Space,
13225: in which case the null string is returned.
13226:
13227: =item *
13228:
1.243 albertel 13229: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13230: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13231: and course level
13232:
13233: =item *
13234:
1.988 raeburn 13235: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13236: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13237: $type is Course (default) or Community.
1.988 raeburn 13238: If $forcedefault evaluates to true, text returned will be default
13239: text for $type. Otherwise, if this is a course, the text returned
13240: will be a custom name for the role (if defined in the course's
13241: environment). If no custom name is defined the default is returned.
13242:
1.832 raeburn 13243: =item *
13244:
1.1172.2.23 raeburn 13245: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13246: All arguments are optional. Returns a hash of a roles, either for
13247: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13248: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13249: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13250: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13251: For each key, value is set to colon-separated start and end times for
13252: the role. If no username and domain are specified, will default to
1.934 raeburn 13253: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13254: of role statuses (active, future or previous), roles
13255: (e.g., cc,in, st etc.) and domains of the roles which can be used
13256: to restrict the list of roles reported. If no array ref is
13257: provided for types, will default to return only active roles.
1.834 albertel 13258:
1.1172.2.13 raeburn 13259: =item *
13260:
13261: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13262: user: $uname:$udom has a role in the course: $cdom_$cnum.
13263:
13264: Additional optional arguments are: $type (if role checking is to be restricted
13265: to certain user status types -- previous (expired roles), active (currently
13266: available roles) or future (roles available in the future), and
13267: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13268: have active Domain Coordinator role in course's domain or in additional
13269: domains (specified in 'Domains to check for privileged users' in course
13270: environment -- set via: Course Settings -> Classlists and staff listing).
13271:
13272: =item *
13273:
13274: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13275: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13276: $possdomains and $possroles are optional array refs -- to domains to check and
13277: roles to check. If $possdomains is not specified, a dump will be done of the
13278: users' roles.db to check for a dc or su role in any domain. This can be
13279: time consuming if &privileged is called repeatedly (e.g., when displaying a
13280: classlist), so in such cases, supplying a $possdomains array is preferred, as
13281: this then allows &privileged_by_domain() to be used, which caches the identity
13282: of privileged users, eliminating the need for repeated calls to &dump().
13283:
13284: =item *
13285:
13286: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13287: where the outer hash keys are domains specified in the $possdomains array ref,
13288: next inner hash keys are privileged roles specified in the $roles array ref,
13289: and the innermost hash contains key = value pairs for username:domain = end:start
13290: for active or future "privileged" users with that role in that domain. To avoid
13291: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13292: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13293:
1.243 albertel 13294: =back
13295:
13296: =head2 User Modification
13297:
13298: =over 4
13299:
13300: =item *
13301:
1.957 raeburn 13302: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13303: user for the level given by URL. Optional start and end dates (leave empty
13304: string or zero for "no date")
1.191 harris41 13305:
13306: =item *
13307:
1.243 albertel 13308: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13309: change a users, password, possible return values are: ok,
13310: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13311: refused
1.191 harris41 13312:
13313: =item *
13314:
1.243 albertel 13315: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13316:
13317: =item *
13318:
1.1058 raeburn 13319: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13320: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13321:
13322: will update user information (firstname,middlename,lastname,generation,
13323: permanentemail), and if forceid is true, student/employee ID also.
13324: A user's institutional affiliation(s) can also be updated.
13325: User information fields will not be overwritten with empty entries
13326: unless the field is included in the $candelete array reference.
13327: This array is included when a single user is modified via "Manage Users",
13328: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13329:
13330: =item *
13331:
1.286 matthew 13332: modifystudent
13333:
1.957 raeburn 13334: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13335: The course id is resolved based on the current user's environment.
13336: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13337: associated with a course.
13338:
1.297 matthew 13339: This call is essentially a wrapper for lonnet::modifyuser and
13340: lonnet::modify_student_enrollment
1.286 matthew 13341:
13342: Inputs:
13343:
13344: =over 4
13345:
1.957 raeburn 13346: =item B<$udom> Student's loncapa domain
1.286 matthew 13347:
1.957 raeburn 13348: =item B<$uname> Student's loncapa login name
1.286 matthew 13349:
1.964 bisitz 13350: =item B<$uid> Student/Employee ID
1.286 matthew 13351:
1.957 raeburn 13352: =item B<$umode> Student's authentication mode
1.286 matthew 13353:
1.957 raeburn 13354: =item B<$upass> Student's password
1.286 matthew 13355:
1.957 raeburn 13356: =item B<$first> Student's first name
1.286 matthew 13357:
1.957 raeburn 13358: =item B<$middle> Student's middle name
1.286 matthew 13359:
1.957 raeburn 13360: =item B<$last> Student's last name
1.286 matthew 13361:
1.957 raeburn 13362: =item B<$gene> Student's generation
1.286 matthew 13363:
1.957 raeburn 13364: =item B<$usec> Student's section in course
1.286 matthew 13365:
13366: =item B<$end> Unix time of the roles expiration
13367:
13368: =item B<$start> Unix time of the roles start date
13369:
13370: =item B<$forceid> If defined, allow $uid to be changed
13371:
13372: =item B<$desiredhome> server to use as home server for student
13373:
1.957 raeburn 13374: =item B<$email> Student's permanent e-mail address
13375:
13376: =item B<$type> Type of enrollment (auto or manual)
13377:
1.963 raeburn 13378: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13379:
13380: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13381:
1.963 raeburn 13382: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13383:
1.963 raeburn 13384: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13385:
1.1172.2.19 raeburn 13386: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13387:
13388: =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 13389:
1.286 matthew 13390: =back
1.297 matthew 13391:
13392: =item *
13393:
13394: modify_student_enrollment
13395:
1.1172.2.31 raeburn 13396: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13397: 'role.request.course' must be defined for this function to proceed.
13398:
13399: Inputs:
13400:
13401: =over 4
13402:
1.1172.2.31 raeburn 13403: =item $udom, student's domain
1.297 matthew 13404:
1.1172.2.31 raeburn 13405: =item $uname, student's name
1.297 matthew 13406:
1.1172.2.31 raeburn 13407: =item $uid, student's user id
1.297 matthew 13408:
1.1172.2.31 raeburn 13409: =item $first, student's first name
1.297 matthew 13410:
13411: =item $middle
13412:
13413: =item $last
13414:
13415: =item $gene
13416:
13417: =item $usec
13418:
13419: =item $end
13420:
13421: =item $start
13422:
1.957 raeburn 13423: =item $type
13424:
13425: =item $locktype
13426:
13427: =item $cid
13428:
13429: =item $selfenroll
13430:
13431: =item $context
13432:
1.1172.2.19 raeburn 13433: =item $credits, number of credits student will earn from this class
13434:
1.1172.2.76 raeburn 13435: =item $instsec, institutional course section code for student
13436:
1.297 matthew 13437: =back
13438:
1.191 harris41 13439:
13440: =item *
13441:
1.243 albertel 13442: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13443: custom role; give a custom role to a user for the level given by URL. Specify
13444: name and domain of role author, and role name
1.191 harris41 13445:
13446: =item *
13447:
1.243 albertel 13448: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13449:
13450: =item *
13451:
1.243 albertel 13452: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13453:
13454: =back
13455:
13456: =head2 Course Infomation
13457:
13458: =over 4
1.191 harris41 13459:
13460: =item *
13461:
1.1118 foxr 13462: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13463: specified course id, including all environment settings for the
13464: course, the description of the course will be in the hash under the
13465: key 'description'
1.191 harris41 13466:
1.1118 foxr 13467: $options is an optional parameter that if supplied is a hash reference that controls
13468: what how this function works. It has the following key/values:
13469:
13470: =over 4
13471:
13472: =item freshen_cache
13473:
13474: If defined, and the environment cache for the course is valid, it is
13475: returned in the returned hash.
13476:
13477: =item one_time
13478:
13479: If defined, the last cache time is set to _now_
13480:
13481: =item user
13482:
13483: If defined, the supplied username is used instead of the current user.
13484:
13485:
13486: =back
13487:
1.191 harris41 13488: =item *
13489:
1.624 albertel 13490: resdata($name,$domain,$type,@which) : request for current parameter
13491: setting for a specific $type, where $type is either 'course' or 'user',
13492: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13493: answers for 10 minutes.
1.243 albertel 13494:
1.877 foxr 13495: =item *
13496:
13497: get_courseresdata($courseid, $domain) : dump the entire course resource
13498: data base, returning a hash that is keyed by the resource name and has
13499: values that are the resource value. I believe that the timestamps and
13500: versions are also returned.
13501:
1.1172.2.31 raeburn 13502: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13503: supplemental content area. This routine caches the number of files for
13504: 10 minutes.
13505:
1.243 albertel 13506: =back
13507:
13508: =head2 Course Modification
13509:
13510: =over 4
1.191 harris41 13511:
13512: =item *
13513:
1.243 albertel 13514: writecoursepref($courseid,%prefs) : write preferences (environment
13515: database) for a course
1.191 harris41 13516:
13517: =item *
13518:
1.1011 raeburn 13519: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13520:
13521: =item *
13522:
1.1038 raeburn 13523: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13524:
1.1167 droeschl 13525: =item *
13526:
13527: is_course($courseid), is_course($cdom, $cnum)
13528:
13529: Accepts either a combined $courseid (in the form of domain_courseid) or the
13530: two component version $cdom, $cnum. It checks if the specified course exists.
13531:
13532: Returns:
13533: undef if the course doesn't exist, otherwise
13534: in scalar context the combined courseid.
13535: in list context the two components of the course identifier, domain and
13536: courseid.
13537:
1.243 albertel 13538: =back
13539:
13540: =head2 Resource Subroutines
13541:
13542: =over 4
1.191 harris41 13543:
13544: =item *
13545:
1.243 albertel 13546: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13547:
13548: =item *
13549:
1.243 albertel 13550: repcopy($filename) : subscribes to the requested file, and attempts to
13551: replicate from the owning library server, Might return
1.607 raeburn 13552: 'unavailable', 'not_found', 'forbidden', 'ok', or
13553: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13554: resource. Expects the local filesystem pathname
13555: (/home/httpd/html/res/....)
13556:
13557: =back
13558:
13559: =head2 Resource Information
13560:
13561: =over 4
1.191 harris41 13562:
13563: =item *
13564:
1.1172.2.28 raeburn 13565: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13566: and returns the value of a variety of different possible values,
13567: $varname should be a request string, and the other parameters can be
13568: used to specify who and what one is asking about. Ordinarily, $cid
13569: does not need to be specified, as it is retrived from
13570: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13571: within lonuserstate::loadmap() when initializing a course, before
13572: $env{'request.course.id'} has been set, so it needs to be provided
13573: in that one case.
1.243 albertel 13574:
13575: Possible values for $varname are environment.lastname (or other item
13576: from the envirnment hash), user.name (or someother aspect about the
13577: user), resource.0.maxtries (or some other part and parameter of a
13578: resource)
1.204 albertel 13579:
13580: =item *
13581:
1.243 albertel 13582: directcondval($number) : get current value of a condition; reads from a state
13583: string
1.204 albertel 13584:
13585: =item *
13586:
1.243 albertel 13587: condval($condidx) : value of condition index based on state
1.204 albertel 13588:
13589: =item *
13590:
1.243 albertel 13591: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13592: resource's metadata, $what should be either a specific key, or either
13593: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13594: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13595:
13596: this function automatically caches all requests
1.191 harris41 13597:
13598: =item *
13599:
1.243 albertel 13600: metadata_query($query,$custom,$customshow) : make a metadata query against the
13601: network of library servers; returns file handle of where SQL and regex results
13602: will be stored for query
1.191 harris41 13603:
13604: =item *
13605:
1.1172.2.66 raeburn 13606: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13607: return symbolic list entry (all arguments optional).
13608:
13609: Args: filename is the filename (including path) for the file for which a symb
13610: is required; donotrecurse, if true will prevent calls to allowed() being made
13611: to check access status if more than one resource was found in the bighash
13612: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13613: a randompick); ignorecachednull, if true will prevent a symb of '' being
13614: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13615: cause possible symbs to be checked to determine if they are subject to content
13616: blocking, if so they will not be included as possible symbs; possibles is a
13617: ref to a hash, which, as a side effect, will be populated with all possible
13618: symbs (content blocking not tested).
13619:
1.243 albertel 13620: returns the data handle
1.191 harris41 13621:
13622: =item *
13623:
1.1172.2.17 raeburn 13624: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13625: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13626: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13627: on failure, user must be in a course, as it assumes the existence of
13628: the course initial hash, and uses $env('request.course.id'}. The third
13629: arg is an optional reference to a scalar. If this arg is passed in the
13630: call to symbverify, it will be set to 1 if the symb has been set to be
13631: encrypted; otherwise it will be null.
1.243 albertel 13632:
1.191 harris41 13633: =item *
13634:
1.243 albertel 13635: symbclean($symb) : removes versions numbers from a symb, returns the
13636: cleaned symb
1.191 harris41 13637:
13638: =item *
13639:
1.243 albertel 13640: is_on_map($uri) : checks if the $uri is somewhere on the current
13641: course map, user must be in a course for it to work.
1.191 harris41 13642:
13643: =item *
13644:
1.243 albertel 13645: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13646:
13647: =item *
13648:
1.243 albertel 13649: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13650: a random seed, all arguments are optional, if they aren't sent it uses the
13651: environment to derive them. Note: if symb isn't sent and it can't get one
13652: from &symbread it will use the current time as its return value
1.191 harris41 13653:
13654: =item *
13655:
1.243 albertel 13656: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13657: unfakeable, receipt
1.191 harris41 13658:
13659: =item *
13660:
1.620 albertel 13661: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13662:
13663: =item *
13664:
1.243 albertel 13665: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13666:
13667: =item *
13668:
1.243 albertel 13669: 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 13670:
13671: =item *
13672:
1.243 albertel 13673: 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 13674:
13675: =item *
13676:
1.243 albertel 13677: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13678:
13679: =item *
13680:
1.243 albertel 13681: devalidate($symb) : devalidate temporary spreadsheet calculations,
13682: forcing spreadsheet to reevaluate the resource scores next time.
13683:
1.1172.2.13 raeburn 13684: =item *
13685:
13686: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13687: when viewing in course context.
13688:
13689: input: six args -- filename (decluttered), course number, course domain,
13690: url, symb (if registered) and group (if this is a
13691: group item -- e.g., bulletin board, group page etc.).
13692:
13693: output: array of five scalars --
13694: $cfile -- url for file editing if editable on current server
13695: $home -- homeserver of resource (i.e., for author if published,
13696: or course if uploaded.).
13697: $switchserver -- 1 if server switch will be needed.
13698: $forceedit -- 1 if icon/link should be to go to edit mode
13699: $forceview -- 1 if icon/link should be to go to view mode
13700:
13701: =item *
13702:
13703: is_course_upload($file,$cnum,$cdom)
13704:
13705: Used in course context to determine if current file was uploaded to
13706: the course (i.e., would be found in /userfiles/docs on the course's
13707: homeserver.
13708:
13709: input: 3 args -- filename (decluttered), course number and course domain.
13710: output: boolean -- 1 if file was uploaded.
13711:
1.243 albertel 13712: =back
13713:
13714: =head2 Storing/Retreiving Data
13715:
13716: =over 4
1.191 harris41 13717:
13718: =item *
13719:
1.1172.2.64 raeburn 13720: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13721: permanently for this url; hashref needs to be given and should be a \%hashname;
13722: the remaining args aren't required and if they aren't passed or are '' they will
13723: be derived from the env (with the exception of $laststore, which is an
13724: optional arg used when a user's submission is stored in grading).
13725: $laststore is $version=$timestamp, where $version is the most recent version
13726: number retrieved for the corresponding $symb in the $namespace db file, and
13727: $timestamp is the timestamp for that transaction (UNIX time).
13728: $laststore is currently only passed when cstore() is called by
13729: structuretags::finalize_storage().
1.191 harris41 13730:
13731: =item *
13732:
1.1172.2.64 raeburn 13733: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13734: but uses critical subroutine
1.191 harris41 13735:
13736: =item *
13737:
1.243 albertel 13738: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13739: all args are optional
1.191 harris41 13740:
13741: =item *
13742:
1.717 albertel 13743: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13744: dumps the complete (or key matching regexp) namespace into a hash
13745: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13746: normally &store()ed into
13747:
13748: $range should be either an integer '100' (give me the first 100
13749: matching records)
13750: or be two integers sperated by a - with no spaces
13751: '30-50' (give me the 30th through the 50th matching
13752: records)
13753:
13754:
13755: =item *
13756:
1.1172.2.59 raeburn 13757: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13758: replaces a &store() version of data with a replacement set of data
13759: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13760: reference. If $tolog is true, the transaction is logged in the courselog
13761: with an action=PUTSTORE.
1.717 albertel 13762:
13763: =item *
13764:
1.243 albertel 13765: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13766: works very similar to store/cstore, but all data is stored in a
13767: temporary location and can be reset using tmpreset, $storehash should
13768: be a hash reference, returns nothing on success
1.191 harris41 13769:
13770: =item *
13771:
1.243 albertel 13772: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13773: similar to restore, but all data is stored in a temporary location and
13774: can be reset using tmpreset. Returns a hash of values on success,
13775: error string otherwise.
1.191 harris41 13776:
13777: =item *
13778:
1.243 albertel 13779: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13780: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13781:
13782: =item *
13783:
1.243 albertel 13784: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13785: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13786:
13787: =item *
13788:
1.243 albertel 13789: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13790: namesp ($udom and $uname are optional)
1.191 harris41 13791:
13792: =item *
13793:
1.702 albertel 13794: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13795: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13796: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13797:
1.702 albertel 13798: $range should be either an integer '100' (give me the first 100
13799: matching records)
13800: or be two integers sperated by a - with no spaces
13801: '30-50' (give me the 30th through the 50th matching
13802: records)
1.449 matthew 13803: =item *
13804:
13805: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13806: $store can be a scalar, an array reference, or if the amount to be
13807: incremented is > 1, a hash reference.
13808:
13809: ($udom and $uname are optional)
1.191 harris41 13810:
13811: =item *
13812:
1.243 albertel 13813: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13814: ($udom and $uname are optional)
1.191 harris41 13815:
13816: =item *
13817:
1.243 albertel 13818: cput($namespace,$storehash,$udom,$uname) : critical put
13819: ($udom and $uname are optional)
1.191 harris41 13820:
13821: =item *
13822:
1.748 albertel 13823: newput($namespace,$storehash,$udom,$uname) :
13824:
13825: Attempts to store the items in the $storehash, but only if they don't
13826: currently exist, if this succeeds you can be certain that you have
13827: successfully created a new key value pair in the $namespace db.
13828:
13829:
13830: Args:
13831: $namespace: name of database to store values to
13832: $storehash: hashref to store to the db
13833: $udom: (optional) domain of user containing the db
13834: $uname: (optional) name of user caontaining the db
13835:
13836: Returns:
13837: 'ok' -> succeeded in storing all keys of $storehash
13838: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13839: least <key> already existed in the db (other
13840: requested keys may also already exist)
1.967 bisitz 13841: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13842: 'con_lost' -> unable to contact request server
13843: 'refused' -> action was not allowed by remote machine
13844:
13845:
13846: =item *
13847:
1.243 albertel 13848: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13849: reference filled in from namesp (encrypts the return communication)
13850: ($udom and $uname are optional)
1.191 harris41 13851:
13852: =item *
13853:
1.243 albertel 13854: log($udom,$name,$home,$message) : write to permanent log for user; use
13855: critical subroutine
13856:
1.806 raeburn 13857: =item *
13858:
1.860 raeburn 13859: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13860: array reference filled in from namespace found in domain level on either
13861: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13862:
13863: =item *
13864:
1.860 raeburn 13865: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13866: domain level either on specified domain server ($uhome) or primary domain
13867: server ($udom and $uhome are optional)
1.806 raeburn 13868:
1.943 raeburn 13869: =item *
13870:
1.1172.2.35 raeburn 13871: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13872: for: authentication, language, quotas, timezone, date locale, and portal URL in
13873: the target domain.
13874:
13875: May also include additional key => value pairs for the following groups:
13876:
13877: =over
13878:
13879: =item
13880: disk quotas (MB allocated by default to portfolios and authoring spaces).
13881:
13882: =over
13883:
13884: =item defaultquota, authorquota
13885:
13886: =back
13887:
13888: =item
13889: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13890: portfolio for users).
13891:
13892: =over
13893:
13894: =item
13895: aboutme, blog, webdav, portfolio
13896:
13897: =back
13898:
13899: =item
13900: requestcourses: ability to request courses, and how requests are processed.
13901:
13902: =over
13903:
13904: =item
1.1172.2.37 raeburn 13905: official, unofficial, community, textbook
1.1172.2.35 raeburn 13906:
13907: =back
13908:
13909: =item
13910: inststatus: types of institutional affiliation, and order in which they are displayed.
13911:
13912: =over
13913:
13914: =item
1.1172.2.44 raeburn 13915: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13916:
13917: =back
13918:
13919: =item
13920: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13921: for course's uploaded content.
13922:
13923: =over
13924:
13925: =item
1.1172.2.68 raeburn 13926: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13927: communityquota, textbookquota
1.1172.2.35 raeburn 13928:
13929: =back
13930:
13931: =item
13932: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13933: on your servers.
13934:
13935: =over
13936:
13937: =item
13938: remotesessions, hostedsessions
13939:
13940: =back
13941:
13942: =back
13943:
13944: In cases where a domain coordinator has never used the "Set Domain Configuration"
13945: utility to create a configuration.db file on a domain's primary library server
13946: only the following domain defaults: auth_def, auth_arg_def, lang_def
13947: -- corresponding values are authentication type (internal, krb4, krb5,
13948: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13949: will be available. Values are retrieved from cache (if current), unless the
13950: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13951: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13952:
13953: Typical usage:
1.943 raeburn 13954:
1.1172.2.35 raeburn 13955: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13956:
1.243 albertel 13957: =back
13958:
13959: =head2 Network Status Functions
13960:
13961: =over 4
1.191 harris41 13962:
13963: =item *
13964:
1.1137 raeburn 13965: dirlist() : return directory list based on URI (first arg).
13966:
13967: Inputs: 1 required, 5 optional.
13968:
13969: =over
13970:
13971: =item
13972: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13973:
13974: =item
13975: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13976:
13977: =item
13978: $username - username of user/course to be listed. Extracted from $uri if absent.
13979:
13980: =item
13981: $getpropath - boolean: 1 if prepend path using &propath().
13982:
13983: =item
13984: $getuserdir - boolean: 1 if prepend path for "userfiles".
13985:
13986: =item
13987: $alternateRoot - path to prepend in place of path from $uri.
13988:
13989: =back
13990:
13991: Returns: Array of up to two items.
13992:
13993: =over
13994:
13995: a reference to an array of files/subdirectories
13996:
13997: =over
13998:
13999: Each element in the array of files/subdirectories is a & separated list of
14000: item name and the result of running stat on the item. If dirlist was requested
14001: for a file instead of a directory, the item name will be ''. For a directory
14002: listing, if the item is a metadata file, the element will end &N&M
14003: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14004: default copyright set (1).
14005:
14006: =back
14007:
14008: a scalar containing error condition (if encountered).
14009:
14010: =over
14011:
14012: =item
14013: no_host (no homeserver identified for $username:$domain).
14014:
14015: =item
14016: no_such_host (server contacted for listing not identified as valid host).
14017:
14018: =item
14019: con_lost (connection to remote server failed).
14020:
14021: =item
14022: refused (invalid $username:$domain received on lond side).
14023:
14024: =item
14025: no_such_dir (directory at specified path on lond side does not exist).
14026:
14027: =item
14028: empty (directory at specified path on lond side is empty).
14029:
14030: =over
14031:
14032: This is currently not encountered because the &ls3, &ls2,
14033: &ls (_handler) routines on the lond side do not filter out
14034: . and .. from a directory listing.
14035:
14036: =back
14037:
14038: =back
14039:
14040: =back
1.191 harris41 14041:
14042: =item *
14043:
1.243 albertel 14044: spareserver() : find server with least workload from spare.tab
14045:
1.986 foxr 14046:
14047: =item *
14048:
14049: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14050: if there is no corresponding loncapa host.
14051:
1.243 albertel 14052: =back
14053:
1.986 foxr 14054:
1.243 albertel 14055: =head2 Apache Request
14056:
14057: =over 4
1.191 harris41 14058:
14059: =item *
14060:
1.243 albertel 14061: ssi($url,%hash) : server side include, does a complete request cycle on url to
14062: localhost, posts hash
14063:
14064: =back
14065:
14066: =head2 Data to String to Data
14067:
14068: =over 4
1.191 harris41 14069:
14070: =item *
14071:
1.243 albertel 14072: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14073: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14074:
14075: =item *
14076:
1.243 albertel 14077: hashref2str($hashref) : convert a hashref into a string complete with
14078: escaping and '=' and '&' separators, supports elements that are
14079: arrayrefs and hashrefs
1.191 harris41 14080:
14081: =item *
14082:
1.243 albertel 14083: arrayref2str($arrayref) : convert an arrayref into a string complete
14084: with escaping and '&' separators, supports elements that are arrayrefs
14085: and hashrefs
1.191 harris41 14086:
14087: =item *
14088:
1.243 albertel 14089: str2hash($string) : convert string to hash using unescaping and
14090: splitting on '=' and '&', supports elements that are arrayrefs and
14091: hashrefs
1.191 harris41 14092:
14093: =item *
14094:
1.243 albertel 14095: str2array($string) : convert string to hash using unescaping and
14096: splitting on '&', supports elements that are arrayrefs and hashrefs
14097:
14098: =back
14099:
14100: =head2 Logging Routines
14101:
14102:
14103: These routines allow one to make log messages in the lonnet.log and
14104: lonnet.perm logfiles.
1.191 harris41 14105:
1.1119 foxr 14106: =over 4
14107:
1.191 harris41 14108: =item *
14109:
1.243 albertel 14110: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14111:
14112: =item *
14113:
1.243 albertel 14114: logthis() : append message to the normal lonnet.log file, it gets
14115: preiodically rolled over and deleted.
1.191 harris41 14116:
14117: =item *
14118:
1.243 albertel 14119: logperm() : append a permanent message to lonnet.perm.log, this log
14120: file never gets deleted by any automated portion of the system, only
14121: messages of critical importance should go in here.
14122:
1.1119 foxr 14123:
1.243 albertel 14124: =back
14125:
14126: =head2 General File Helper Routines
14127:
14128: =over 4
1.191 harris41 14129:
14130: =item *
14131:
1.481 raeburn 14132: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14133: (a) files in /uploaded
14134: (i) If a local copy of the file exists -
14135: compares modification date of local copy with last-modified date for
14136: definitive version stored on home server for course. If local copy is
14137: stale, requests a new version from the home server and stores it.
14138: If the original has been removed from the home server, then local copy
14139: is unlinked.
14140: (ii) If local copy does not exist -
14141: requests the file from the home server and stores it.
14142:
14143: If $caller is 'uploadrep':
14144: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14145: for request for files originally uploaded via DOCS.
14146: - returns 'ok' if fresh local copy now available, -1 otherwise.
14147:
14148: Otherwise:
14149: This indicates a call from the content generation phase of the request.
14150: - returns the entire contents of the file or -1.
14151:
14152: (b) files in /res
14153: - returns the entire contents of a file or -1;
14154: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14155:
1.712 albertel 14156:
14157: =item *
14158:
14159: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14160: reference
14161:
14162: returns either a stat() list of data about the file or an empty list
14163: if the file doesn't exist or couldn't find out about it (connection
14164: problems or user unknown)
14165:
1.191 harris41 14166: =item *
14167:
1.243 albertel 14168: filelocation($dir,$file) : returns file system location of a file
14169: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14170: directory that relative $file lookups are to looked in ($dir of /a/dir
14171: and a file of ../bob will become /a/bob)
1.191 harris41 14172:
14173: =item *
14174:
14175: hreflocation($dir,$file) : returns file system location or a URL; same as
14176: filelocation except for hrefs
14177:
14178: =item *
14179:
1.1172.2.49 raeburn 14180: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14181: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14182:
1.243 albertel 14183: =back
14184:
1.608 albertel 14185: =head2 Usererfile file routines (/uploaded*)
14186:
14187: =over 4
14188:
14189: =item *
14190:
14191: userfileupload(): main rotine for putting a file in a user or course's
14192: filespace, arguments are,
14193:
1.620 albertel 14194: formname - required - this is the name of the element in $env where the
1.608 albertel 14195: filename, and the contents of the file to create/modifed exist
1.620 albertel 14196: the filename is in $env{'form.'.$formname.'.filename'} and the
14197: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14198: context - if coursedoc, store the file in the course of the active role
14199: of the current user;
14200: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14201: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14202: subdir - required - subdirectory to put the file in under ../userfiles/
14203: if undefined, it will be placed in "unknown"
14204:
14205: (This routine calls clean_filename() to remove any dangerous
14206: characters from the filename, and then calls finuserfileupload() to
14207: complete the transaction)
14208:
14209: returns either the url of the uploaded file (/uploaded/....) if successful
14210: and /adm/notfound.html if unsuccessful
14211:
14212: =item *
14213:
14214: clean_filename(): routine for cleaing a filename up for storage in
14215: userfile space, argument is:
14216:
14217: filename - proposed filename
14218:
14219: returns: the new clean filename
14220:
14221: =item *
14222:
1.1090 raeburn 14223: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14224: userspace, probably shouldn't be called directly
14225:
14226: docuname: username or courseid of destination for the file
14227: docudom: domain of user/course of destination for the file
14228: formname: same as for userfileupload()
1.1090 raeburn 14229: fname: filename (including subdirectories) for the file
14230: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14231: allfiles: reference to hash used to store objects found by parser
14232: codebase: reference to hash used for codebases of java objects found by parser
14233: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14234: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14235: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14236: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14237: context: if 'overwrite', will move the uploaded file from its temporary location to
14238: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14239: mimetype: reference to scalar to accommodate mime type determined
14240: from File::MMagic if $parser = parse.
1.608 albertel 14241:
14242: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14243: and /adm/notfound.html if unsuccessful (or an error message if context
14244: was 'overwrite').
14245:
1.608 albertel 14246:
14247: =item *
14248:
14249: renameuserfile(): renames an existing userfile to a new name
14250:
14251: Args:
14252: docuname: username or courseid of destination for the file
14253: docudom: domain of user/course of destination for the file
14254: old: current file name (including any subdirs under userfiles)
14255: new: desired file name (including any subdirs under userfiles)
14256:
14257: =item *
14258:
14259: mkdiruserfile(): creates a directory is a userfiles dir
14260:
14261: Args:
14262: docuname: username or courseid of destination for the file
14263: docudom: domain of user/course of destination for the file
14264: dir: dir to create (including any subdirs under userfiles)
14265:
14266: =item *
14267:
14268: removeuserfile(): removes a file that exists in userfiles
14269:
14270: Args:
14271: docuname: username or courseid of destination for the file
14272: docudom: domain of user/course of destination for the file
14273: fname: filname to delete (including any subdirs under userfiles)
14274:
14275: =item *
14276:
14277: removeuploadedurl(): convience function for removeuserfile()
14278:
14279: Args:
14280: url: a full /uploaded/... url to delete
14281:
1.747 albertel 14282: =item *
14283:
14284: get_portfile_permissions():
14285: Args:
14286: domain: domain of user or course contain the portfolio files
14287: user: name of user or num of course contain the portfolio files
14288: Returns:
14289: hashref of a dump of the proper file_permissions.db
14290:
14291:
14292: =item *
14293:
14294: get_access_controls():
14295:
14296: Args:
14297: current_permissions: the hash ref returned from get_portfile_permissions()
14298: group: (optional) the group you want the files associated with
14299: file: (optional) the file you want access info on
14300:
14301: Returns:
1.749 raeburn 14302: a hash (keys are file names) of hashes containing
14303: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14304: values are XML containing access control settings (see below)
1.747 albertel 14305:
14306: Internal notes:
14307:
1.749 raeburn 14308: access controls are stored in file_permissions.db as key=value pairs.
14309: key -> path to file/file_name\0uniqueID:scope_end_start
14310: where scope -> public,guest,course,group,domains or users.
14311: end -> UNIX time for end of access (0 -> no end date)
14312: start -> UNIX time for start of access
14313:
14314: value -> XML description of access control
14315: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14316: <start></start>
14317: <end></end>
14318:
14319: <password></password> for scope type = guest
14320:
14321: <domain></domain> for scope type = course or group
14322: <number></number>
14323: <roles id="">
14324: <role></role>
14325: <access></access>
14326: <section></section>
14327: <group></group>
14328: </roles>
14329:
14330: <dom></dom> for scope type = domains
14331:
14332: <users> for scope type = users
14333: <user>
14334: <uname></uname>
14335: <udom></udom>
14336: </user>
14337: </users>
14338: </scope>
14339:
14340: Access data is also aggregated for each file in an additional key=value pair:
14341: key -> path to file/file_name\0accesscontrol
14342: value -> reference to hash
14343: hash contains key = value pairs
14344: where key = uniqueID:scope_end_start
14345: value = UNIX time record was last updated
14346:
14347: Used to improve speed of look-ups of access controls for each file.
14348:
14349: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14350:
1.1172.2.13 raeburn 14351: =item *
14352:
1.749 raeburn 14353: modify_access_controls():
14354:
14355: Modifies access controls for a portfolio file
14356: Args
14357: 1. file name
14358: 2. reference to hash of required changes,
14359: 3. domain
14360: 4. username
14361: where domain,username are the domain of the portfolio owner
14362: (either a user or a course)
14363:
14364: Returns:
14365: 1. result of additions or updates ('ok' or 'error', with error message).
14366: 2. result of deletions ('ok' or 'error', with error message).
14367: 3. reference to hash of any new or updated access controls.
14368: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14369: key = integer (inbound ID)
1.1172.2.13 raeburn 14370: value = uniqueID
14371:
14372: =item *
14373:
14374: get_timebased_id():
14375:
14376: Attempts to get a unique timestamp-based suffix for use with items added to a
14377: course via the Course Editor (e.g., folders, composite pages,
14378: group bulletin boards).
14379:
14380: Args: (first three required; six others optional)
14381:
14382: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14383: docssequence, or name of group
14384:
14385: 2. keyid (alphanumeric): name of temporary locking key in hash,
14386: e.g., num, boardids
14387:
14388: 3. namespace: name of gdbm file used to store suffixes already assigned;
14389: file will be named nohist_namespace.db
14390:
14391: 4. cdom: domain of course; default is current course domain from %env
14392:
14393: 5. cnum: course number; default is current course number from %env
14394:
14395: 6. idtype: set to concat if an additional digit is to be appended to the
14396: unix timestamp to form the suffix, if the plain timestamp is already
14397: in use. Default is to not do this, but simply increment the unix
14398: timestamp by 1 until a unique key is obtained.
14399:
14400: 7. who: holder of locking key; defaults to user:domain for user.
14401:
14402: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14403: retrying); default is 3.
14404:
14405: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14406:
14407: Returns:
14408:
14409: 1. suffix obtained (numeric)
14410:
14411: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14412:
14413: 3. error: contains (localized) error message if an error occurred.
14414:
1.747 albertel 14415:
1.608 albertel 14416: =back
14417:
1.243 albertel 14418: =head2 HTTP Helper Routines
14419:
14420: =over 4
14421:
1.191 harris41 14422: =item *
14423:
14424: escape() : unpack non-word characters into CGI-compatible hex codes
14425:
14426: =item *
14427:
14428: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14429:
1.243 albertel 14430: =back
14431:
14432: =head1 PRIVATE SUBROUTINES
14433:
14434: =head2 Underlying communication routines (Shouldn't call)
14435:
14436: =over 4
14437:
14438: =item *
14439:
14440: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14441:
14442: =item *
14443:
14444: reply() : uses subreply to send a message to remote machine, logs all failures
14445:
14446: =item *
14447:
14448: critical() : passes a critical message to another server; if cannot
14449: get through then place message in connection buffer directory and
14450: returns con_delayed, if incapable of saving message, returns
14451: con_failed
14452:
14453: =item *
14454:
14455: reconlonc() : tries to reconnect lonc client processes.
14456:
14457: =back
14458:
14459: =head2 Resource Access Logging
14460:
14461: =over 4
14462:
14463: =item *
14464:
14465: flushcourselogs() : flush (save) buffer logs and access logs
14466:
14467: =item *
14468:
14469: courselog($what) : save message for course in hash
14470:
14471: =item *
14472:
14473: courseacclog($what) : save message for course using &courselog(). Perform
14474: special processing for specific resource types (problems, exams, quizzes, etc).
14475:
1.191 harris41 14476: =item *
14477:
14478: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14479: as a PerlChildExitHandler
1.243 albertel 14480:
14481: =back
14482:
14483: =head2 Other
14484:
14485: =over 4
14486:
14487: =item *
14488:
14489: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14490:
14491: =back
14492:
14493: =cut
1.877 foxr 14494:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>