Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.36
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.36! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.35 2013/10/16 19:06:28 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36! raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( 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.550 foxr 105: my $max_connection_retries = 10; # 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.
373: sleep(1);
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.850 albertel 391: sleep(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: my $hostname = &hostname($lonid);
421: if ($lonid) {
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') {
467: &reconlonc("$perlvar{'lonSockDir'}/$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: }
484: sleep 2;
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') {
674: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
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'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
888: my ($try_server, $spare_server, $lowest_load) = @_;
889:
890: my $loadans = &reply('load', $try_server);
891: my $userloadans = &reply('userload',$try_server);
892:
893: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 894: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 895: }
896:
897: my $load;
898: if ($loadans =~ /\d/) {
899: if ($userloadans =~ /\d/) {
900: #both are numbers, pick the bigger one
901: $load = ($loadans > $userloadans) ? $loadans
902: : $userloadans;
1.411 albertel 903: } else {
1.784 albertel 904: $load = $loadans;
1.411 albertel 905: }
1.784 albertel 906: } else {
907: $load = $userloadans;
908: }
909:
910: if (($load =~ /\d/) && ($load < $lowest_load)) {
911: $spare_server = $try_server;
912: $lowest_load = $load;
1.370 albertel 913: }
1.784 albertel 914: return ($spare_server,$lowest_load);
1.202 matthew 915: }
1.914 albertel 916:
917: # --------------------------- ask offload servers if user already has a session
918: sub find_existing_session {
919: my ($udom,$uname) = @_;
1.1123 raeburn 920: my $spareshash = &this_host_spares($udom);
921: if (ref($spareshash) eq 'HASH') {
922: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
923: foreach my $try_server (@{ $spareshash->{'primary'} }) {
924: return $try_server if (&has_user_session($try_server, $udom, $uname));
925: }
926: }
927: if (ref($spareshash->{'default'}) eq 'ARRAY') {
928: foreach my $try_server (@{ $spareshash->{'default'} }) {
929: return $try_server if (&has_user_session($try_server, $udom, $uname));
930: }
931: }
1.914 albertel 932: }
933: return;
934: }
935:
936: # -------------------------------- ask if server already has a session for user
937: sub has_user_session {
938: my ($lonid,$udom,$uname) = @_;
939: my $result = &reply(join(':','userhassession',
940: map {&escape($_)} ($udom,$uname)),$lonid);
941: return 1 if ($result eq 'ok');
942:
943: return 0;
944: }
945:
1.1076 raeburn 946: # --------- determine least loaded server in a user's domain which allows login
947:
948: sub choose_server {
1.1115 raeburn 949: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 950: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 951: my %servers = &get_servers($udom);
1.1076 raeburn 952: my $lowest_load = 30000;
1.1151 raeburn 953: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 954: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 955: my $loginvia;
956: if ($checkloginvia) {
957: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 958: if ($loginvia) {
959: my ($server,$path) = split(/:/,$loginvia);
960: ($login_host, $lowest_load) =
961: &compare_server_load($server, $login_host, $lowest_load);
962: if ($login_host eq $server) {
963: $portal_path = $path;
1.1151 raeburn 964: $isredirect = 1;
1.1116 raeburn 965: }
966: } else {
967: ($login_host, $lowest_load) =
968: &compare_server_load($lonhost, $login_host, $lowest_load);
969: if ($login_host eq $lonhost) {
970: $portal_path = '';
1.1151 raeburn 971: $isredirect = '';
1.1116 raeburn 972: }
973: }
974: } else {
1.1076 raeburn 975: ($login_host, $lowest_load) =
1.1116 raeburn 976: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 977: }
978: }
979: if ($login_host ne '') {
1.1116 raeburn 980: $hostname = &hostname($login_host);
1.1076 raeburn 981: }
1.1151 raeburn 982: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 983: }
984:
1.202 matthew 985: # --------------------------------------------- Try to change a user's password
986:
987: sub changepass {
1.799 raeburn 988: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 989: $currentpass = &escape($currentpass);
990: $newpass = &escape($newpass);
1.1030 raeburn 991: my $lonhost = $perlvar{'lonHostID'};
992: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 993: $server);
994: if (! $answer) {
995: &logthis("No reply on password change request to $server ".
996: "by $uname in domain $udom.");
997: } elsif ($answer =~ "^ok") {
998: &logthis("$uname in $udom successfully changed their password ".
999: "on $server.");
1000: } elsif ($answer =~ "^pwchange_failure") {
1001: &logthis("$uname in $udom was unable to change their password ".
1002: "on $server. The action was blocked by either lcpasswd ".
1003: "or pwchange");
1004: } elsif ($answer =~ "^non_authorized") {
1005: &logthis("$uname in $udom did not get their password correct when ".
1006: "attempting to change it on $server.");
1007: } elsif ($answer =~ "^auth_mode_error") {
1008: &logthis("$uname in $udom attempted to change their password despite ".
1009: "not being locally or internally authenticated on $server.");
1010: } elsif ($answer =~ "^unknown_user") {
1011: &logthis("$uname in $udom attempted to change their password ".
1012: "on $server but were unable to because $server is not ".
1013: "their home server.");
1014: } elsif ($answer =~ "^refused") {
1015: &logthis("$server refused to change $uname in $udom password because ".
1016: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1017: } elsif ($answer =~ "invalid_client") {
1018: &logthis("$server refused to change $uname in $udom password because ".
1019: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1020: }
1021: return $answer;
1.1 albertel 1022: }
1023:
1.169 harris41 1024: # ----------------------- Try to determine user's current authentication scheme
1025:
1026: sub queryauthenticate {
1027: my ($uname,$udom)=@_;
1.456 albertel 1028: my $uhome=&homeserver($uname,$udom);
1029: if (!$uhome) {
1030: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1031: return 'no_host';
1032: }
1033: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1034: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1035: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1036: }
1.456 albertel 1037: return $answer;
1.169 harris41 1038: }
1039:
1.1 albertel 1040: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1041:
1.1 albertel 1042: sub authenticate {
1.1073 raeburn 1043: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1044: $upass=&escape($upass);
1045: $uname= &LONCAPA::clean_username($uname);
1.836 www 1046: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1047: my $newhome;
1.836 www 1048: if ((!$uhome) || ($uhome eq 'no_host')) {
1049: # Maybe the machine was offline and only re-appeared again recently?
1050: &reconlonc();
1051: # One more
1.952 raeburn 1052: $uhome=&homeserver($uname,$udom,1);
1053: if (($uhome eq 'no_host') && $checkdefauth) {
1054: if (defined(&domain($udom,'primary'))) {
1055: $newhome=&domain($udom,'primary');
1056: }
1057: if ($newhome ne '') {
1058: $uhome = $newhome;
1059: }
1060: }
1.836 www 1061: if ((!$uhome) || ($uhome eq 'no_host')) {
1062: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1063: return 'no_host';
1064: }
1.1 albertel 1065: }
1.1073 raeburn 1066: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1067: if ($answer eq 'authorized') {
1.952 raeburn 1068: if ($newhome) {
1069: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1070: return 'no_account_on_host';
1071: } else {
1072: &logthis("User $uname at $udom authorized by $uhome");
1073: return $uhome;
1074: }
1.471 albertel 1075: }
1076: if ($answer eq 'non_authorized') {
1077: &logthis("User $uname at $udom rejected by $uhome");
1078: return 'no_host';
1.9 www 1079: }
1.471 albertel 1080: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1081: return 'no_host';
1082: }
1083:
1.1073 raeburn 1084: sub can_host_session {
1.1074 raeburn 1085: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1086: my $canhost = 1;
1.1074 raeburn 1087: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1088: if (ref($remotesessions) eq 'HASH') {
1089: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1090: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1091: $canhost = 0;
1092: } else {
1093: $canhost = 1;
1094: }
1095: }
1096: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1097: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1098: $canhost = 1;
1099: } else {
1100: $canhost = 0;
1101: }
1102: }
1103: if ($canhost) {
1104: if ($remotesessions->{'version'} ne '') {
1105: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1106: if ($reqmajor ne '' && $reqminor ne '') {
1107: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1108: my $major = $1;
1109: my $minor = $2;
1110: if (($major < $reqmajor ) ||
1111: (($major == $reqmajor) && ($minor < $reqminor))) {
1112: $canhost = 0;
1113: }
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: }
1119: }
1120: }
1121: if ($canhost) {
1122: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1123: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1124: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1125: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1126: if (($uint_dom ne '') &&
1127: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1128: $canhost = 0;
1129: } else {
1130: $canhost = 1;
1131: }
1132: }
1133: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1134: if (($uint_dom ne '') &&
1135: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1136: $canhost = 1;
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: return $canhost;
1144: }
1145:
1.1083 raeburn 1146: sub spare_can_host {
1147: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1148: my $canhost=1;
1149: my @intdoms;
1150: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1151: if (ref($internet_names) eq 'ARRAY') {
1152: @intdoms = @{$internet_names};
1153: }
1154: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1155: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1156: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1157: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1158: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1159: $canhost = &can_host_session($udom,$try_server,$remoterev,
1160: $remotesessions,
1161: $defdomdefaults{'hostedsessions'});
1162: }
1163: return $canhost;
1164: }
1165:
1.1123 raeburn 1166: sub this_host_spares {
1167: my ($dom) = @_;
1.1126 raeburn 1168: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1169: my @hosts = ¤t_machine_ids();
1170: foreach my $lonhost (@hosts) {
1171: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1172: $dom_in_use = $dom;
1173: $lonhost_in_use = $lonhost;
1.1123 raeburn 1174: last;
1175: }
1176: }
1.1126 raeburn 1177: if ($dom_in_use ne '') {
1178: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1179: }
1180: if (ref($result) ne 'HASH') {
1181: $lonhost_in_use = $perlvar{'lonHostID'};
1182: $dom_in_use = &host_domain($lonhost_in_use);
1183: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1184: if (ref($result) ne 'HASH') {
1185: $result = \%spareid;
1186: }
1187: }
1188: return $result;
1189: }
1190:
1191: sub spares_for_offload {
1192: my ($dom_in_use,$lonhost_in_use) = @_;
1193: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1194: if (defined($cached)) {
1195: return $result;
1196: } else {
1.1126 raeburn 1197: my $cachetime = 60*60*24;
1198: my %domconfig =
1199: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1200: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1201: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1202: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1203: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1204: }
1205: }
1206: }
1207: }
1.1126 raeburn 1208: return;
1.1123 raeburn 1209: }
1210:
1.1129 raeburn 1211: sub get_lonbalancer_config {
1212: my ($servers) = @_;
1213: my ($currbalancer,$currtargets);
1214: if (ref($servers) eq 'HASH') {
1215: foreach my $server (keys(%{$servers})) {
1216: my %what = (
1217: spareid => 1,
1218: perlvar => 1,
1219: );
1220: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1221: if ($result eq 'ok') {
1222: if (ref($returnhash) eq 'HASH') {
1223: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1224: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1225: $currbalancer = $server;
1226: $currtargets = {};
1227: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1228: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1229: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1230: }
1231: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1232: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1233: }
1234: }
1235: last;
1236: }
1237: }
1238: }
1239: }
1240: }
1241: }
1242: return ($currbalancer,$currtargets);
1243: }
1244:
1245: sub check_loadbalancing {
1246: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1247: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1248: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1249: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1250: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1251: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1252: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1253: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1254: my $serverhomedom = &host_domain($lonhost);
1255:
1256: my $cachetime = 60*60*24;
1257:
1258: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1259: $dom_in_use = $udom;
1260: $homeintdom = 1;
1261: } else {
1262: $dom_in_use = $serverhomedom;
1263: }
1264: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1265: unless (defined($cached)) {
1266: my %domconfig =
1267: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1268: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1269: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1270: }
1271: }
1272: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1273: ($is_balancer,$currtargets,$currrules) =
1274: &check_balancer_result($result,@hosts);
1.1129 raeburn 1275: if ($is_balancer) {
1276: if (ref($currrules) eq 'HASH') {
1277: if ($homeintdom) {
1278: if ($uname ne '') {
1279: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1280: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1281: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1282: $rule_in_effect = $currrules->{'_LC_author'};
1283: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1284: $rule_in_effect = $currrules->{'_LC_adv'}
1285: }
1286: }
1287: if ($rule_in_effect eq '') {
1288: my %userenv = &userenvironment($udom,$uname,'inststatus');
1289: if ($userenv{'inststatus'} ne '') {
1290: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1291: my ($othertitle,$usertypes,$types) =
1292: &Apache::loncommon::sorted_inst_types($udom);
1293: if (ref($types) eq 'ARRAY') {
1294: foreach my $type (@{$types}) {
1295: if (grep(/^\Q$type\E$/,@statuses)) {
1296: if (exists($currrules->{$type})) {
1297: $rule_in_effect = $currrules->{$type};
1298: }
1299: }
1300: }
1301: }
1302: } else {
1303: if (exists($currrules->{'default'})) {
1304: $rule_in_effect = $currrules->{'default'};
1305: }
1306: }
1307: }
1308: } else {
1309: if (exists($currrules->{'default'})) {
1310: $rule_in_effect = $currrules->{'default'};
1311: }
1312: }
1313: } else {
1314: if ($currrules->{'_LC_external'} ne '') {
1315: $rule_in_effect = $currrules->{'_LC_external'};
1316: }
1317: }
1318: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1319: $uname,$udom);
1320: }
1321: }
1322: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1323: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1324: unless (defined($cached)) {
1325: my %domconfig =
1326: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1327: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1328: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1329: }
1330: }
1331: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1332: ($is_balancer,$currtargets,$currrules) =
1333: &check_balancer_result($result,@hosts);
1334: if ($is_balancer) {
1.1129 raeburn 1335: if (ref($currrules) eq 'HASH') {
1336: if ($currrules->{'_LC_internetdom'} ne '') {
1337: $rule_in_effect = $currrules->{'_LC_internetdom'};
1338: }
1339: }
1340: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1341: $uname,$udom);
1342: }
1343: } else {
1344: if ($perlvar{'lonBalancer'} eq 'yes') {
1345: $is_balancer = 1;
1346: $offloadto = &this_host_spares($dom_in_use);
1347: }
1348: }
1349: } else {
1350: if ($perlvar{'lonBalancer'} eq 'yes') {
1351: $is_balancer = 1;
1352: $offloadto = &this_host_spares($dom_in_use);
1353: }
1354: }
1.1172.2.5 raeburn 1355: if ($is_balancer) {
1356: my $lowest_load = 30000;
1357: if (ref($offloadto) eq 'HASH') {
1358: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1359: foreach my $try_server (@{$offloadto->{'primary'}}) {
1360: ($otherserver,$lowest_load) =
1361: &compare_server_load($try_server,$otherserver,$lowest_load);
1362: }
1.1129 raeburn 1363: }
1.1172.2.5 raeburn 1364: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1365:
1.1172.2.5 raeburn 1366: if (!$found_server) {
1367: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1368: foreach my $try_server (@{$offloadto->{'default'}}) {
1369: ($otherserver,$lowest_load) =
1370: &compare_server_load($try_server,$otherserver,$lowest_load);
1371: }
1372: }
1373: }
1374: } elsif (ref($offloadto) eq 'ARRAY') {
1375: if (@{$offloadto} == 1) {
1376: $otherserver = $offloadto->[0];
1377: } elsif (@{$offloadto} > 1) {
1378: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1379: ($otherserver,$lowest_load) =
1380: &compare_server_load($try_server,$otherserver,$lowest_load);
1381: }
1382: }
1383: }
1.1172.2.5 raeburn 1384: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1385: $is_balancer = 0;
1386: if ($uname ne '' && $udom ne '') {
1387: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1388:
1389: &appenv({'user.loadbalexempt' => $lonhost,
1390: 'user.loadbalcheck.time' => time});
1391: }
1.1129 raeburn 1392: }
1393: }
1394: }
1395: return ($is_balancer,$otherserver);
1396: }
1397:
1.1172.2.12 raeburn 1398: sub check_balancer_result {
1399: my ($result,@hosts) = @_;
1400: my ($is_balancer,$currtargets,$currrules);
1401: if (ref($result) eq 'HASH') {
1402: if ($result->{'lonhost'} ne '') {
1403: my $currbalancer = $result->{'lonhost'};
1404: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1405: $is_balancer = 1;
1406: $currtargets = $result->{'targets'};
1407: $currrules = $result->{'rules'};
1408: }
1409: } else {
1410: foreach my $key (keys(%{$result})) {
1411: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1412: (ref($result->{$key}) eq 'HASH')) {
1413: $is_balancer = 1;
1414: $currrules = $result->{$key}{'rules'};
1415: $currtargets = $result->{$key}{'targets'};
1416: last;
1417: }
1418: }
1419: }
1420: }
1421: return ($is_balancer,$currtargets,$currrules);
1422: }
1423:
1.1129 raeburn 1424: sub get_loadbalancer_targets {
1425: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1426: my $offloadto;
1.1172.2.4 raeburn 1427: if ($rule_in_effect eq 'none') {
1428: return [$perlvar{'lonHostID'}];
1429: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1430: $offloadto = $currtargets;
1431: } else {
1432: if ($rule_in_effect eq 'homeserver') {
1433: my $homeserver = &homeserver($uname,$udom);
1434: if ($homeserver ne 'no_host') {
1435: $offloadto = [$homeserver];
1436: }
1437: } elsif ($rule_in_effect eq 'externalbalancer') {
1438: my %domconfig =
1439: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1440: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1441: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1442: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1443: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1444: }
1445: }
1446: } else {
1.1172.2.7 raeburn 1447: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1448: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1449: if (&hostname($remotebalancer) ne '') {
1450: $offloadto = [$remotebalancer];
1451: }
1452: }
1453: } elsif (&hostname($rule_in_effect) ne '') {
1454: $offloadto = [$rule_in_effect];
1455: }
1456: }
1457: return $offloadto;
1458: }
1459:
1.1127 raeburn 1460: sub internet_dom_servers {
1461: my ($dom) = @_;
1462: my (%uniqservers,%servers);
1463: my $primaryserver = &hostname(&domain($dom,'primary'));
1464: my @machinedoms = &machine_domains($primaryserver);
1465: foreach my $mdom (@machinedoms) {
1466: my %currservers = %servers;
1467: my %server = &get_servers($mdom);
1468: %servers = (%currservers,%server);
1469: }
1470: my %by_hostname;
1471: foreach my $id (keys(%servers)) {
1472: push(@{$by_hostname{$servers{$id}}},$id);
1473: }
1474: foreach my $hostname (sort(keys(%by_hostname))) {
1475: if (@{$by_hostname{$hostname}} > 1) {
1476: my $match = 0;
1477: foreach my $id (@{$by_hostname{$hostname}}) {
1478: if (&host_domain($id) eq $dom) {
1479: $uniqservers{$id} = $hostname;
1480: $match = 1;
1481: }
1482: }
1483: unless ($match) {
1484: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1485: }
1486: } else {
1487: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1488: }
1489: }
1490: return %uniqservers;
1491: }
1492:
1.1 albertel 1493: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1494:
1.599 albertel 1495: my %homecache;
1.1 albertel 1496: sub homeserver {
1.230 stredwic 1497: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1498: my $index="$uname:$udom";
1.426 albertel 1499:
1.599 albertel 1500: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1501:
1502: my %servers = &get_servers($udom,'library');
1503: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1504: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1505: exists($badServerCache{$tryserver}));
1.841 albertel 1506:
1507: my $answer=reply("home:$udom:$uname",$tryserver);
1508: if ($answer eq 'found') {
1509: delete($badServerCache{$tryserver});
1510: return $homecache{$index}=$tryserver;
1511: } elsif ($answer eq 'no_host') {
1512: $badServerCache{$tryserver}=1;
1513: }
1.1 albertel 1514: }
1515: return 'no_host';
1.70 www 1516: }
1517:
1518: # ------------------------------------- Find the usernames behind a list of IDs
1519:
1520: sub idget {
1521: my ($udom,@ids)=@_;
1522: my %returnhash=();
1523:
1.841 albertel 1524: my %servers = &get_servers($udom,'library');
1525: foreach my $tryserver (keys(%servers)) {
1526: my $idlist=join('&',@ids);
1527: $idlist=~tr/A-Z/a-z/;
1528: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1529: my @answer=();
1530: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1531: @answer=split(/\&/,$reply);
1532: } ;
1533: my $i;
1534: for ($i=0;$i<=$#ids;$i++) {
1535: if ($answer[$i]) {
1536: $returnhash{$ids[$i]}=$answer[$i];
1537: }
1538: }
1539: }
1.70 www 1540: return %returnhash;
1541: }
1542:
1543: # ------------------------------------- Find the IDs behind a list of usernames
1544:
1545: sub idrget {
1546: my ($udom,@unames)=@_;
1547: my %returnhash=();
1.800 albertel 1548: foreach my $uname (@unames) {
1549: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1550: }
1.70 www 1551: return %returnhash;
1552: }
1553:
1554: # ------------------------------- Store away a list of names and associated IDs
1555:
1556: sub idput {
1557: my ($udom,%ids)=@_;
1558: my %servers=();
1.800 albertel 1559: foreach my $uname (keys(%ids)) {
1560: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1561: my $uhom=&homeserver($uname,$udom);
1.70 www 1562: if ($uhom ne 'no_host') {
1.800 albertel 1563: my $id=&escape($ids{$uname});
1.70 www 1564: $id=~tr/A-Z/a-z/;
1.800 albertel 1565: my $esc_unam=&escape($uname);
1.70 www 1566: if ($servers{$uhom}) {
1.800 albertel 1567: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1568: } else {
1.800 albertel 1569: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1570: }
1571: }
1.191 harris41 1572: }
1.800 albertel 1573: foreach my $server (keys(%servers)) {
1574: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1575: }
1.344 www 1576: }
1577:
1.1172.2.30 raeburn 1578: # ---------------------------------------- Delete unwanted IDs from ids.db file
1579:
1580: sub iddel {
1581: my ($udom,$idshashref,$uhome)=@_;
1582: my %result=();
1583: unless (ref($idshashref) eq 'HASH') {
1584: return %result;
1585: }
1586: my %servers=();
1587: while (my ($id,$uname) = each(%{$idshashref})) {
1588: my $uhom;
1589: if ($uhome) {
1590: $uhom = $uhome;
1591: } else {
1592: $uhom=&homeserver($uname,$udom);
1593: }
1594: if ($uhom ne 'no_host') {
1595: if ($servers{$uhom}) {
1596: $servers{$uhom}.='&'.&escape($id);
1597: } else {
1598: $servers{$uhom}=&escape($id);
1599: }
1600: }
1601: }
1602: foreach my $server (keys(%servers)) {
1603: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1604: }
1605: return %result;
1606: }
1607:
1.1023 raeburn 1608: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1609: sub dump_dom {
1.1165 droeschl 1610: my ($namespace, $udom, $regexp) = @_;
1611:
1612: $udom ||= $env{'user.domain'};
1613:
1614: return () unless $udom;
1615:
1616: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1617: }
1618:
1.1023 raeburn 1619: # ------------------------------------------ get items from domain db files
1.806 raeburn 1620:
1621: sub get_dom {
1.860 raeburn 1622: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1623: my $items='';
1624: foreach my $item (@$storearr) {
1625: $items.=&escape($item).'&';
1626: }
1627: $items=~s/\&$//;
1.860 raeburn 1628: if (!$udom) {
1629: $udom=$env{'user.domain'};
1630: if (defined(&domain($udom,'primary'))) {
1631: $uhome=&domain($udom,'primary');
1632: } else {
1.874 albertel 1633: undef($uhome);
1.860 raeburn 1634: }
1635: } else {
1636: if (!$uhome) {
1637: if (defined(&domain($udom,'primary'))) {
1638: $uhome=&domain($udom,'primary');
1639: }
1640: }
1641: }
1642: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1643: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1644: my %returnhash;
1.875 albertel 1645: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1646: return %returnhash;
1647: }
1.806 raeburn 1648: my @pairs=split(/\&/,$rep);
1649: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1650: return @pairs;
1651: }
1652: my $i=0;
1653: foreach my $item (@$storearr) {
1654: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1655: $i++;
1656: }
1657: return %returnhash;
1658: } else {
1.880 banghart 1659: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1660: }
1661: }
1662:
1663: # -------------------------------------------- put items in domain db files
1664:
1665: sub put_dom {
1.860 raeburn 1666: my ($namespace,$storehash,$udom,$uhome)=@_;
1667: if (!$udom) {
1668: $udom=$env{'user.domain'};
1669: if (defined(&domain($udom,'primary'))) {
1670: $uhome=&domain($udom,'primary');
1671: } else {
1.874 albertel 1672: undef($uhome);
1.860 raeburn 1673: }
1674: } else {
1675: if (!$uhome) {
1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: }
1679: }
1680: }
1681: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1682: my $items='';
1683: foreach my $item (keys(%$storehash)) {
1684: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1685: }
1686: $items=~s/\&$//;
1687: return &reply("putdom:$udom:$namespace:$items",$uhome);
1688: } else {
1.860 raeburn 1689: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1690: }
1691: }
1692:
1.1023 raeburn 1693: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1694: sub newput_dom {
1.1023 raeburn 1695: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1696: my $result;
1697: if (!$udom) {
1698: $udom=$env{'user.domain'};
1699: }
1.1023 raeburn 1700: if ($udom) {
1701: my $uname = &get_domainconfiguser($udom);
1702: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1703: }
1704: return $result;
1705: }
1706:
1.1023 raeburn 1707: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1708: sub del_dom {
1.1023 raeburn 1709: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1710: if (ref($storearr) eq 'ARRAY') {
1711: if (!$udom) {
1712: $udom=$env{'user.domain'};
1713: }
1.1023 raeburn 1714: if ($udom) {
1715: my $uname = &get_domainconfiguser($udom);
1716: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1717: }
1718: }
1719: }
1720:
1.1023 raeburn 1721: # ----------------------------------construct domainconfig user for a domain
1722: sub get_domainconfiguser {
1723: my ($udom) = @_;
1724: return $udom.'-domainconfig';
1725: }
1726:
1.837 raeburn 1727: sub retrieve_inst_usertypes {
1728: my ($udom) = @_;
1729: my (%returnhash,@order);
1.989 raeburn 1730: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1731: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1732: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1733: %returnhash = %{$domdefs{'inststatustypes'}};
1734: @order = @{$domdefs{'inststatusorder'}};
1735: } else {
1736: if (defined(&domain($udom,'primary'))) {
1737: my $uhome=&domain($udom,'primary');
1738: my $rep=&reply("inst_usertypes:$udom",$uhome);
1739: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1740: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1741: return (\%returnhash,\@order);
1742: }
1743: my ($hashitems,$orderitems) = split(/:/,$rep);
1744: my @pairs=split(/\&/,$hashitems);
1745: foreach my $item (@pairs) {
1746: my ($key,$value)=split(/=/,$item,2);
1747: $key = &unescape($key);
1748: next if ($key =~ /^error: 2 /);
1749: $returnhash{$key}=&thaw_unescape($value);
1750: }
1751: my @esc_order = split(/\&/,$orderitems);
1752: foreach my $item (@esc_order) {
1753: push(@order,&unescape($item));
1754: }
1755: } else {
1756: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1757: }
1758: }
1759: return (\%returnhash,\@order);
1760: }
1761:
1.868 raeburn 1762: sub is_domainimage {
1763: my ($url) = @_;
1764: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1765: if (&domain($1) ne '') {
1766: return '1';
1767: }
1768: }
1769: return;
1770: }
1771:
1.899 raeburn 1772: sub inst_directory_query {
1773: my ($srch) = @_;
1774: my $udom = $srch->{'srchdomain'};
1775: my %results;
1776: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1777: my $outcome;
1.899 raeburn 1778: if ($homeserver ne '') {
1.904 albertel 1779: my $queryid=&reply("querysend:instdirsearch:".
1780: &escape($srch->{'srchby'}).':'.
1781: &escape($srch->{'srchterm'}).':'.
1782: &escape($srch->{'srchtype'}),$homeserver);
1783: my $host=&hostname($homeserver);
1784: if ($queryid !~/^\Q$host\E\_/) {
1785: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1786: return;
1787: }
1788: my $response = &get_query_reply($queryid);
1789: my $maxtries = 5;
1790: my $tries = 1;
1791: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1792: $response = &get_query_reply($queryid);
1793: $tries ++;
1794: }
1795:
1796: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1797: if ($response eq 'unavailable') {
1798: $outcome = $response;
1799: } else {
1800: $outcome = 'ok';
1801: my @matches = split(/\n/,$response);
1802: foreach my $match (@matches) {
1803: my ($key,$value) = split(/=/,$match);
1804: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1805: }
1.899 raeburn 1806: }
1807: }
1808: }
1.909 raeburn 1809: return ($outcome,%results);
1.899 raeburn 1810: }
1811:
1812: sub usersearch {
1813: my ($srch) = @_;
1814: my $dom = $srch->{'srchdomain'};
1815: my %results;
1816: my %libserv = &all_library();
1817: my $query = 'usersearch';
1818: foreach my $tryserver (keys(%libserv)) {
1819: if (&host_domain($tryserver) eq $dom) {
1820: my $host=&hostname($tryserver);
1821: my $queryid=
1.911 raeburn 1822: &reply("querysend:".&escape($query).':'.
1823: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1824: &escape($srch->{'srchtype'}).':'.
1825: &escape($srch->{'srchterm'}),$tryserver);
1826: if ($queryid !~/^\Q$host\E\_/) {
1827: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1828: next;
1.899 raeburn 1829: }
1830: my $reply = &get_query_reply($queryid);
1831: my $maxtries = 1;
1832: my $tries = 1;
1833: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1834: $reply = &get_query_reply($queryid);
1835: $tries ++;
1836: }
1837: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1838: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1839: } else {
1.911 raeburn 1840: my @matches;
1841: if ($reply =~ /\n/) {
1842: @matches = split(/\n/,$reply);
1843: } else {
1844: @matches = split(/\&/,$reply);
1845: }
1.899 raeburn 1846: foreach my $match (@matches) {
1847: my ($uname,$udom,%userhash);
1.911 raeburn 1848: foreach my $entry (split(/:/,$match)) {
1849: my ($key,$value) =
1850: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1851: $userhash{$key} = $value;
1852: if ($key eq 'username') {
1853: $uname = $value;
1854: } elsif ($key eq 'domain') {
1855: $udom = $value;
1.911 raeburn 1856: }
1.899 raeburn 1857: }
1858: $results{$uname.':'.$udom} = \%userhash;
1859: }
1860: }
1861: }
1862: }
1863: return %results;
1864: }
1865:
1.912 raeburn 1866: sub get_instuser {
1867: my ($udom,$uname,$id) = @_;
1868: my $homeserver = &domain($udom,'primary');
1869: my ($outcome,%results);
1870: if ($homeserver ne '') {
1871: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1872: &escape($id).':'.&escape($udom),$homeserver);
1873: my $host=&hostname($homeserver);
1874: if ($queryid !~/^\Q$host\E\_/) {
1875: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1876: return;
1877: }
1878: my $response = &get_query_reply($queryid);
1879: my $maxtries = 5;
1880: my $tries = 1;
1881: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1882: $response = &get_query_reply($queryid);
1883: $tries ++;
1884: }
1885: if (!&error($response) && $response ne 'refused') {
1886: if ($response eq 'unavailable') {
1887: $outcome = $response;
1888: } else {
1889: $outcome = 'ok';
1890: my @matches = split(/\n/,$response);
1891: foreach my $match (@matches) {
1892: my ($key,$value) = split(/=/,$match);
1893: $results{&unescape($key)} = &thaw_unescape($value);
1894: }
1895: }
1896: }
1897: }
1898: my %userinfo;
1899: if (ref($results{$uname}) eq 'HASH') {
1900: %userinfo = %{$results{$uname}};
1901: }
1902: return ($outcome,%userinfo);
1903: }
1904:
1905: sub inst_rulecheck {
1.923 raeburn 1906: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1907: my %returnhash;
1908: if ($udom ne '') {
1909: if (ref($rules) eq 'ARRAY') {
1910: @{$rules} = map {&escape($_);} (@{$rules});
1911: my $rulestr = join(':',@{$rules});
1912: my $homeserver=&domain($udom,'primary');
1913: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1914: my $response;
1915: if ($item eq 'username') {
1916: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1917: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1918: $homeserver));
1.923 raeburn 1919: } elsif ($item eq 'id') {
1920: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1921: ':'.&escape($id).':'.$rulestr,
1922: $homeserver));
1.945 raeburn 1923: } elsif ($item eq 'selfcreate') {
1924: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1925: &escape($udom).':'.&escape($uname).
1926: ':'.$rulestr,$homeserver));
1.923 raeburn 1927: }
1.912 raeburn 1928: if ($response ne 'refused') {
1929: my @pairs=split(/\&/,$response);
1930: foreach my $item (@pairs) {
1931: my ($key,$value)=split(/=/,$item,2);
1932: $key = &unescape($key);
1933: next if ($key =~ /^error: 2 /);
1934: $returnhash{$key}=&thaw_unescape($value);
1935: }
1936: }
1937: }
1938: }
1939: }
1940: return %returnhash;
1941: }
1942:
1943: sub inst_userrules {
1.923 raeburn 1944: my ($udom,$check) = @_;
1.912 raeburn 1945: my (%ruleshash,@ruleorder);
1946: if ($udom ne '') {
1947: my $homeserver=&domain($udom,'primary');
1948: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1949: my $response;
1950: if ($check eq 'id') {
1951: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1952: $homeserver);
1.943 raeburn 1953: } elsif ($check eq 'email') {
1954: $response=&reply('instemailrules:'.&escape($udom),
1955: $homeserver);
1.923 raeburn 1956: } else {
1957: $response=&reply('instuserrules:'.&escape($udom),
1958: $homeserver);
1959: }
1.912 raeburn 1960: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1961: ($response ne 'unknown_cmd') &&
1.912 raeburn 1962: ($response ne 'no_such_host')) {
1963: my ($hashitems,$orderitems) = split(/:/,$response);
1964: my @pairs=split(/\&/,$hashitems);
1965: foreach my $item (@pairs) {
1966: my ($key,$value)=split(/=/,$item,2);
1967: $key = &unescape($key);
1968: next if ($key =~ /^error: 2 /);
1969: $ruleshash{$key}=&thaw_unescape($value);
1970: }
1971: my @esc_order = split(/\&/,$orderitems);
1972: foreach my $item (@esc_order) {
1973: push(@ruleorder,&unescape($item));
1974: }
1975: }
1976: }
1977: }
1978: return (\%ruleshash,\@ruleorder);
1979: }
1980:
1.976 raeburn 1981: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1982:
1983: sub get_domain_defaults {
1.1172.2.35 raeburn 1984: my ($domain,$ignore_cache) = @_;
1985: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1986: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 1987: unless ($ignore_cache) {
1988: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1989: if (defined($cached)) {
1990: if (ref($result) eq 'HASH') {
1991: return %{$result};
1992: }
1.943 raeburn 1993: }
1994: }
1995: my %domdefaults;
1996: my %domconfig =
1.989 raeburn 1997: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1998: 'requestcourses','inststatus',
1.1172.2.9 raeburn 1999: 'coursedefaults','usersessions',
2000: 'requestauthor'],$domain);
1.943 raeburn 2001: if (ref($domconfig{'defaults'}) eq 'HASH') {
2002: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2003: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2004: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2005: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2006: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2007: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2008: } else {
2009: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2010: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2011: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2012: }
1.976 raeburn 2013: if (ref($domconfig{'quotas'}) eq 'HASH') {
2014: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2015: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2016: } else {
2017: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2018: }
1.1172.2.6 raeburn 2019: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2020: foreach my $item (@usertools) {
2021: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2022: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2023: }
2024: }
1.1172.2.29 raeburn 2025: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2026: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2027: }
1.976 raeburn 2028: }
1.985 raeburn 2029: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 2030: foreach my $item ('official','unofficial','community') {
1.985 raeburn 2031: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2032: }
2033: }
1.1172.2.9 raeburn 2034: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2035: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2036: }
1.989 raeburn 2037: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2038: foreach my $item ('inststatustypes','inststatusorder') {
2039: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2040: }
2041: }
1.1047 raeburn 2042: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19 raeburn 2043: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2044: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2045: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047 raeburn 2046: }
1.1172.2.30 raeburn 2047: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2048: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2049: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2050: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2051: }
1.1047 raeburn 2052: }
1.1073 raeburn 2053: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2054: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2055: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2056: }
2057: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2058: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2059: }
2060: }
1.1172.2.23 raeburn 2061: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2062: return %domdefaults;
2063: }
2064:
1.344 www 2065: # --------------------------------------------------- Assign a key to a student
2066:
2067: sub assign_access_key {
1.364 www 2068: #
2069: # a valid key looks like uname:udom#comments
2070: # comments are being appended
2071: #
1.498 www 2072: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2073: $kdom=
1.620 albertel 2074: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2075: $knum=
1.620 albertel 2076: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2077: $cdom=
1.620 albertel 2078: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2079: $cnum=
1.620 albertel 2080: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2081: $udom=$env{'user.name'} unless (defined($udom));
2082: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2083: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2084: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2085: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2086: # assigned to this person
2087: # - this should not happen,
1.345 www 2088: # unless something went wrong
2089: # the first time around
2090: # ready to assign
1.364 www 2091: $logentry=$1.'; '.$logentry;
1.496 www 2092: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2093: $kdom,$knum) eq 'ok') {
1.345 www 2094: # key now belongs to user
1.346 www 2095: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2096: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2097: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2098: return 'ok';
2099: } else {
2100: return
2101: 'error: Count not permanently assign key, will need to be re-entered later.';
2102: }
2103: } else {
2104: return 'error: Could not assign key, try again later.';
2105: }
1.364 www 2106: } elsif (!$existing{$ckey}) {
1.345 www 2107: # the key does not exist
2108: return 'error: The key does not exist';
2109: } else {
2110: # the key is somebody else's
2111: return 'error: The key is already in use';
2112: }
1.344 www 2113: }
2114:
1.364 www 2115: # ------------------------------------------ put an additional comment on a key
2116:
2117: sub comment_access_key {
2118: #
2119: # a valid key looks like uname:udom#comments
2120: # comments are being appended
2121: #
2122: my ($ckey,$cdom,$cnum,$logentry)=@_;
2123: $cdom=
1.620 albertel 2124: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2125: $cnum=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2127: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2128: if ($existing{$ckey}) {
2129: $existing{$ckey}.='; '.$logentry;
2130: # ready to assign
1.367 www 2131: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2132: $cdom,$cnum) eq 'ok') {
2133: return 'ok';
2134: } else {
2135: return 'error: Count not store comment.';
2136: }
2137: } else {
2138: # the key does not exist
2139: return 'error: The key does not exist';
2140: }
2141: }
2142:
1.344 www 2143: # ------------------------------------------------------ Generate a set of keys
2144:
2145: sub generate_access_keys {
1.364 www 2146: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2147: $cdom=
1.620 albertel 2148: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2149: $cnum=
1.620 albertel 2150: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2151: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2152: unless (($cdom) && ($cnum)) { return 0; }
2153: if ($number>10000) { return 0; }
2154: sleep(2); # make sure don't get same seed twice
2155: srand(time()^($$+($$<<15))); # from "Programming Perl"
2156: my $total=0;
2157: for (my $i=1;$i<=$number;$i++) {
2158: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2159: sprintf("%lx",int(100000*rand)).'-'.
2160: sprintf("%lx",int(100000*rand));
2161: $newkey=~s/1/g/g; # folks mix up 1 and l
2162: $newkey=~s/0/h/g; # and also 0 and O
2163: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2164: if ($existing{$newkey}) {
2165: $i--;
2166: } else {
1.364 www 2167: if (&put('accesskeys',
2168: { $newkey => '# generated '.localtime().
1.620 albertel 2169: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2170: '; '.$logentry },
2171: $cdom,$cnum) eq 'ok') {
1.344 www 2172: $total++;
2173: }
2174: }
2175: }
1.620 albertel 2176: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2177: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2178: return $total;
2179: }
2180:
2181: # ------------------------------------------------------- Validate an accesskey
2182:
2183: sub validate_access_key {
2184: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2185: $cdom=
1.620 albertel 2186: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2187: $cnum=
1.620 albertel 2188: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2189: $udom=$env{'user.domain'} unless (defined($udom));
2190: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2191: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2192: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2193: }
2194:
2195: # ------------------------------------- Find the section of student in a course
1.652 albertel 2196: sub devalidate_getsection_cache {
2197: my ($udom,$unam,$courseid)=@_;
2198: my $hashid="$udom:$unam:$courseid";
2199: &devalidate_cache_new('getsection',$hashid);
2200: }
1.298 matthew 2201:
1.815 albertel 2202: sub courseid_to_courseurl {
2203: my ($courseid) = @_;
2204: #already url style courseid
2205: return $courseid if ($courseid =~ m{^/});
2206:
2207: if (exists($env{'course.'.$courseid.'.num'})) {
2208: my $cnum = $env{'course.'.$courseid.'.num'};
2209: my $cdom = $env{'course.'.$courseid.'.domain'};
2210: return "/$cdom/$cnum";
2211: }
2212:
2213: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2214: if (exists($courseinfo{'num'})) {
2215: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2216: }
2217:
2218: return undef;
2219: }
2220:
1.298 matthew 2221: sub getsection {
2222: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2223: my $cachetime=1800;
1.551 albertel 2224:
2225: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2226: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2227: if (defined($cached)) { return $result; }
2228:
1.298 matthew 2229: my %Pending;
2230: my %Expired;
2231: #
2232: # Each role can either have not started yet (pending), be active,
2233: # or have expired.
2234: #
2235: # If there is an active role, we are done.
2236: #
2237: # If there is more than one role which has not started yet,
2238: # choose the one which will start sooner
2239: # If there is one role which has not started yet, return it.
2240: #
2241: # If there is more than one expired role, choose the one which ended last.
2242: # If there is a role which has expired, return it.
2243: #
1.815 albertel 2244: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2245: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2246: foreach my $key (keys(%roleshash)) {
1.479 albertel 2247: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2248: my $section=$1;
2249: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2250: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2251: my $now=time;
1.548 albertel 2252: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2253: $Expired{$end}=$section;
2254: next;
2255: }
1.548 albertel 2256: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2257: $Pending{$start}=$section;
2258: next;
2259: }
1.599 albertel 2260: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2261: }
2262: #
2263: # Presumedly there will be few matching roles from the above
2264: # loop and the sorting time will be negligible.
2265: if (scalar(keys(%Pending))) {
2266: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2267: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2268: }
2269: if (scalar(keys(%Expired))) {
2270: my @sorted = sort {$a <=> $b} keys(%Expired);
2271: my $time = pop(@sorted);
1.599 albertel 2272: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2273: }
1.599 albertel 2274: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2275: }
1.70 www 2276:
1.599 albertel 2277: sub save_cache {
2278: &purge_remembered();
1.722 albertel 2279: #&Apache::loncommon::validate_page();
1.620 albertel 2280: undef(%env);
1.780 albertel 2281: undef($env_loaded);
1.599 albertel 2282: }
1.452 albertel 2283:
1.599 albertel 2284: my $to_remember=-1;
2285: my %remembered;
2286: my %accessed;
2287: my $kicks=0;
2288: my $hits=0;
1.849 albertel 2289: sub make_key {
2290: my ($name,$id) = @_;
1.872 albertel 2291: if (length($id) > 65
2292: && length(&escape($id)) > 200) {
2293: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2294: }
1.849 albertel 2295: return &escape($name.':'.$id);
2296: }
2297:
1.599 albertel 2298: sub devalidate_cache_new {
2299: my ($name,$id,$debug) = @_;
2300: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2301: $id=&make_key($name,$id);
1.599 albertel 2302: $memcache->delete($id);
2303: delete($remembered{$id});
2304: delete($accessed{$id});
2305: }
2306:
2307: sub is_cached_new {
2308: my ($name,$id,$debug) = @_;
1.849 albertel 2309: $id=&make_key($name,$id);
1.599 albertel 2310: if (exists($remembered{$id})) {
1.1133 foxr 2311: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2312: $accessed{$id}=[&gettimeofday()];
2313: $hits++;
2314: return ($remembered{$id},1);
2315: }
2316: my $value = $memcache->get($id);
2317: if (!(defined($value))) {
2318: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2319: return (undef,undef);
1.416 albertel 2320: }
1.599 albertel 2321: if ($value eq '__undef__') {
2322: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2323: $value=undef;
2324: }
2325: &make_room($id,$value,$debug);
2326: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2327: return ($value,1);
2328: }
2329:
2330: sub do_cache_new {
2331: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2332: $id=&make_key($name,$id);
1.599 albertel 2333: my $setvalue=$value;
2334: if (!defined($setvalue)) {
2335: $setvalue='__undef__';
2336: }
1.623 albertel 2337: if (!defined($time) ) {
2338: $time=600;
2339: }
1.599 albertel 2340: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2341: my $result = $memcache->set($id,$setvalue,$time);
2342: if (! $result) {
1.872 albertel 2343: &logthis("caching of id -> $id failed");
1.910 albertel 2344: $memcache->disconnect_all();
1.872 albertel 2345: }
1.600 albertel 2346: # need to make a copy of $value
1.919 albertel 2347: &make_room($id,$value,$debug);
1.599 albertel 2348: return $value;
2349: }
2350:
2351: sub make_room {
2352: my ($id,$value,$debug)=@_;
1.919 albertel 2353:
2354: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2355: : $value;
1.599 albertel 2356: if ($to_remember<0) { return; }
2357: $accessed{$id}=[&gettimeofday()];
2358: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2359: my $to_kick;
2360: my $max_time=0;
2361: foreach my $other (keys(%accessed)) {
2362: if (&tv_interval($accessed{$other}) > $max_time) {
2363: $to_kick=$other;
2364: $max_time=&tv_interval($accessed{$other});
2365: }
2366: }
2367: delete($remembered{$to_kick});
2368: delete($accessed{$to_kick});
2369: $kicks++;
2370: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2371: return;
2372: }
2373:
1.599 albertel 2374: sub purge_remembered {
1.604 albertel 2375: #&logthis("Tossing ".scalar(keys(%remembered)));
2376: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2377: undef(%remembered);
2378: undef(%accessed);
1.428 albertel 2379: }
1.70 www 2380: # ------------------------------------- Read an entry from a user's environment
2381:
2382: sub userenvironment {
2383: my ($udom,$unam,@what)=@_;
1.976 raeburn 2384: my $items;
2385: foreach my $item (@what) {
2386: $items.=&escape($item).'&';
2387: }
2388: $items=~s/\&$//;
1.70 www 2389: my %returnhash=();
1.1009 raeburn 2390: my $uhome = &homeserver($unam,$udom);
2391: unless ($uhome eq 'no_host') {
2392: my @answer=split(/\&/,
2393: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2394: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2395: return %returnhash;
2396: }
1.1009 raeburn 2397: my $i;
2398: for ($i=0;$i<=$#what;$i++) {
2399: $returnhash{$what[$i]}=&unescape($answer[$i]);
2400: }
1.70 www 2401: }
2402: return %returnhash;
1.1 albertel 2403: }
2404:
1.617 albertel 2405: # ---------------------------------------------------------- Get a studentphoto
2406: sub studentphoto {
2407: my ($udom,$unam,$ext) = @_;
2408: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2409: if (defined($env{'request.course.id'})) {
1.708 raeburn 2410: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2411: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2412: return(&retrievestudentphoto($udom,$unam,$ext));
2413: } else {
2414: my ($result,$perm_reqd)=
1.707 albertel 2415: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2416: if ($result eq 'ok') {
2417: if (!($perm_reqd eq 'yes')) {
2418: return(&retrievestudentphoto($udom,$unam,$ext));
2419: }
2420: }
2421: }
2422: }
2423: } else {
2424: my ($result,$perm_reqd) =
1.707 albertel 2425: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2426: if ($result eq 'ok') {
2427: if (!($perm_reqd eq 'yes')) {
2428: return(&retrievestudentphoto($udom,$unam,$ext));
2429: }
2430: }
2431: }
2432: return '/adm/lonKaputt/lonlogo_broken.gif';
2433: }
2434:
2435: sub retrievestudentphoto {
2436: my ($udom,$unam,$ext,$type) = @_;
2437: my $home=&Apache::lonnet::homeserver($unam,$udom);
2438: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2439: if ($ret eq 'ok') {
2440: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2441: if ($type eq 'thumbnail') {
2442: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2443: }
2444: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2445: return $tokenurl;
2446: } else {
2447: if ($type eq 'thumbnail') {
2448: return '/adm/lonKaputt/genericstudent_tn.gif';
2449: } else {
2450: return '/adm/lonKaputt/lonlogo_broken.gif';
2451: }
1.617 albertel 2452: }
2453: }
2454:
1.263 www 2455: # -------------------------------------------------------------------- New chat
2456:
2457: sub chatsend {
1.724 raeburn 2458: my ($newentry,$anon,$group)=@_;
1.620 albertel 2459: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2460: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2461: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2462: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2463: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2464: &escape($newentry)).':'.$group,$chome);
1.292 www 2465: }
2466:
2467: # ------------------------------------------ Find current version of a resource
2468:
2469: sub getversion {
2470: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2471: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2472: return ¤tversion(&filelocation('',$fname));
2473: }
2474:
2475: sub currentversion {
2476: my $fname=shift;
2477: my $author=$fname;
2478: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2479: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2480: my $home=&homeserver($uname,$udom);
1.292 www 2481: if ($home eq 'no_host') {
2482: return -1;
2483: }
1.1112 www 2484: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2485: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2486: return -1;
2487: }
1.1112 www 2488: return $answer;
1.263 www 2489: }
2490:
1.1111 www 2491: #
2492: # Return special version number of resource if set by override, empty otherwise
2493: #
2494: sub usedversion {
2495: my $fname=shift;
2496: unless ($fname) { $fname=$env{'request.uri'}; }
2497: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2498: if ($urlversion) { return $urlversion; }
2499: return '';
2500: }
2501:
1.1 albertel 2502: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2503:
1.1 albertel 2504: sub subscribe {
2505: my $fname=shift;
1.761 raeburn 2506: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2507: $fname=~s/[\n\r]//g;
1.1 albertel 2508: my $author=$fname;
2509: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2510: my ($udom,$uname)=split(/\//,$author);
2511: my $home=homeserver($uname,$udom);
1.335 albertel 2512: if ($home eq 'no_host') {
2513: return 'not_found';
1.1 albertel 2514: }
2515: my $answer=reply("sub:$fname",$home);
1.64 www 2516: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2517: $answer.=' by '.$home;
2518: }
1.1 albertel 2519: return $answer;
2520: }
2521:
1.8 www 2522: # -------------------------------------------------------------- Replicate file
2523:
2524: sub repcopy {
2525: my $filename=shift;
1.23 www 2526: $filename=~s/\/+/\//g;
1.1142 raeburn 2527: my $londocroot = $perlvar{'lonDocRoot'};
2528: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2529: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2530: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2531: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2532: return &repcopy_userfile($filename);
2533: }
1.532 albertel 2534: $filename=~s/[\n\r]//g;
1.8 www 2535: my $transname="$filename.in.transfer";
1.828 www 2536: # FIXME: this should flock
1.607 raeburn 2537: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2538: my $remoteurl=subscribe($filename);
1.64 www 2539: if ($remoteurl =~ /^con_lost by/) {
2540: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2541: return 'unavailable';
1.8 www 2542: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2543: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2544: return 'not_found';
1.64 www 2545: } elsif ($remoteurl =~ /^rejected by/) {
2546: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2547: return 'forbidden';
1.20 www 2548: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2549: return 'ok';
1.8 www 2550: } else {
1.290 www 2551: my $author=$filename;
2552: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2553: my ($udom,$uname)=split(/\//,$author);
2554: my $home=homeserver($uname,$udom);
2555: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2556: my @parts=split(/\//,$filename);
2557: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2558: if ($path ne "$londocroot/res") {
1.8 www 2559: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2560: return 'bad_request';
1.8 www 2561: }
2562: my $count;
2563: for ($count=5;$count<$#parts;$count++) {
2564: $path.="/$parts[$count]";
2565: if ((-e $path)!=1) {
2566: mkdir($path,0777);
2567: }
2568: }
2569: my $ua=new LWP::UserAgent;
2570: my $request=new HTTP::Request('GET',"$remoteurl");
2571: my $response=$ua->request($request,$transname);
2572: if ($response->is_error()) {
2573: unlink($transname);
2574: my $message=$response->status_line;
1.672 albertel 2575: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2576: ." LWP get: $message: $filename</font>");
1.607 raeburn 2577: return 'unavailable';
1.8 www 2578: } else {
1.16 www 2579: if ($remoteurl!~/\.meta$/) {
2580: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2581: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2582: if ($mresponse->is_error()) {
2583: unlink($filename.'.meta');
2584: &logthis(
1.672 albertel 2585: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2586: }
2587: }
1.8 www 2588: rename($transname,$filename);
1.607 raeburn 2589: return 'ok';
1.8 www 2590: }
1.290 www 2591: }
1.8 www 2592: }
1.330 www 2593: }
2594:
2595: # ------------------------------------------------ Get server side include body
2596: sub ssi_body {
1.381 albertel 2597: my ($filelink,%form)=@_;
1.606 matthew 2598: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2599: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2600: }
1.953 www 2601: my $output='';
2602: my $response;
1.980 raeburn 2603: if ($filelink=~/^https?\:/) {
1.954 raeburn 2604: ($output,$response)=&externalssi($filelink);
1.953 www 2605: } else {
1.1004 droeschl 2606: $filelink .= $filelink=~/\?/ ? '&' : '?';
2607: $filelink .= 'inhibitmenu=yes';
1.953 www 2608: ($output,$response)=&ssi($filelink,%form);
2609: }
1.778 albertel 2610: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2611: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2612: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2613: if (wantarray) {
2614: return ($output, $response);
2615: } else {
2616: return $output;
2617: }
1.8 www 2618: }
2619:
1.15 www 2620: # --------------------------------------------------------- Server Side Include
2621:
1.782 albertel 2622: sub absolute_url {
2623: my ($host_name) = @_;
2624: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2625: if ($host_name eq '') {
2626: $host_name = $ENV{'SERVER_NAME'};
2627: }
2628: return $protocol.$host_name;
2629: }
2630:
1.942 foxr 2631: #
2632: # Server side include.
2633: # Parameters:
2634: # fn Possibly encrypted resource name/id.
2635: # form Hash that describes how the rendering should be done
2636: # and other things.
1.944 foxr 2637: # Returns:
1.950 raeburn 2638: # Scalar context: The content of the response.
2639: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2640: #
1.15 www 2641: sub ssi {
2642:
1.944 foxr 2643: my ($fn,%form)=@_;
1.15 www 2644: my $ua=new LWP::UserAgent;
1.23 www 2645: my $request;
1.711 albertel 2646:
2647: $form{'no_update_last_known'}=1;
1.895 albertel 2648: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2649: if (%form) {
1.782 albertel 2650: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2651: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2652: } else {
1.782 albertel 2653: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2654: }
2655:
1.15 www 2656: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2657: my $response= $ua->request($request);
1.944 foxr 2658: if (wantarray) {
1.1172.2.3 raeburn 2659: return ($response->content, $response);
1.944 foxr 2660: } else {
1.1172.2.3 raeburn 2661: return $response->content;
1.942 foxr 2662: }
1.324 www 2663: }
2664:
2665: sub externalssi {
2666: my ($url)=@_;
2667: my $ua=new LWP::UserAgent;
2668: my $request=new HTTP::Request('GET',$url);
2669: my $response=$ua->request($request);
1.954 raeburn 2670: if (wantarray) {
2671: return ($response->content, $response);
2672: } else {
2673: return $response->content;
2674: }
1.15 www 2675: }
1.254 www 2676:
1.492 albertel 2677: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2678:
2679: sub allowuploaded {
2680: my ($srcurl,$url)=@_;
2681: $url=&clutter(&declutter($url));
2682: my $dir=$url;
2683: $dir=~s/\/[^\/]+$//;
2684: my %httpref=();
2685: my $httpurl=&hreflocation('',$url);
2686: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2687: &Apache::lonnet::appenv(\%httpref);
1.254 www 2688: }
1.477 raeburn 2689:
1.1172.2.13 raeburn 2690: #
2691: # Determine if the current user should be able to edit a particular resource,
2692: # when viewing in course context.
2693: # (a) When viewing resource used to determine if "Edit" item is included in
2694: # Functions.
2695: # (b) When displaying folder contents in course editor, used to determine if
2696: # "Edit" link will be displayed alongside resource.
2697: #
2698: # input: six args -- filename (decluttered), course number, course domain,
2699: # url, symb (if registered) and group (if this is a group
2700: # item -- e.g., bulletin board, group page etc.).
2701: # output: array of five scalars --
2702: # $cfile -- url for file editing if editable on current server
2703: # $home -- homeserver of resource (i.e., for author if published,
2704: # or course if uploaded.).
2705: # $switchserver -- 1 if server switch will be needed.
2706: # $forceedit -- 1 if icon/link should be to go to edit mode
2707: # $forceview -- 1 if icon/link should be to go to view mode
2708: #
2709:
2710: sub can_edit_resource {
2711: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2712: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2713: #
2714: # For aboutme pages user can only edit his/her own.
2715: #
2716: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2717: my ($sdom,$sname) = ($1,$2);
2718: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2719: $home = $env{'user.home'};
2720: $cfile = $resurl;
2721: if ($env{'form.forceedit'}) {
2722: $forceview = 1;
2723: } else {
2724: $forceedit = 1;
2725: }
2726: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2727: } else {
2728: return;
2729: }
2730: }
2731:
2732: if ($env{'request.course.id'}) {
2733: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2734: if ($group ne '') {
2735: # if this is a group homepage or group bulletin board, check group privs
2736: my $allowed = 0;
2737: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2738: if ((&allowed('mdg',$env{'request.course.id'}.
2739: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2740: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2741: $allowed = 1;
2742: }
2743: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2744: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2745: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2746: $allowed = 1;
2747: }
2748: }
2749: if ($allowed) {
2750: $home=&homeserver($cnum,$cdom);
2751: if ($env{'form.forceedit'}) {
2752: $forceview = 1;
2753: } else {
2754: $forceedit = 1;
2755: }
2756: $cfile = $resurl;
2757: } else {
2758: return;
2759: }
2760: } else {
1.1172.2.15 raeburn 2761: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2762: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2763: return;
2764: }
2765: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2766: #
2767: # No edit allowed where CC has switched to student role.
2768: #
2769: return;
2770: }
2771: }
2772: }
2773:
2774: if ($file ne '') {
2775: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2776: if (&is_course_upload($file,$cnum,$cdom)) {
2777: $uploaded = 1;
2778: $incourse = 1;
2779: if ($file =~/\.(htm|html|css|js|txt)$/) {
2780: $cfile = &hreflocation('',$file);
2781: if ($env{'form.forceedit'}) {
2782: $forceview = 1;
2783: } else {
2784: $forceedit = 1;
2785: }
2786: }
2787: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2788: $incourse = 1;
2789: if ($env{'form.forceedit'}) {
2790: $forceview = 1;
2791: } else {
2792: $forceedit = 1;
2793: }
2794: $cfile = $resurl;
2795: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2796: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2797: $incourse = 1;
2798: if ($env{'form.forceedit'}) {
2799: $forceview = 1;
2800: } else {
2801: $forceedit = 1;
2802: }
2803: $cfile = $resurl;
2804: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2805: $incourse = 1;
2806: $cfile = $resurl.'/smpedit';
2807: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2808: $incourse = 1;
2809: if ($env{'form.forceedit'}) {
2810: $forceview = 1;
2811: } else {
2812: $forceedit = 1;
2813: }
2814: $cfile = $resurl;
1.1172.2.15 raeburn 2815: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2816: $incourse = 1;
2817: if ($env{'form.forceedit'}) {
2818: $forceview = 1;
2819: } else {
2820: $forceedit = 1;
2821: }
2822: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2823: }
2824: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2825: my $template = '/res/lib/templates/simpleproblem.problem';
2826: if (&is_on_map($template)) {
2827: $incourse = 1;
2828: $forceview = 1;
2829: $cfile = $template;
2830: }
2831: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2832: $incourse = 1;
2833: if ($env{'form.forceedit'}) {
2834: $forceview = 1;
2835: } else {
2836: $forceedit = 1;
2837: }
2838: $cfile = $resurl;
2839: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2840: $incourse = 1;
2841: $forceview = 1;
2842: if ($symb) {
2843: my ($map,$id,$res)=&decode_symb($symb);
2844: $env{'request.symb'} = $symb;
2845: $cfile = &clutter($res);
2846: } else {
2847: $cfile = $env{'form.suppurl'};
2848: $cfile =~ s{^http://}{};
2849: $cfile = '/adm/wrapper/ext/'.$cfile;
2850: }
1.1172.2.31 raeburn 2851: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2852: if ($env{'form.forceedit'}) {
2853: $forceview = 1;
2854: } else {
2855: $forceedit = 1;
2856: }
2857: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2858: }
2859: }
2860: if ($uploaded || $incourse) {
2861: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2862: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2863: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2864: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2865: # Check that the user has permission to edit this resource
2866: my $setpriv = 1;
2867: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2868: if (defined($cfudom)) {
2869: $home=&homeserver($cfuname,$cfudom);
2870: $cfile=$file;
2871: }
2872: }
2873: if (($cfile ne '') && (!$incourse || $uploaded) &&
2874: (($home ne '') && ($home ne 'no_host'))) {
2875: my @ids=¤t_machine_ids();
2876: unless (grep(/^\Q$home\E$/,@ids)) {
2877: $switchserver=1;
2878: }
2879: }
2880: }
2881: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2882: }
2883:
2884: sub is_course_upload {
2885: my ($file,$cnum,$cdom) = @_;
2886: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2887: $uploadpath =~ s{^\/}{};
2888: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2889: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2890: return 1;
2891: }
2892: return;
2893: }
2894:
2895: sub in_course {
2896: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2897: if ($hideprivileged) {
2898: my $skipuser;
1.1172.2.23 raeburn 2899: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2900: my @possdoms = ($cdom);
2901: if ($coursehash{'checkforpriv'}) {
2902: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2903: }
2904: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2905: $skipuser = 1;
2906: if ($coursehash{'nothideprivileged'}) {
2907: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2908: my $user;
2909: if ($item =~ /:/) {
2910: $user = $item;
2911: } else {
2912: $user = join(':',split(/[\@]/,$item));
2913: }
2914: if ($user eq $uname.':'.$udom) {
2915: undef($skipuser);
2916: last;
2917: }
2918: }
2919: }
2920: if ($skipuser) {
2921: return 0;
2922: }
2923: }
2924: }
2925: $type ||= 'any';
2926: if (!defined($cdom) || !defined($cnum)) {
2927: my $cid = $env{'request.course.id'};
2928: $cdom = $env{'course.'.$cid.'.domain'};
2929: $cnum = $env{'course.'.$cid.'.num'};
2930: }
2931: my $typesref;
2932: if (($type eq 'any') || ($type eq 'all')) {
2933: $typesref = ['active','previous','future'];
2934: } elsif ($type eq 'previous' || $type eq 'future') {
2935: $typesref = [$type];
2936: }
2937: my %roles = &get_my_roles($uname,$udom,'userroles',
2938: $typesref,undef,[$cdom]);
2939: my ($tmp) = keys(%roles);
2940: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2941: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2942: if (@course_roles > 0) {
2943: return 1;
2944: }
2945: return 0;
2946: }
2947:
1.478 albertel 2948: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2949: # input: action, courseID, current domain, intended
1.637 raeburn 2950: # path to file, source of file, instruction to parse file for objects,
2951: # ref to hash for embedded objects,
2952: # ref to hash for codebase of java objects.
1.1095 raeburn 2953: # reference to scalar to accommodate mime type determined
2954: # from File::MMagic if $parser = parse.
1.637 raeburn 2955: #
1.485 raeburn 2956: # output: url to file (if action was uploaddoc),
2957: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2958: #
1.478 albertel 2959: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2960: # course.
1.477 raeburn 2961: #
1.478 albertel 2962: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2963: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2964: # course's home server.
1.477 raeburn 2965: #
1.478 albertel 2966: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2967: # be copied from $source (current location) to
2968: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2969: # and will then be copied to
2970: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2971: # course's home server.
1.485 raeburn 2972: #
1.481 raeburn 2973: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2974: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2975: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2976: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2977: # in course's home server.
1.637 raeburn 2978: #
1.477 raeburn 2979:
2980: sub process_coursefile {
1.1095 raeburn 2981: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2982: $mimetype)=@_;
1.477 raeburn 2983: my $fetchresult;
1.638 albertel 2984: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2985: if ($action eq 'propagate') {
1.638 albertel 2986: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2987: $home);
1.481 raeburn 2988: } else {
1.477 raeburn 2989: my $fpath = '';
2990: my $fname = $file;
1.478 albertel 2991: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2992: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2993: my $filepath = &build_filepath($fpath);
1.481 raeburn 2994: if ($action eq 'copy') {
2995: if ($source eq '') {
2996: $fetchresult = 'no source file';
2997: return $fetchresult;
2998: } else {
2999: my $destination = $filepath.'/'.$fname;
3000: rename($source,$destination);
3001: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3002: $home);
1.481 raeburn 3003: }
3004: } elsif ($action eq 'uploaddoc') {
3005: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3006: print $fh $env{'form.'.$source};
1.481 raeburn 3007: close($fh);
1.637 raeburn 3008: if ($parser eq 'parse') {
1.1024 raeburn 3009: my $mm = new File::MMagic;
1.1095 raeburn 3010: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3011: if ($type eq 'text/html') {
1.1024 raeburn 3012: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3013: unless ($parse_result eq 'ok') {
3014: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3015: }
1.637 raeburn 3016: }
1.1095 raeburn 3017: if (ref($mimetype)) {
3018: $$mimetype = $type;
3019: }
1.637 raeburn 3020: }
1.477 raeburn 3021: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3022: $home);
1.481 raeburn 3023: if ($fetchresult eq 'ok') {
3024: return '/uploaded/'.$fpath.'/'.$fname;
3025: } else {
3026: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3027: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3028: return '/adm/notfound.html';
3029: }
1.477 raeburn 3030: }
3031: }
1.485 raeburn 3032: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3033: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3034: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3035: }
3036: return $fetchresult;
3037: }
3038:
1.637 raeburn 3039: sub build_filepath {
3040: my ($fpath) = @_;
3041: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3042: unless ($fpath eq '') {
3043: my @parts=split('/',$fpath);
3044: foreach my $part (@parts) {
3045: $filepath.= '/'.$part;
3046: if ((-e $filepath)!=1) {
3047: mkdir($filepath,0777);
3048: }
3049: }
3050: }
3051: return $filepath;
3052: }
3053:
3054: sub store_edited_file {
1.638 albertel 3055: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3056: my $file = $primary_url;
3057: $file =~ s#^/uploaded/$docudom/$docuname/##;
3058: my $fpath = '';
3059: my $fname = $file;
3060: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3061: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3062: my $filepath = &build_filepath($fpath);
3063: open(my $fh,'>'.$filepath.'/'.$fname);
3064: print $fh $content;
3065: close($fh);
1.638 albertel 3066: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3067: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3068: $home);
1.637 raeburn 3069: if ($$fetchresult eq 'ok') {
3070: return '/uploaded/'.$fpath.'/'.$fname;
3071: } else {
1.638 albertel 3072: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3073: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3074: return '/adm/notfound.html';
3075: }
3076: }
3077:
1.531 albertel 3078: sub clean_filename {
1.831 albertel 3079: my ($fname,$args)=@_;
1.315 www 3080: # Replace Windows backslashes by forward slashes
1.257 www 3081: $fname=~s/\\/\//g;
1.831 albertel 3082: if (!$args->{'keep_path'}) {
3083: # Get rid of everything but the actual filename
3084: $fname=~s/^.*\/([^\/]+)$/$1/;
3085: }
1.315 www 3086: # Replace spaces by underscores
3087: $fname=~s/\s+/\_/g;
3088: # Replace all other weird characters by nothing
1.831 albertel 3089: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3090: # Replace all .\d. sequences with _\d. so they no longer look like version
3091: # numbers
3092: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3093: return $fname;
3094: }
1.1051 raeburn 3095: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3096: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3097: # image with the same aspect ratio as the original, but with dimensions which do
3098: # not exceed $resizewidth and $resizeheight.
3099:
1.984 neumanie 3100: sub resizeImage {
1.1051 raeburn 3101: my ($img_path,$resizewidth,$resizeheight) = @_;
3102: my $ima = Image::Magick->new;
3103: my $resized;
3104: if (-e $img_path) {
3105: $ima->Read($img_path);
3106: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3107: my $width = $ima->Get('width');
3108: my $height = $ima->Get('height');
3109: if ($width > $resizewidth) {
3110: my $factor = $width/$resizewidth;
3111: my $newheight = $height/$factor;
3112: $ima->Scale(width=>$resizewidth,height=>$newheight);
3113: $resized = 1;
3114: }
3115: }
3116: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3117: my $width = $ima->Get('width');
3118: my $height = $ima->Get('height');
3119: if ($height > $resizeheight) {
3120: my $factor = $height/$resizeheight;
3121: my $newwidth = $width/$factor;
3122: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3123: $resized = 1;
3124: }
3125: }
3126: if ($resized) {
3127: $ima->Write($img_path);
3128: }
3129: }
3130: return;
1.977 amueller 3131: }
3132:
1.608 albertel 3133: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3134: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3135: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3136: # $context - possible values: coursedoc, existingfile, overwrite,
3137: # canceloverwrite, or ''.
3138: # if 'coursedoc': upload to the current course
3139: # if 'existingfile': write file to tmp/overwrites directory
3140: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3141: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3142: # $subdir - directory in userfile to store the file into
1.858 raeburn 3143: # $parser - instruction to parse file for objects ($parser = parse)
3144: # $allfiles - reference to hash for embedded objects
3145: # $codebase - reference to hash for codebase of java objects
3146: # $desuname - username for permanent storage of uploaded file
3147: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3148: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3149: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3150: # $resizewidth - width (pixels) to which to resize uploaded image
3151: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3152: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3153: # from File::MMagic.
1.858 raeburn 3154: #
1.686 albertel 3155: # output: url of file in userspace, or error: <message>
3156: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3157:
1.531 albertel 3158: sub userfileupload {
1.1090 raeburn 3159: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3160: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3161: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3162: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3163: $fname=&clean_filename($fname);
1.1090 raeburn 3164: # See if there is anything left
1.257 www 3165: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3166: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3167: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3168: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3169: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3170: my $now = time;
1.1090 raeburn 3171: my $filepath;
1.1095 raeburn 3172: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3173: $filepath = 'tmp/helprequests/'.$now;
3174: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3175: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3176: '_'.$env{'user.domain'}.'/pending';
3177: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3178: my ($docuname,$docudom);
3179: if ($destudom) {
3180: $docudom = $destudom;
3181: } else {
3182: $docudom = $env{'user.domain'};
3183: }
3184: if ($destuname) {
3185: $docuname = $destuname;
3186: } else {
3187: $docuname = $env{'user.name'};
3188: }
3189: if (exists($env{'form.group'})) {
3190: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3191: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3192: }
3193: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3194: if ($context eq 'canceloverwrite') {
3195: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3196: if (-e $tempfile) {
3197: my @info = stat($tempfile);
3198: if ($info[9] eq $env{'form.timestamp'}) {
3199: unlink($tempfile);
3200: }
3201: }
3202: return;
1.523 raeburn 3203: }
3204: }
1.1090 raeburn 3205: # Create the directory if not present
1.741 raeburn 3206: my @parts=split(/\//,$filepath);
3207: my $fullpath = $perlvar{'lonDaemons'};
3208: for (my $i=0;$i<@parts;$i++) {
3209: $fullpath .= '/'.$parts[$i];
3210: if ((-e $fullpath)!=1) {
3211: mkdir($fullpath,0777);
3212: }
3213: }
3214: open(my $fh,'>'.$fullpath.'/'.$fname);
3215: print $fh $env{'form.'.$formname};
3216: close($fh);
1.1090 raeburn 3217: if ($context eq 'existingfile') {
3218: my @info = stat($fullpath.'/'.$fname);
3219: return ($fullpath.'/'.$fname,$info[9]);
3220: } else {
3221: return $fullpath.'/'.$fname;
3222: }
1.523 raeburn 3223: }
1.995 raeburn 3224: if ($subdir eq 'scantron') {
3225: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3226: } else {
1.995 raeburn 3227: $fname="$subdir/$fname";
3228: }
1.1090 raeburn 3229: if ($context eq 'coursedoc') {
1.638 albertel 3230: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3231: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3232: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3233: return &finishuserfileupload($docuname,$docudom,
3234: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3235: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3236: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3237: } else {
1.1172.2.21 raeburn 3238: if ($env{'form.folder'}) {
3239: $fname=$env{'form.folder'}.'/'.$fname;
3240: }
1.638 albertel 3241: return &process_coursefile('uploaddoc',$docuname,$docudom,
3242: $fname,$formname,$parser,
1.1095 raeburn 3243: $allfiles,$codebase,$mimetype);
1.481 raeburn 3244: }
1.719 banghart 3245: } elsif (defined($destuname)) {
3246: my $docuname=$destuname;
3247: my $docudom=$destudom;
1.860 raeburn 3248: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3249: $parser,$allfiles,$codebase,
1.1051 raeburn 3250: $thumbwidth,$thumbheight,
1.1095 raeburn 3251: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3252: } else {
1.638 albertel 3253: my $docuname=$env{'user.name'};
3254: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3255: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3256: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3257: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3258: }
1.860 raeburn 3259: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3260: $parser,$allfiles,$codebase,
1.1051 raeburn 3261: $thumbwidth,$thumbheight,
1.1095 raeburn 3262: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3263: }
1.271 www 3264: }
3265:
3266: sub finishuserfileupload {
1.860 raeburn 3267: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3268: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3269: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3270: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3271:
1.860 raeburn 3272: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3273: $file=$fname;
3274: if ($fname=~m|/|) {
3275: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3276: $path.=$fnamepath.'/';
3277: }
1.259 www 3278: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3279: my $count;
3280: for ($count=4;$count<=$#parts;$count++) {
3281: $filepath.="/$parts[$count]";
3282: if ((-e $filepath)!=1) {
3283: mkdir($filepath,0777);
3284: }
3285: }
1.984 neumanie 3286:
1.258 www 3287: # Save the file
3288: {
1.701 albertel 3289: if (!open(FH,'>'.$filepath.'/'.$file)) {
3290: &logthis('Failed to create '.$filepath.'/'.$file);
3291: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3292: return '/adm/notfound.html';
3293: }
1.1090 raeburn 3294: if ($context eq 'overwrite') {
1.1117 foxr 3295: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3296: my $target = $filepath.'/'.$file;
3297: if (-e $source) {
3298: my @info = stat($source);
3299: if ($info[9] eq $env{'form.timestamp'}) {
3300: unless (&File::Copy::move($source,$target)) {
3301: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3302: return "Moving from $source failed";
3303: }
3304: } else {
3305: return "Temporary file: $source had unexpected date/time for last modification";
3306: }
3307: } else {
3308: return "Temporary file: $source missing";
3309: }
3310: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3311: &logthis('Failed to write to '.$filepath.'/'.$file);
3312: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3313: return '/adm/notfound.html';
3314: }
1.570 albertel 3315: close(FH);
1.1051 raeburn 3316: if ($resizewidth && $resizeheight) {
3317: my $mm = new File::MMagic;
3318: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3319: if ($mime_type =~ m{^image/}) {
3320: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3321: }
1.977 amueller 3322: }
1.258 www 3323: }
1.1152 raeburn 3324: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3325: if (ref($mimetype)) {
3326: if ($$mimetype eq '') {
3327: my $mm = new File::MMagic;
3328: my $type = $mm->checktype_filename($filepath.'/'.$file);
3329: $$mimetype = $type;
3330: }
3331: }
3332: }
1.637 raeburn 3333: if ($parser eq 'parse') {
1.1152 raeburn 3334: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3335: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3336: $allfiles,$codebase);
3337: unless ($parse_result eq 'ok') {
3338: &logthis('Failed to parse '.$filepath.$file.
3339: ' for embedded media: '.$parse_result);
3340: }
1.637 raeburn 3341: }
3342: }
1.860 raeburn 3343: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3344: my $input = $filepath.'/'.$file;
3345: my $output = $filepath.'/'.'tn-'.$file;
3346: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3347: system("convert -sample $thumbsize $input $output");
3348: if (-e $filepath.'/'.'tn-'.$file) {
3349: $fetchthumb = 1;
3350: }
3351: }
1.858 raeburn 3352:
1.259 www 3353: # Notify homeserver to grep it
3354: #
1.984 neumanie 3355: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3356: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3357: if ($fetchresult eq 'ok') {
1.860 raeburn 3358: if ($fetchthumb) {
3359: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3360: if ($thumbresult ne 'ok') {
3361: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3362: $docuhome.': '.$thumbresult);
3363: }
3364: }
1.259 www 3365: #
1.258 www 3366: # Return the URL to it
1.494 albertel 3367: return '/uploaded/'.$path.$file;
1.263 www 3368: } else {
1.494 albertel 3369: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3370: ': '.$fetchresult);
1.263 www 3371: return '/adm/notfound.html';
1.858 raeburn 3372: }
1.493 albertel 3373: }
3374:
1.637 raeburn 3375: sub extract_embedded_items {
1.961 raeburn 3376: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3377: my @state = ();
1.1164 raeburn 3378: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3379: my %javafiles = (
3380: codebase => '',
3381: code => '',
3382: archive => ''
3383: );
3384: my %mediafiles = (
3385: src => '',
3386: movie => '',
3387: );
1.648 raeburn 3388: my $p;
3389: if ($content) {
3390: $p = HTML::LCParser->new($content);
3391: } else {
1.961 raeburn 3392: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3393: }
1.641 albertel 3394: while (my $t=$p->get_token()) {
1.640 albertel 3395: if ($t->[0] eq 'S') {
3396: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3397: push(@state, $tagname);
1.648 raeburn 3398: if (lc($tagname) eq 'allow') {
3399: &add_filetype($allfiles,$attr->{'src'},'src');
3400: }
1.640 albertel 3401: if (lc($tagname) eq 'img') {
3402: &add_filetype($allfiles,$attr->{'src'},'src');
3403: }
1.886 albertel 3404: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3405: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3406: &add_filetype($allfiles,$attr->{'href'},'href');
3407: }
1.886 albertel 3408: }
1.645 raeburn 3409: if (lc($tagname) eq 'script') {
1.1164 raeburn 3410: my $src;
1.645 raeburn 3411: if ($attr->{'archive'} =~ /\.jar$/i) {
3412: &add_filetype($allfiles,$attr->{'archive'},'archive');
3413: } else {
1.1164 raeburn 3414: if ($attr->{'src'} ne '') {
3415: $src = $attr->{'src'};
3416: &add_filetype($allfiles,$src,'src');
3417: }
3418: }
3419: my $text = $p->get_trimmed_text();
3420: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3421: my @swfargs = split(/,/,$1);
3422: foreach my $item (@swfargs) {
3423: $item =~ s/["']//g;
3424: $item =~ s/^\s+//;
3425: $item =~ s/\s+$//;
3426: }
3427: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3428: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3429: push(@{$related{$swfargs[0]}},$swfargs[2]);
3430: } else {
3431: $related{$swfargs[0]} = [$swfargs[2]];
3432: }
3433: }
1.645 raeburn 3434: }
3435: }
3436: if (lc($tagname) eq 'link') {
3437: if (lc($attr->{'rel'}) eq 'stylesheet') {
3438: &add_filetype($allfiles,$attr->{'href'},'href');
3439: }
3440: }
1.640 albertel 3441: if (lc($tagname) eq 'object' ||
3442: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3443: foreach my $item (keys(%javafiles)) {
3444: $javafiles{$item} = '';
3445: }
1.1164 raeburn 3446: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3447: $lastids{lc($tagname)} = $attr->{'id'};
3448: }
1.640 albertel 3449: }
3450: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3451: my $name = lc($attr->{'name'});
3452: foreach my $item (keys(%javafiles)) {
3453: if ($name eq $item) {
3454: $javafiles{$item} = $attr->{'value'};
3455: last;
3456: }
3457: }
1.1164 raeburn 3458: my $pathfrom;
1.640 albertel 3459: foreach my $item (keys(%mediafiles)) {
3460: if ($name eq $item) {
1.1164 raeburn 3461: $pathfrom = $attr->{'value'};
3462: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3463: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3464: last;
3465: }
3466: }
1.1164 raeburn 3467: if ($name eq 'flashvars') {
3468: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3469: }
3470: if ($pathfrom ne '') {
3471: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3472: $pathfrom);
3473: }
1.640 albertel 3474: }
3475: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3476: foreach my $item (keys(%javafiles)) {
3477: if ($attr->{$item}) {
3478: $javafiles{$item} = $attr->{$item};
3479: last;
3480: }
3481: }
3482: foreach my $item (keys(%mediafiles)) {
3483: if ($attr->{$item}) {
3484: &add_filetype($allfiles,$attr->{$item},$item);
3485: last;
3486: }
3487: }
1.1164 raeburn 3488: if (lc($tagname) eq 'embed') {
3489: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3490: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3491: $attr->{'src'});
3492: }
3493: }
1.640 albertel 3494: }
1.1172.2.35 raeburn 3495: if (lc($tagname) eq 'iframe') {
3496: my $src = $attr->{'src'} ;
3497: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3498: &add_filetype($allfiles,$src,'src');
3499: } elsif ($src =~ m{^/}) {
3500: if ($env{'request.course.id'}) {
3501: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3502: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3503: my $url = &hreflocation('',$fullpath);
3504: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3505: my $relpath = $1;
3506: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3507: &add_filetype($allfiles,$1,'src');
3508: }
3509: }
3510: }
3511: }
3512: }
1.1164 raeburn 3513: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3514: pop(@state);
1.1164 raeburn 3515: }
1.640 albertel 3516: } elsif ($t->[0] eq 'E') {
3517: my ($tagname) = ($t->[1]);
3518: if ($javafiles{'codebase'} ne '') {
3519: $javafiles{'codebase'} .= '/';
3520: }
3521: if (lc($tagname) eq 'applet' ||
3522: lc($tagname) eq 'object' ||
3523: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3524: ) {
3525: foreach my $item (keys(%javafiles)) {
3526: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3527: my $file=$javafiles{'codebase'}.$javafiles{$item};
3528: &add_filetype($allfiles,$file,$item);
3529: }
3530: }
3531: }
3532: pop @state;
3533: }
3534: }
1.1164 raeburn 3535: foreach my $id (sort(keys(%flashvars))) {
3536: if ($shockwave{$id} ne '') {
3537: my @pairs = split(/\&/,$flashvars{$id});
3538: foreach my $pair (@pairs) {
3539: my ($key,$value) = split(/\=/,$pair);
3540: if ($key eq 'thumb') {
3541: &add_filetype($allfiles,$value,$key);
3542: } elsif ($key eq 'content') {
3543: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3544: my ($ext) = ($value =~ /\.([^.]+)$/);
3545: if ($ext ne '') {
3546: &add_filetype($allfiles,$path.$value,$ext);
3547: }
3548: }
3549: }
3550: }
3551: }
1.637 raeburn 3552: return 'ok';
3553: }
3554:
1.639 albertel 3555: sub add_filetype {
3556: my ($allfiles,$file,$type)=@_;
3557: if (exists($allfiles->{$file})) {
3558: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3559: push(@{$allfiles->{$file}}, &escape($type));
3560: }
3561: } else {
3562: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3563: }
3564: }
3565:
1.1164 raeburn 3566: sub embedded_dependency {
3567: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3568: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3569: if (($identifier ne '') &&
3570: (ref($related->{$identifier}) eq 'ARRAY') &&
3571: ($pathfrom ne '')) {
3572: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3573: foreach my $dep (@{$related->{$identifier}}) {
3574: &add_filetype($allfiles,$path.$dep,'object');
3575: }
3576: }
3577: }
3578: return;
3579: }
3580:
1.493 albertel 3581: sub removeuploadedurl {
1.984 neumanie 3582: my ($url)=@_;
3583: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3584: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3585: }
3586:
3587: sub removeuserfile {
3588: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3589: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3590: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3591: if ($result eq 'ok') {
1.798 raeburn 3592: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3593: my $metafile = $fname.'.meta';
3594: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3595: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3596: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3597: my $sqlresult =
1.823 albertel 3598: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3599: 'portfolio_metadata',$group,
3600: 'delete');
1.798 raeburn 3601: }
3602: }
3603: return $result;
1.257 www 3604: }
1.15 www 3605:
1.530 albertel 3606: sub mkdiruserfile {
3607: my ($docuname,$docudom,$dir)=@_;
3608: my $home=&homeserver($docuname,$docudom);
3609: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3610: }
3611:
1.531 albertel 3612: sub renameuserfile {
3613: my ($docuname,$docudom,$old,$new)=@_;
3614: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3615: my $result = &reply("renameuserfile:$docudom:$docuname:".
3616: &escape("$old").':'.&escape("$new"),$home);
3617: if ($result eq 'ok') {
3618: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3619: my $oldmeta = $old.'.meta';
3620: my $newmeta = $new.'.meta';
3621: my $metaresult =
3622: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3623: my $url = "/uploaded/$docudom/$docuname/$old";
3624: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3625: my $sqlresult =
1.823 albertel 3626: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3627: 'portfolio_metadata',$group,
3628: 'delete');
1.798 raeburn 3629: }
3630: }
3631: return $result;
1.531 albertel 3632: }
3633:
1.14 www 3634: # ------------------------------------------------------------------------- Log
3635:
3636: sub log {
3637: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3638: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3639: }
3640:
3641: # ------------------------------------------------------------------ Course Log
1.352 www 3642: #
3643: # This routine flushes several buffers of non-mission-critical nature
3644: #
1.157 www 3645:
3646: sub flushcourselogs {
1.352 www 3647: &logthis('Flushing log buffers');
3648: #
3649: # course logs
3650: # This is a log of all transactions in a course, which can be used
3651: # for data mining purposes
3652: #
3653: # It also collects the courseid database, which lists last transaction
3654: # times and course titles for all courseids
3655: #
3656: my %courseidbuffer=();
1.921 raeburn 3657: foreach my $crsid (keys(%courselogs)) {
1.352 www 3658: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3659: &escape($courselogs{$crsid}),
3660: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3661: delete $courselogs{$crsid};
3662: } else {
3663: &logthis('Failed to flush log buffer for '.$crsid);
3664: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3665: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3666: " exceeded maximum size, deleting.</font>");
3667: delete $courselogs{$crsid};
3668: }
1.352 www 3669: }
1.920 raeburn 3670: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3671: 'description' => $coursedescrbuf{$crsid},
3672: 'inst_code' => $courseinstcodebuf{$crsid},
3673: 'type' => $coursetypebuf{$crsid},
3674: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3675: };
1.191 harris41 3676: }
1.352 www 3677: #
3678: # Write course id database (reverse lookup) to homeserver of courses
3679: # Is used in pickcourse
3680: #
1.840 albertel 3681: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3682: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3683: $courseidbuffer{$crs_home},
3684: $crs_home,'timeonly');
1.352 www 3685: }
3686: #
3687: # File accesses
3688: # Writes to the dynamic metadata of resources to get hit counts, etc.
3689: #
1.449 matthew 3690: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3691: if ($entry =~ /___count$/) {
3692: my ($dom,$name);
1.807 albertel 3693: ($dom,$name,undef)=
1.811 albertel 3694: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3695: if (! defined($dom) || $dom eq '' ||
3696: ! defined($name) || $name eq '') {
1.620 albertel 3697: my $cid = $env{'request.course.id'};
3698: $dom = $env{'request.'.$cid.'.domain'};
3699: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3700: }
1.450 matthew 3701: my $value = $accesshash{$entry};
3702: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3703: my %temphash=($url => $value);
1.449 matthew 3704: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3705: if ($result eq 'ok') {
3706: delete $accesshash{$entry};
3707: }
3708: } else {
1.811 albertel 3709: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3710: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3711: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3712: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3713: delete $accesshash{$entry};
3714: }
1.185 www 3715: }
1.191 harris41 3716: }
1.352 www 3717: #
3718: # Roles
3719: # Reverse lookup of user roles for course faculty/staff and co-authorship
3720: #
1.800 albertel 3721: foreach my $entry (keys(%userrolehash)) {
1.351 www 3722: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3723: split(/\:/,$entry);
3724: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3725: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3726: $rudom,$runame) eq 'ok') {
3727: delete $userrolehash{$entry};
3728: }
3729: }
1.662 raeburn 3730: #
3731: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3732: #
3733: my %domrolebuffer = ();
1.1000 raeburn 3734: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3735: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3736: if ($domrolebuffer{$rudom}) {
3737: $domrolebuffer{$rudom}.='&'.&escape($entry).
3738: '='.&escape($domainrolehash{$entry});
3739: } else {
3740: $domrolebuffer{$rudom}.=&escape($entry).
3741: '='.&escape($domainrolehash{$entry});
3742: }
3743: delete $domainrolehash{$entry};
3744: }
3745: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3746: my %servers = &get_servers($dom,'library');
3747: foreach my $tryserver (keys(%servers)) {
3748: unless (&reply('domroleput:'.$dom.':'.
3749: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3750: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3751: }
1.662 raeburn 3752: }
3753: }
1.186 www 3754: $dumpcount++;
1.157 www 3755: }
3756:
3757: sub courselog {
3758: my $what=shift;
1.158 www 3759: $what=time.':'.$what;
1.620 albertel 3760: unless ($env{'request.course.id'}) { return ''; }
3761: $coursedombuf{$env{'request.course.id'}}=
3762: $env{'course.'.$env{'request.course.id'}.'.domain'};
3763: $coursenumbuf{$env{'request.course.id'}}=
3764: $env{'course.'.$env{'request.course.id'}.'.num'};
3765: $coursehombuf{$env{'request.course.id'}}=
3766: $env{'course.'.$env{'request.course.id'}.'.home'};
3767: $coursedescrbuf{$env{'request.course.id'}}=
3768: $env{'course.'.$env{'request.course.id'}.'.description'};
3769: $courseinstcodebuf{$env{'request.course.id'}}=
3770: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3771: $courseownerbuf{$env{'request.course.id'}}=
3772: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3773: $coursetypebuf{$env{'request.course.id'}}=
3774: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3775: if (defined $courselogs{$env{'request.course.id'}}) {
3776: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3777: } else {
1.620 albertel 3778: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3779: }
1.620 albertel 3780: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3781: &flushcourselogs();
3782: }
1.158 www 3783: }
3784:
3785: sub courseacclog {
3786: my $fnsymb=shift;
1.620 albertel 3787: unless ($env{'request.course.id'}) { return ''; }
3788: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3789: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3790: $what.=':POST';
1.583 matthew 3791: # FIXME: Probably ought to escape things....
1.800 albertel 3792: foreach my $key (keys(%env)) {
3793: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3794: my $formitem = $1;
3795: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3796: $what.=':'.$formitem.'='.$env{$key};
3797: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3798: $what.=':'.$formitem.'='.$env{$key};
3799: }
1.158 www 3800: }
1.191 harris41 3801: }
1.583 matthew 3802: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3803: # FIXME: We should not be depending on a form parameter that someone
3804: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3805: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3806: $what.= ':POST';
3807: # FIXME: Probably ought to escape things....
3808: foreach my $element ('courseexp','crsfulltext','crsrelated',
3809: 'crsdiscuss') {
1.620 albertel 3810: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3811: }
3812: }
1.158 www 3813: }
3814: &courselog($what);
1.149 www 3815: }
3816:
1.185 www 3817: sub countacc {
3818: my $url=&declutter(shift);
1.458 matthew 3819: return if (! defined($url) || $url eq '');
1.620 albertel 3820: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3821: #
3822: # Mark that this url was used in this course
3823: #
1.620 albertel 3824: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3825: #
3826: # Increase the access count for this resource in this child process
3827: #
1.281 www 3828: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3829: $accesshash{$key}++;
1.185 www 3830: }
1.349 www 3831:
1.361 www 3832: sub linklog {
3833: my ($from,$to)=@_;
3834: $from=&declutter($from);
3835: $to=&declutter($to);
3836: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3837: $accesshash{$to.'___'.$from.'___goto'}=1;
3838: }
1.1160 www 3839:
3840: sub statslog {
3841: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3842: if ($users<2) { return; }
3843: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3844: 'course' => $env{'request.course.id'},
3845: 'sections' => '"all"',
3846: 'num_students' => $users,
3847: 'part' => $part,
3848: 'symb' => $symb,
3849: 'mean_tries' => $av_attempts,
3850: 'deg_of_diff' => $degdiff});
3851: foreach my $key (keys(%dynstore)) {
3852: $accesshash{$key}=$dynstore{$key};
3853: }
3854: }
1.361 www 3855:
1.349 www 3856: sub userrolelog {
3857: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3858: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3859: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3860: $userrolehash
3861: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3862: =$tend.':'.$tstart;
1.662 raeburn 3863: }
1.1169 droeschl 3864: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3865: $userrolehash
3866: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3867: =$tend.':'.$tstart;
3868: }
1.1169 droeschl 3869: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3870: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3871: $domainrolehash
3872: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3873: = $tend.':'.$tstart;
3874: }
1.351 www 3875: }
3876:
1.957 raeburn 3877: sub courserolelog {
3878: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3879: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3880: my $cdom = $1;
3881: my $cnum = $2;
3882: my $sec = $3;
3883: my $namespace = 'rolelog';
3884: my %storehash = (
3885: role => $trole,
3886: start => $tstart,
3887: end => $tend,
3888: selfenroll => $selfenroll,
3889: context => $context,
3890: );
3891: if ($trole eq 'gr') {
3892: $namespace = 'groupslog';
3893: $storehash{'group'} = $sec;
3894: } else {
3895: $storehash{'section'} = $sec;
3896: }
3897: &write_log('course',$namespace,\%storehash,$delflag,$username,
3898: $domain,$cnum,$cdom);
3899: if (($trole ne 'st') || ($sec ne '')) {
3900: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3901: }
3902: }
3903: return;
3904: }
3905:
1.1172.2.9 raeburn 3906: sub domainrolelog {
3907: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3908: if ($area =~ m{^/($match_domain)/$}) {
3909: my $cdom = $1;
3910: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3911: my $namespace = 'rolelog';
3912: my %storehash = (
3913: role => $trole,
3914: start => $tstart,
3915: end => $tend,
3916: context => $context,
3917: );
3918: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3919: $domain,$domconfiguser,$cdom);
3920: }
3921: return;
3922:
3923: }
3924:
3925: sub coauthorrolelog {
3926: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3927: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3928: my $audom = $1;
3929: my $auname = $2;
3930: my $namespace = 'rolelog';
3931: my %storehash = (
3932: role => $trole,
3933: start => $tstart,
3934: end => $tend,
3935: context => $context,
3936: );
3937: &write_log('author',$namespace,\%storehash,$delflag,$username,
3938: $domain,$auname,$audom);
3939: }
3940: return;
3941: }
3942:
1.351 www 3943: sub get_course_adv_roles {
1.948 raeburn 3944: my ($cid,$codes) = @_;
1.620 albertel 3945: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3946: my %coursehash=&coursedescription($cid);
1.988 raeburn 3947: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3948: my %nothide=();
1.800 albertel 3949: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3950: if ($user !~ /:/) {
3951: $nothide{join(':',split(/[\@]/,$user))}=1;
3952: } else {
3953: $nothide{$user}=1;
3954: }
1.470 www 3955: }
1.1172.2.23 raeburn 3956: my @possdoms = ($coursehash{'domain'});
3957: if ($coursehash{'checkforpriv'}) {
3958: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3959: }
1.351 www 3960: my %returnhash=();
3961: my %dumphash=
3962: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3963: my $now=time;
1.997 raeburn 3964: my %privileged;
1.1000 raeburn 3965: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3966: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3967: if (($tstart) && ($tstart<0)) { next; }
3968: if (($tend) && ($tend<$now)) { next; }
3969: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3970: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3971: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 3972: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3973: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3974: if ($role eq 'cr') { next; }
1.948 raeburn 3975: if ($codes) {
3976: if ($section) { $role .= ':'.$section; }
3977: if ($returnhash{$role}) {
3978: $returnhash{$role}.=','.$username.':'.$domain;
3979: } else {
3980: $returnhash{$role}=$username.':'.$domain;
3981: }
1.351 www 3982: } else {
1.988 raeburn 3983: my $key=&plaintext($role,$crstype);
1.973 bisitz 3984: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3985: if ($returnhash{$key}) {
3986: $returnhash{$key}.=','.$username.':'.$domain;
3987: } else {
3988: $returnhash{$key}=$username.':'.$domain;
3989: }
1.351 www 3990: }
1.948 raeburn 3991: }
1.400 www 3992: return %returnhash;
3993: }
3994:
3995: sub get_my_roles {
1.937 raeburn 3996: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3997: unless (defined($uname)) { $uname=$env{'user.name'}; }
3998: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3999: my (%dumphash,%nothide);
1.1086 raeburn 4000: if ($context eq 'userroles') {
1.1166 raeburn 4001: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4002: } else {
1.1172.2.23 raeburn 4003: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4004: if ($hidepriv) {
4005: my %coursehash=&coursedescription($udom.'_'.$uname);
4006: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4007: if ($user !~ /:/) {
4008: $nothide{join(':',split(/[\@]/,$user))} = 1;
4009: } else {
4010: $nothide{$user} = 1;
4011: }
4012: }
4013: }
1.858 raeburn 4014: }
1.400 www 4015: my %returnhash=();
4016: my $now=time;
1.999 raeburn 4017: my %privileged;
1.800 albertel 4018: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4019: my ($role,$tend,$tstart);
4020: if ($context eq 'userroles') {
1.1149 raeburn 4021: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4022: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4023: } else {
4024: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4025: }
1.400 www 4026: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4027: my $status = 'active';
1.939 raeburn 4028: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4029: $status = 'previous';
4030: }
4031: if (($tstart) && ($now<$tstart)) {
4032: $status = 'future';
4033: }
4034: if (ref($types) eq 'ARRAY') {
4035: if (!grep(/^\Q$status\E$/,@{$types})) {
4036: next;
4037: }
4038: } else {
4039: if ($status ne 'active') {
4040: next;
4041: }
4042: }
1.867 raeburn 4043: my ($rolecode,$username,$domain,$section,$area);
4044: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4045: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4046: (undef,$domain,$username,$section) = split(/\//,$area);
4047: } else {
4048: ($role,$username,$domain,$section) = split(/\:/,$entry);
4049: }
1.832 raeburn 4050: if (ref($roledoms) eq 'ARRAY') {
4051: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4052: next;
4053: }
4054: }
4055: if (ref($roles) eq 'ARRAY') {
4056: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4057: if ($role =~ /^cr\//) {
4058: if (!grep(/^cr$/,@{$roles})) {
4059: next;
4060: }
1.1104 raeburn 4061: } elsif ($role =~ /^gr\//) {
4062: if (!grep(/^gr$/,@{$roles})) {
4063: next;
4064: }
1.922 raeburn 4065: } else {
4066: next;
4067: }
1.832 raeburn 4068: }
1.867 raeburn 4069: }
1.937 raeburn 4070: if ($hidepriv) {
1.1172.2.23 raeburn 4071: my @privroles = ('dc','su');
1.999 raeburn 4072: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4073: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4074: } else {
1.1172.2.23 raeburn 4075: my $possdoms = [$domain];
4076: if (ref($roledoms) eq 'ARRAY') {
4077: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4078: }
1.1172.2.23 raeburn 4079: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4080: if (!$nothide{$username.':'.$domain}) {
4081: next;
4082: }
4083: }
1.937 raeburn 4084: }
4085: }
1.933 raeburn 4086: if ($withsec) {
4087: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4088: $tstart.':'.$tend;
4089: } else {
4090: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4091: }
1.832 raeburn 4092: }
1.373 www 4093: return %returnhash;
1.399 www 4094: }
4095:
4096: # ----------------------------------------------------- Frontpage Announcements
4097: #
4098: #
4099:
4100: sub postannounce {
4101: my ($server,$text)=@_;
1.844 albertel 4102: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4103: unless ($text=~/\w/) { $text=''; }
4104: return &reply('setannounce:'.&escape($text),$server);
4105: }
4106:
4107: sub getannounce {
1.448 albertel 4108:
4109: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4110: my $announcement='';
1.800 albertel 4111: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4112: close($fh);
1.399 www 4113: if ($announcement=~/\w/) {
4114: return
4115: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4116: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4117: } else {
4118: return '';
4119: }
4120: } else {
4121: return '';
4122: }
1.351 www 4123: }
1.353 www 4124:
4125: # ---------------------------------------------------------- Course ID routines
4126: # Deal with domain's nohist_courseid.db files
4127: #
4128:
4129: sub courseidput {
1.921 raeburn 4130: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4131: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4132: my $outcome;
4133: if ($caller eq 'timeonly') {
4134: my $cids = '';
4135: foreach my $item (keys(%$storehash)) {
4136: $cids.=&escape($item).'&';
4137: }
4138: $cids=~s/\&$//;
4139: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4140: $coursehome);
4141: } else {
4142: my $items = '';
4143: foreach my $item (keys(%$storehash)) {
4144: $items.= &escape($item).'='.
4145: &freeze_escape($$storehash{$item}).'&';
4146: }
4147: $items=~s/\&$//;
4148: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4149: $coursehome);
1.918 raeburn 4150: }
4151: if ($outcome eq 'unknown_cmd') {
4152: my $what;
4153: foreach my $cid (keys(%$storehash)) {
4154: $what .= &escape($cid).'=';
1.921 raeburn 4155: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4156: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4157: }
4158: $what =~ s/\:$/&/;
4159: }
4160: $what =~ s/\&$//;
4161: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4162: } else {
4163: return $outcome;
4164: }
1.353 www 4165: }
4166:
4167: sub courseiddump {
1.921 raeburn 4168: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4169: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4170: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4171: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4172: my $as_hash = 1;
4173: my %returnhash;
4174: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4175: my %libserv = &all_library();
4176: foreach my $tryserver (keys(%libserv)) {
4177: if ( ( $hostidflag == 1
4178: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4179: || (!defined($hostidflag)) ) {
4180:
1.918 raeburn 4181: if (($domfilter eq '') ||
4182: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4183: my $rep;
4184: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4185: $rep = &LONCAPA::Lond::dump_course_id_handler(
4186: join(":", (&host_domain($tryserver), $sincefilter,
4187: &escape($descfilter), &escape($instcodefilter),
4188: &escape($ownerfilter), &escape($coursefilter),
4189: &escape($typefilter), &escape($regexp_ok),
4190: $as_hash, &escape($selfenrollonly),
4191: &escape($catfilter), $showhidden, $caller,
4192: &escape($cloner), &escape($cc_clone), $cloneonly,
4193: &escape($createdbefore), &escape($createdafter),
4194: &escape($creationcontext), $domcloner)));
4195: } else {
4196: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4197: $sincefilter.':'.&escape($descfilter).':'.
4198: &escape($instcodefilter).':'.&escape($ownerfilter).
4199: ':'.&escape($coursefilter).':'.&escape($typefilter).
4200: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4201: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4202: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4203: &escape($cc_clone).':'.$cloneonly.':'.
4204: &escape($createdbefore).':'.&escape($createdafter).':'.
4205: &escape($creationcontext).':'.$domcloner,
4206: $tryserver);
4207: }
4208:
1.918 raeburn 4209: my @pairs=split(/\&/,$rep);
4210: foreach my $item (@pairs) {
4211: my ($key,$value)=split(/\=/,$item,2);
4212: $key = &unescape($key);
4213: next if ($key =~ /^error: 2 /);
4214: my $result = &thaw_unescape($value);
4215: if (ref($result) eq 'HASH') {
4216: $returnhash{$key}=$result;
4217: } else {
1.921 raeburn 4218: my @responses = split(/:/,$value);
4219: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4220: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4221: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4222: }
1.1008 raeburn 4223: }
1.353 www 4224: }
4225: }
4226: }
4227: }
4228: return %returnhash;
4229: }
4230:
1.1055 raeburn 4231: sub courselastaccess {
4232: my ($cdom,$cnum,$hostidref) = @_;
4233: my %returnhash;
4234: if ($cdom && $cnum) {
4235: my $chome = &homeserver($cnum,$cdom);
4236: if ($chome ne 'no_host') {
4237: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4238: &extract_lastaccess(\%returnhash,$rep);
4239: }
4240: } else {
4241: if (!$cdom) { $cdom=''; }
4242: my %libserv = &all_library();
4243: foreach my $tryserver (keys(%libserv)) {
4244: if (ref($hostidref) eq 'ARRAY') {
4245: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4246: }
4247: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4248: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4249: &extract_lastaccess(\%returnhash,$rep);
4250: }
4251: }
4252: }
4253: return %returnhash;
4254: }
4255:
4256: sub extract_lastaccess {
4257: my ($returnhash,$rep) = @_;
4258: if (ref($returnhash) eq 'HASH') {
4259: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4260: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4261: $rep eq '') {
4262: my @pairs=split(/\&/,$rep);
4263: foreach my $item (@pairs) {
4264: my ($key,$value)=split(/\=/,$item,2);
4265: $key = &unescape($key);
4266: next if ($key =~ /^error: 2 /);
4267: $returnhash->{$key} = &thaw_unescape($value);
4268: }
4269: }
4270: }
4271: return;
4272: }
4273:
1.658 raeburn 4274: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4275:
4276: sub dcmailput {
1.685 raeburn 4277: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4278: my $status = &Apache::lonnet::critical(
1.740 www 4279: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4280: &escape($message),$server);
1.662 raeburn 4281: return $status;
4282: }
4283:
1.658 raeburn 4284: sub dcmaildump {
4285: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4286: my %returnhash=();
1.846 albertel 4287:
4288: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4289: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4290: &escape($enddate).':';
4291: my @esc_senders=map { &escape($_)} @$senders;
4292: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4293: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4294: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4295: if (($key) && ($value)) {
4296: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4297: }
4298: }
4299: }
4300: return %returnhash;
4301: }
1.662 raeburn 4302: # ---------------------------------------------------------- Domain roles
4303:
4304: sub get_domain_roles {
4305: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4306: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4307: $startdate = '.';
4308: }
1.1018 raeburn 4309: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4310: $enddate = '.';
4311: }
1.922 raeburn 4312: my $rolelist;
4313: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4314: $rolelist = join('&',@{$roles});
1.922 raeburn 4315: }
1.662 raeburn 4316: my %personnel = ();
1.841 albertel 4317:
4318: my %servers = &get_servers($dom,'library');
4319: foreach my $tryserver (keys(%servers)) {
4320: %{$personnel{$tryserver}}=();
4321: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4322: &escape($startdate).':'.
4323: &escape($enddate).':'.
4324: &escape($rolelist), $tryserver))) {
4325: my ($key,$value) = split(/\=/,$line,2);
4326: if (($key) && ($value)) {
4327: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4328: }
4329: }
1.662 raeburn 4330: }
4331: return %personnel;
4332: }
1.658 raeburn 4333:
1.1057 www 4334: # ----------------------------------------------------------- Interval timing
1.149 www 4335:
1.1153 www 4336: {
4337: # Caches needed for speedup of navmaps
4338: # We don't want to cache this for very long at all (5 seconds at most)
4339: #
4340: # The user for whom we cache
4341: my $cachedkey='';
4342: # The cached times for this user
4343: my %cachedtimes=();
4344: # When this was last done
4345: my $cachedtime=();
4346:
4347: sub load_all_first_access {
1.1154 raeburn 4348: my ($uname,$udom)=@_;
1.1156 www 4349: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4350: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4351: return;
4352: }
4353: $cachedtime=time;
4354: $cachedkey=$uname.':'.$udom;
4355: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4356: }
4357:
1.504 albertel 4358: sub get_first_access {
1.1162 raeburn 4359: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4360: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4361: if ($argsymb) { $symb=$argsymb; }
4362: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4363: if ($argmap) { $map = $argmap; }
1.926 albertel 4364: if ($type eq 'course') {
4365: $res='course';
4366: } elsif ($type eq 'map') {
1.588 albertel 4367: $res=&symbread($map);
4368: } else {
4369: $res=$symb;
4370: }
1.1153 www 4371: &load_all_first_access($uname,$udom);
4372: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4373: }
4374:
4375: sub set_first_access {
1.1162 raeburn 4376: my ($type,$interval)=@_;
1.790 albertel 4377: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4378: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4379: if ($type eq 'course') {
4380: $res='course';
4381: } elsif ($type eq 'map') {
1.588 albertel 4382: $res=&symbread($map);
4383: } else {
4384: $res=$symb;
4385: }
1.1153 www 4386: $cachedkey='';
1.1162 raeburn 4387: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4388: if (!$firstaccess) {
1.1162 raeburn 4389: my $start = time;
4390: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4391: $udom,$uname);
4392: if ($putres eq 'ok') {
4393: &put('timerinterval',{"$courseid\0$res"=>$interval},
4394: $udom,$uname);
4395: &appenv(
4396: {
4397: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4398: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4399: }
4400: );
4401: }
4402: return $putres;
1.505 albertel 4403: }
4404: return 'already_set';
1.504 albertel 4405: }
1.1153 www 4406: }
1.1172.2.32 raeburn 4407:
4408: sub checkout {
4409: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4410: my $now=time;
4411: my $lonhost=$perlvar{'lonHostID'};
4412: my $infostr=&escape(
4413: 'CHECKOUTTOKEN&'.
4414: $tuname.'&'.
4415: $tudom.'&'.
4416: $tcrsid.'&'.
4417: $symb.'&'.
4418: $now.'&'.$ENV{'REMOTE_ADDR'});
4419: my $token=&reply('tmpput:'.$infostr,$lonhost);
4420: if ($token=~/^error\:/) {
4421: &logthis("<font color=\"blue\">WARNING: ".
4422: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4423: "</font>");
4424: return '';
4425: }
4426:
4427: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4428: $token=~tr/a-z/A-Z/;
4429:
4430: my %infohash=('resource.0.outtoken' => $token,
4431: 'resource.0.checkouttime' => $now,
4432: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4433:
4434: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4435: return '';
4436: } else {
4437: &logthis("<font color=\"blue\">WARNING: ".
4438: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4439: "</font>");
4440: }
4441:
4442: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4443: &escape('Checkout '.$infostr.' - '.
4444: $token)) ne 'ok') {
4445: return '';
4446: } else {
4447: &logthis("<font color=\"blue\">WARNING: ".
4448: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4449: "</font>");
4450: }
4451: return $token;
4452: }
4453:
4454: # ------------------------------------------------------------ Check in an item
4455:
4456: sub checkin {
4457: my $token=shift;
4458: my $now=time;
4459: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4460: $lonhost=~tr/A-Z/a-z/;
4461: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4462: $dtoken=~s/\W/\_/g;
4463: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4464: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4465:
4466: unless (($tuname) && ($tudom)) {
4467: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4468: return '';
4469: }
4470:
4471: unless (&allowed('mgr',$tcrsid)) {
4472: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4473: $env{'user.name'}.' - '.$env{'user.domain'});
4474: return '';
4475: }
4476:
4477: my %infohash=('resource.0.intoken' => $token,
4478: 'resource.0.checkintime' => $now,
4479: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4480:
4481: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4482: return '';
4483: }
4484:
4485: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4486: &escape('Checkin - '.$token)) ne 'ok') {
4487: return '';
4488: }
4489:
4490: return ($symb,$tuname,$tudom,$tcrsid);
4491: }
4492:
1.110 www 4493: # --------------------------------------------- Set Expire Date for Spreadsheet
4494:
4495: sub expirespread {
4496: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4497: my $cid=$env{'request.course.id'};
1.110 www 4498: if ($cid) {
4499: my $now=time;
4500: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4501: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4502: $env{'course.'.$cid.'.num'}.
1.110 www 4503: ':nohist_expirationdates:'.
4504: &escape($key).'='.$now,
1.620 albertel 4505: $env{'course.'.$cid.'.home'})
1.110 www 4506: }
4507: return 'ok';
1.14 www 4508: }
4509:
1.109 www 4510: # ----------------------------------------------------- Devalidate Spreadsheets
4511:
4512: sub devalidate {
1.325 www 4513: my ($symb,$uname,$udom)=@_;
1.620 albertel 4514: my $cid=$env{'request.course.id'};
1.109 www 4515: if ($cid) {
1.391 matthew 4516: # delete the stored spreadsheets for
4517: # - the student level sheet of this user in course's homespace
4518: # - the assessment level sheet for this resource
4519: # for this user in user's homespace
1.553 albertel 4520: # - current conditional state info
1.325 www 4521: my $key=$uname.':'.$udom.':';
1.109 www 4522: my $status=
1.299 matthew 4523: &del('nohist_calculatedsheets',
1.391 matthew 4524: [$key.'studentcalc:'],
1.620 albertel 4525: $env{'course.'.$cid.'.domain'},
4526: $env{'course.'.$cid.'.num'})
1.133 albertel 4527: .' '.
4528: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4529: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4530: unless ($status eq 'ok ok') {
4531: &logthis('Could not devalidate spreadsheet '.
1.325 www 4532: $uname.' at '.$udom.' for '.
1.109 www 4533: $symb.': '.$status);
1.133 albertel 4534: }
1.553 albertel 4535: &delenv('user.state.'.$cid);
1.109 www 4536: }
4537: }
4538:
1.265 albertel 4539: sub get_scalar {
4540: my ($string,$end) = @_;
4541: my $value;
4542: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4543: $value = $1;
4544: } elsif ($$string =~ s/^([^&]*?)&//) {
4545: $value = $1;
4546: }
4547: return &unescape($value);
4548: }
4549:
4550: sub array2str {
4551: my (@array) = @_;
4552: my $result=&arrayref2str(\@array);
4553: $result=~s/^__ARRAY_REF__//;
4554: $result=~s/__END_ARRAY_REF__$//;
4555: return $result;
4556: }
4557:
1.204 albertel 4558: sub arrayref2str {
4559: my ($arrayref) = @_;
1.265 albertel 4560: my $result='__ARRAY_REF__';
1.204 albertel 4561: foreach my $elem (@$arrayref) {
1.265 albertel 4562: if(ref($elem) eq 'ARRAY') {
4563: $result.=&arrayref2str($elem).'&';
4564: } elsif(ref($elem) eq 'HASH') {
4565: $result.=&hashref2str($elem).'&';
4566: } elsif(ref($elem)) {
4567: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4568: } else {
4569: $result.=&escape($elem).'&';
4570: }
4571: }
4572: $result=~s/\&$//;
1.265 albertel 4573: $result .= '__END_ARRAY_REF__';
1.204 albertel 4574: return $result;
4575: }
4576:
1.168 albertel 4577: sub hash2str {
1.204 albertel 4578: my (%hash) = @_;
4579: my $result=&hashref2str(\%hash);
1.265 albertel 4580: $result=~s/^__HASH_REF__//;
4581: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4582: return $result;
4583: }
4584:
4585: sub hashref2str {
4586: my ($hashref)=@_;
1.265 albertel 4587: my $result='__HASH_REF__';
1.800 albertel 4588: foreach my $key (sort(keys(%$hashref))) {
4589: if (ref($key) eq 'ARRAY') {
4590: $result.=&arrayref2str($key).'=';
4591: } elsif (ref($key) eq 'HASH') {
4592: $result.=&hashref2str($key).'=';
4593: } elsif (ref($key)) {
1.265 albertel 4594: $result.='=';
1.800 albertel 4595: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4596: } else {
1.1132 raeburn 4597: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4598: }
4599:
1.800 albertel 4600: if(ref($hashref->{$key}) eq 'ARRAY') {
4601: $result.=&arrayref2str($hashref->{$key}).'&';
4602: } elsif(ref($hashref->{$key}) eq 'HASH') {
4603: $result.=&hashref2str($hashref->{$key}).'&';
4604: } elsif(ref($hashref->{$key})) {
1.265 albertel 4605: $result.='&';
1.800 albertel 4606: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4607: } else {
1.800 albertel 4608: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4609: }
4610: }
1.168 albertel 4611: $result=~s/\&$//;
1.265 albertel 4612: $result .= '__END_HASH_REF__';
1.168 albertel 4613: return $result;
4614: }
4615:
4616: sub str2hash {
1.265 albertel 4617: my ($string)=@_;
4618: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4619: return %$hash;
4620: }
4621:
4622: sub str2hashref {
1.168 albertel 4623: my ($string) = @_;
1.265 albertel 4624:
4625: my %hash;
4626:
4627: if($string !~ /^__HASH_REF__/) {
4628: if (! ($string eq '' || !defined($string))) {
4629: $hash{'error'}='Not hash reference';
4630: }
4631: return (\%hash, $string);
4632: }
4633:
4634: $string =~ s/^__HASH_REF__//;
4635:
4636: while($string !~ /^__END_HASH_REF__/) {
4637: #key
4638: my $key='';
4639: if($string =~ /^__HASH_REF__/) {
4640: ($key, $string)=&str2hashref($string);
4641: if(defined($key->{'error'})) {
4642: $hash{'error'}='Bad data';
4643: return (\%hash, $string);
4644: }
4645: } elsif($string =~ /^__ARRAY_REF__/) {
4646: ($key, $string)=&str2arrayref($string);
4647: if($key->[0] eq 'Array reference error') {
4648: $hash{'error'}='Bad data';
4649: return (\%hash, $string);
4650: }
4651: } else {
4652: $string =~ s/^(.*?)=//;
1.267 albertel 4653: $key=&unescape($1);
1.265 albertel 4654: }
4655: $string =~ s/^=//;
4656:
4657: #value
4658: my $value='';
4659: if($string =~ /^__HASH_REF__/) {
4660: ($value, $string)=&str2hashref($string);
4661: if(defined($value->{'error'})) {
4662: $hash{'error'}='Bad data';
4663: return (\%hash, $string);
4664: }
4665: } elsif($string =~ /^__ARRAY_REF__/) {
4666: ($value, $string)=&str2arrayref($string);
4667: if($value->[0] eq 'Array reference error') {
4668: $hash{'error'}='Bad data';
4669: return (\%hash, $string);
4670: }
4671: } else {
4672: $value=&get_scalar(\$string,'__END_HASH_REF__');
4673: }
4674: $string =~ s/^&//;
4675:
4676: $hash{$key}=$value;
1.204 albertel 4677: }
1.265 albertel 4678:
4679: $string =~ s/^__END_HASH_REF__//;
4680:
4681: return (\%hash, $string);
1.204 albertel 4682: }
4683:
4684: sub str2array {
1.265 albertel 4685: my ($string)=@_;
4686: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4687: return @$array;
4688: }
4689:
4690: sub str2arrayref {
1.204 albertel 4691: my ($string) = @_;
1.265 albertel 4692: my @array;
4693:
4694: if($string !~ /^__ARRAY_REF__/) {
4695: if (! ($string eq '' || !defined($string))) {
4696: $array[0]='Array reference error';
4697: }
4698: return (\@array, $string);
4699: }
4700:
4701: $string =~ s/^__ARRAY_REF__//;
4702:
4703: while($string !~ /^__END_ARRAY_REF__/) {
4704: my $value='';
4705: if($string =~ /^__HASH_REF__/) {
4706: ($value, $string)=&str2hashref($string);
4707: if(defined($value->{'error'})) {
4708: $array[0] ='Array reference error';
4709: return (\@array, $string);
4710: }
4711: } elsif($string =~ /^__ARRAY_REF__/) {
4712: ($value, $string)=&str2arrayref($string);
4713: if($value->[0] eq 'Array reference error') {
4714: $array[0] ='Array reference error';
4715: return (\@array, $string);
4716: }
4717: } else {
4718: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4719: }
4720: $string =~ s/^&//;
4721:
4722: push(@array, $value);
1.191 harris41 4723: }
1.265 albertel 4724:
4725: $string =~ s/^__END_ARRAY_REF__//;
4726:
4727: return (\@array, $string);
1.168 albertel 4728: }
4729:
1.167 albertel 4730: # -------------------------------------------------------------------Temp Store
4731:
1.168 albertel 4732: sub tmpreset {
4733: my ($symb,$namespace,$domain,$stuname) = @_;
4734: if (!$symb) {
4735: $symb=&symbread();
1.620 albertel 4736: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4737: }
4738: $symb=escape($symb);
4739:
1.620 albertel 4740: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4741: $namespace=~s/\//\_/g;
4742: $namespace=~s/\W//g;
4743:
1.620 albertel 4744: if (!$domain) { $domain=$env{'user.domain'}; }
4745: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4746: if ($domain eq 'public' && $stuname eq 'public') {
4747: $stuname=$ENV{'REMOTE_ADDR'};
4748: }
1.1117 foxr 4749: my $path=LONCAPA::tempdir();
1.168 albertel 4750: my %hash;
4751: if (tie(%hash,'GDBM_File',
4752: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4753: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4754: foreach my $key (keys(%hash)) {
1.180 albertel 4755: if ($key=~ /:$symb/) {
1.168 albertel 4756: delete($hash{$key});
4757: }
4758: }
4759: }
4760: }
4761:
1.167 albertel 4762: sub tmpstore {
1.168 albertel 4763: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4764:
4765: if (!$symb) {
4766: $symb=&symbread();
1.620 albertel 4767: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4768: }
4769: $symb=escape($symb);
4770:
4771: if (!$namespace) {
4772: # I don't think we would ever want to store this for a course.
4773: # it seems this will only be used if we don't have a course.
1.620 albertel 4774: #$namespace=$env{'request.course.id'};
1.168 albertel 4775: #if (!$namespace) {
1.620 albertel 4776: $namespace=$env{'request.state'};
1.168 albertel 4777: #}
4778: }
4779: $namespace=~s/\//\_/g;
4780: $namespace=~s/\W//g;
1.620 albertel 4781: if (!$domain) { $domain=$env{'user.domain'}; }
4782: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4783: if ($domain eq 'public' && $stuname eq 'public') {
4784: $stuname=$ENV{'REMOTE_ADDR'};
4785: }
1.168 albertel 4786: my $now=time;
4787: my %hash;
1.1117 foxr 4788: my $path=LONCAPA::tempdir();
1.168 albertel 4789: if (tie(%hash,'GDBM_File',
4790: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4791: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4792: $hash{"version:$symb"}++;
4793: my $version=$hash{"version:$symb"};
4794: my $allkeys='';
4795: foreach my $key (keys(%$storehash)) {
4796: $allkeys.=$key.':';
1.591 albertel 4797: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4798: }
4799: $hash{"$version:$symb:timestamp"}=$now;
4800: $allkeys.='timestamp';
4801: $hash{"$version:keys:$symb"}=$allkeys;
4802: if (untie(%hash)) {
4803: return 'ok';
4804: } else {
4805: return "error:$!";
4806: }
4807: } else {
4808: return "error:$!";
4809: }
4810: }
1.167 albertel 4811:
1.168 albertel 4812: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4813:
1.168 albertel 4814: sub tmprestore {
4815: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4816:
1.168 albertel 4817: if (!$symb) {
4818: $symb=&symbread();
1.620 albertel 4819: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4820: }
4821: $symb=escape($symb);
4822:
1.620 albertel 4823: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4824:
1.620 albertel 4825: if (!$domain) { $domain=$env{'user.domain'}; }
4826: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4827: if ($domain eq 'public' && $stuname eq 'public') {
4828: $stuname=$ENV{'REMOTE_ADDR'};
4829: }
1.168 albertel 4830: my %returnhash;
4831: $namespace=~s/\//\_/g;
4832: $namespace=~s/\W//g;
4833: my %hash;
1.1117 foxr 4834: my $path=LONCAPA::tempdir();
1.168 albertel 4835: if (tie(%hash,'GDBM_File',
4836: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4837: &GDBM_READER(),0640)) {
1.168 albertel 4838: my $version=$hash{"version:$symb"};
4839: $returnhash{'version'}=$version;
4840: my $scope;
4841: for ($scope=1;$scope<=$version;$scope++) {
4842: my $vkeys=$hash{"$scope:keys:$symb"};
4843: my @keys=split(/:/,$vkeys);
4844: my $key;
4845: $returnhash{"$scope:keys"}=$vkeys;
4846: foreach $key (@keys) {
1.591 albertel 4847: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4848: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4849: }
4850: }
1.168 albertel 4851: if (!(untie(%hash))) {
4852: return "error:$!";
4853: }
4854: } else {
4855: return "error:$!";
4856: }
4857: return %returnhash;
1.167 albertel 4858: }
4859:
1.9 www 4860: # ----------------------------------------------------------------------- Store
4861:
4862: sub store {
1.124 www 4863: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4864: my $home='';
4865:
1.168 albertel 4866: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4867:
1.213 www 4868: $symb=&symbclean($symb);
1.122 albertel 4869: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4870:
1.620 albertel 4871: if (!$domain) { $domain=$env{'user.domain'}; }
4872: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4873:
4874: &devalidate($symb,$stuname,$domain);
1.109 www 4875:
4876: $symb=escape($symb);
1.187 www 4877: if (!$namespace) {
1.620 albertel 4878: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4879: return '';
4880: }
4881: }
1.620 albertel 4882: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4883:
4884: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4885: $$storehash{'host'}=$perlvar{'lonHostID'};
4886:
1.12 www 4887: my $namevalue='';
1.800 albertel 4888: foreach my $key (keys(%$storehash)) {
4889: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4890: }
1.12 www 4891: $namevalue=~s/\&$//;
1.187 www 4892: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4893: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4894: }
4895:
1.47 www 4896: # -------------------------------------------------------------- Critical Store
4897:
4898: sub cstore {
1.124 www 4899: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4900: my $home='';
4901:
1.168 albertel 4902: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4903:
1.213 www 4904: $symb=&symbclean($symb);
1.122 albertel 4905: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4906:
1.620 albertel 4907: if (!$domain) { $domain=$env{'user.domain'}; }
4908: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4909:
4910: &devalidate($symb,$stuname,$domain);
1.109 www 4911:
4912: $symb=escape($symb);
1.187 www 4913: if (!$namespace) {
1.620 albertel 4914: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4915: return '';
4916: }
4917: }
1.620 albertel 4918: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4919:
4920: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4921: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4922:
1.47 www 4923: my $namevalue='';
1.800 albertel 4924: foreach my $key (keys(%$storehash)) {
4925: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4926: }
1.47 www 4927: $namevalue=~s/\&$//;
1.187 www 4928: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4929: return critical
4930: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4931: }
4932:
1.9 www 4933: # --------------------------------------------------------------------- Restore
4934:
4935: sub restore {
1.124 www 4936: my ($symb,$namespace,$domain,$stuname) = @_;
4937: my $home='';
4938:
1.168 albertel 4939: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4940:
1.122 albertel 4941: if (!$symb) {
1.1172.2.26 raeburn 4942: return if ($namespace eq 'courserequests');
4943: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4944: } else {
1.1172.2.26 raeburn 4945: unless ($namespace eq 'courserequests') {
4946: $symb=&escape(&symbclean($symb));
4947: }
1.122 albertel 4948: }
1.188 www 4949: if (!$namespace) {
1.620 albertel 4950: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4951: return '';
4952: }
4953: }
1.620 albertel 4954: if (!$domain) { $domain=$env{'user.domain'}; }
4955: if (!$stuname) { $stuname=$env{'user.name'}; }
4956: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4957: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4958:
1.12 www 4959: my %returnhash=();
1.800 albertel 4960: foreach my $line (split(/\&/,$answer)) {
4961: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4962: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4963: }
1.75 www 4964: my $version;
4965: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4966: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4967: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4968: }
1.75 www 4969: }
1.13 www 4970: return %returnhash;
1.34 www 4971: }
4972:
4973: # ---------------------------------------------------------- Course Description
1.1118 foxr 4974: #
4975: #
1.34 www 4976:
4977: sub coursedescription {
1.731 albertel 4978: my ($courseid,$args)=@_;
1.34 www 4979: $courseid=~s/^\///;
1.49 www 4980: $courseid=~s/\_/\//g;
1.34 www 4981: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4982: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4983: my $normalid=$cdomain.'_'.$cnum;
4984: # need to always cache even if we get errors otherwise we keep
4985: # trying and trying and trying to get the course description.
4986: my %envhash=();
4987: my %returnhash=();
1.731 albertel 4988:
4989: my $expiretime=600;
4990: if ($env{'request.course.id'} eq $normalid) {
4991: $expiretime=120;
4992: }
4993:
4994: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4995: if (!$args->{'freshen_cache'}
4996: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4997: foreach my $key (keys(%env)) {
4998: next if ($key !~ /^\Q$prefix\E(.*)/);
4999: my ($setting) = $1;
5000: $returnhash{$setting} = $env{$key};
5001: }
5002: return %returnhash;
5003: }
5004:
1.1118 foxr 5005: # get the data again
5006:
1.731 albertel 5007: if (!$args->{'one_time'}) {
5008: $envhash{'course.'.$normalid.'.last_cache'}=time;
5009: }
1.811 albertel 5010:
1.34 www 5011: if ($chome ne 'no_host') {
1.302 albertel 5012: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5013: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5014: my $username = $env{'user.name'}; # Defult username
5015: if(defined $args->{'user'}) {
5016: $username = $args->{'user'};
5017: }
1.129 albertel 5018: $returnhash{'home'}= $chome;
5019: $returnhash{'domain'} = $cdomain;
5020: $returnhash{'num'} = $cnum;
1.741 raeburn 5021: if (!defined($returnhash{'type'})) {
5022: $returnhash{'type'} = 'Course';
5023: }
1.130 albertel 5024: while (my ($name,$value) = each %returnhash) {
1.53 www 5025: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5026: }
1.270 www 5027: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5028: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5029: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5030: $envhash{'course.'.$normalid.'.home'}=$chome;
5031: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5032: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5033: }
5034: }
1.731 albertel 5035: if (!$args->{'one_time'}) {
1.949 raeburn 5036: &appenv(\%envhash);
1.731 albertel 5037: }
1.302 albertel 5038: return %returnhash;
1.461 www 5039: }
5040:
1.1080 raeburn 5041: sub update_released_required {
5042: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5043: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5044: $cid = $env{'request.course.id'};
5045: $cdom = $env{'course.'.$cid.'.domain'};
5046: $cnum = $env{'course.'.$cid.'.num'};
5047: $chome = $env{'course.'.$cid.'.home'};
5048: }
5049: if ($needsrelease) {
5050: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5051: my $needsupdate;
5052: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5053: $needsupdate = 1;
5054: } else {
5055: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5056: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5057: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5058: $needsupdate = 1;
5059: }
5060: }
5061: if ($needsupdate) {
5062: my %needshash = (
5063: 'internal.releaserequired' => $needsrelease,
5064: );
5065: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5066: if ($putresult eq 'ok') {
5067: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5068: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5069: if (ref($crsinfo{$cid}) eq 'HASH') {
5070: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5071: &courseidput($cdom,\%crsinfo,$chome,'notime');
5072: }
5073: }
5074: }
5075: }
5076: return;
5077: }
5078:
1.461 www 5079: # -------------------------------------------------See if a user is privileged
5080:
5081: sub privileged {
1.1172.2.23 raeburn 5082: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5083: my $now = time;
1.1172.2.23 raeburn 5084: my $roles;
5085: if (ref($possroles) eq 'ARRAY') {
5086: $roles = $possroles;
5087: } else {
5088: $roles = ['dc','su'];
5089: }
5090: if (ref($possdomains) eq 'ARRAY') {
5091: my %privileged = &privileged_by_domain($possdomains,$roles);
5092: foreach my $dom (@{$possdomains}) {
5093: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5094: (ref($privileged{$dom}) eq 'HASH')) {
5095: foreach my $role (@{$roles}) {
5096: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5097: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5098: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5099: return 1 unless (($end && $end < $now) ||
5100: ($start && $start > $now));
5101: }
5102: }
5103: }
5104: }
5105: }
5106: } else {
5107: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5108: my $now = time;
1.1170 droeschl 5109:
1.1172.2.23 raeburn 5110: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5111: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5112: if (grep(/^\Q$trole\E$/,@{$roles})) {
5113: return 1 unless ($tend && $tend < $now)
5114: or ($tstart && $tstart > $now);
1.1170 droeschl 5115: }
1.1172.2.23 raeburn 5116: }
5117: }
1.461 www 5118: return 0;
1.9 www 5119: }
1.1 albertel 5120:
1.1172.2.23 raeburn 5121: sub privileged_by_domain {
5122: my ($domains,$roles) = @_;
5123: my %privileged = ();
5124: my $cachetime = 60*60*24;
5125: my $now = time;
5126: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5127: return %privileged;
5128: }
5129: foreach my $dom (@{$domains}) {
5130: next if (ref($privileged{$dom}) eq 'HASH');
5131: my $needroles;
5132: foreach my $role (@{$roles}) {
5133: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5134: if (defined($cached)) {
5135: if (ref($result) eq 'HASH') {
5136: $privileged{$dom}{$role} = $result;
5137: }
5138: } else {
5139: $needroles = 1;
5140: }
5141: }
5142: if ($needroles) {
5143: my %dompersonnel = &get_domain_roles($dom,$roles);
5144: $privileged{$dom} = {};
5145: foreach my $server (keys(%dompersonnel)) {
5146: if (ref($dompersonnel{$server}) eq 'HASH') {
5147: foreach my $item (keys(%{$dompersonnel{$server}})) {
5148: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5149: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5150: next if ($end && $end < $now);
5151: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5152: $dompersonnel{$server}{$item};
5153: }
5154: }
5155: }
5156: if (ref($privileged{$dom}) eq 'HASH') {
5157: foreach my $role (@{$roles}) {
5158: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5159: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5160: } else {
5161: my %hash = ();
5162: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5163: }
5164: }
5165: }
5166: }
5167: }
5168: return %privileged;
5169: }
5170:
1.103 harris41 5171: # -------------------------------------------------------- Get user privileges
1.11 www 5172:
5173: sub rolesinit {
1.1169 droeschl 5174: my ($domain, $username) = @_;
5175: my %userroles = ('user.login.time' => time);
5176: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5177:
5178: # firstaccess and timerinterval are related to timed maps/resources.
5179: # also, blocking can be triggered by an activating timer
5180: # it's saved in the user's %env.
5181: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5182: my %timerinterval = &dump('timerinterval', $domain, $username);
5183: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5184: %timerintchk, %timerintenv);
5185:
1.1162 raeburn 5186: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5187: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5188: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5189: }
1.1169 droeschl 5190:
1.1162 raeburn 5191: foreach my $key (keys(%timerinterval)) {
5192: my ($cid,$rest) = split(/\0/,$key);
5193: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5194: }
1.1169 droeschl 5195:
1.11 www 5196: my %allroles=();
1.1162 raeburn 5197: my %allgroups=();
1.11 www 5198:
1.1169 droeschl 5199: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5200: my $role = $rolesdump{$area};
5201: $area =~ s/\_\w\w$//;
5202:
5203: my ($trole, $tend, $tstart, $group_privs);
5204:
5205: if ($role =~ /^cr/) {
5206: # Custom role, defined by a user
5207: # e.g., user.role.cr/msu/smith/mynewrole
5208: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5209: $trole = $1;
5210: ($tend, $tstart) = split('_', $2);
5211: } else {
5212: $trole = $role;
5213: }
5214: } elsif ($role =~ m|^gr/|) {
5215: # Role of member in a group, defined within a course/community
5216: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5217: ($trole, $tend, $tstart) = split(/_/, $role);
5218: next if $tstart eq '-1';
5219: ($trole, $group_privs) = split(/\//, $trole);
5220: $group_privs = &unescape($group_privs);
5221: } else {
5222: # Just a normal role, defined in roles.tab
5223: ($trole, $tend, $tstart) = split(/_/,$role);
5224: }
5225:
5226: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5227: $username);
5228: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5229:
5230: # role expired or not available yet?
5231: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5232: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5233:
5234: next if $area eq '' or $trole eq '';
5235:
5236: my $spec = "$trole.$area";
5237: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5238:
5239: if ($trole =~ /^cr\//) {
5240: # Custom role, defined by a user
5241: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5242: } elsif ($trole eq 'gr') {
5243: # Role of a member in a group, defined within a course/community
5244: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5245: next;
5246: } else {
5247: # Normal role, defined in roles.tab
5248: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5249: }
5250:
5251: my $cid = $tdomain.'_'.$trest;
5252: unless ($firstaccchk{$cid}) {
5253: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5254: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5255: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5256: $coursetimerstarts{$cid}{$item};
5257: }
5258: }
5259: $firstaccchk{$cid} = 1;
5260: }
5261: unless ($timerintchk{$cid}) {
5262: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5263: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5264: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5265: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5266: }
1.12 www 5267: }
1.1169 droeschl 5268: $timerintchk{$cid} = 1;
1.191 harris41 5269: }
1.11 www 5270: }
1.1169 droeschl 5271:
5272: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5273: \%allroles, \%allgroups);
5274: $env{'user.adv'} = $userroles{'user.adv'};
5275:
1.1162 raeburn 5276: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5277: }
5278:
1.567 raeburn 5279: sub set_arearole {
1.1172.2.19 raeburn 5280: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5281: unless ($nolog) {
1.567 raeburn 5282: # log the associated role with the area
1.1172.2.19 raeburn 5283: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5284: }
1.743 albertel 5285: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5286: }
5287:
5288: sub custom_roleprivs {
5289: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5290: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5291: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5292: if (&hostname($homsvr) ne '') {
1.567 raeburn 5293: my ($rdummy,$roledef)=
5294: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5295: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5296: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5297: if (defined($syspriv)) {
1.1043 raeburn 5298: if ($trest =~ /^$match_community$/) {
5299: $syspriv =~ s/bre\&S//;
5300: }
1.567 raeburn 5301: $$allroles{'cm./'}.=':'.$syspriv;
5302: $$allroles{$spec.'./'}.=':'.$syspriv;
5303: }
5304: if ($tdomain ne '') {
5305: if (defined($dompriv)) {
5306: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5307: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5308: }
5309: if (($trest ne '') && (defined($coursepriv))) {
5310: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5311: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5312: }
5313: }
5314: }
5315: }
5316: }
5317:
1.678 raeburn 5318: sub group_roleprivs {
5319: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5320: my $access = 1;
5321: my $now = time;
5322: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5323: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5324: if ($access) {
1.811 albertel 5325: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5326: $$allgroups{$course}{$group} .=':'.$group_privs;
5327: }
5328: }
1.567 raeburn 5329:
5330: sub standard_roleprivs {
5331: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5332: if (defined($pr{$trole.':s'})) {
5333: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5334: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5335: }
5336: if ($tdomain ne '') {
5337: if (defined($pr{$trole.':d'})) {
5338: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5339: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5340: }
5341: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5342: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5343: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5344: }
5345: }
5346: }
5347:
5348: sub set_userprivs {
1.1064 raeburn 5349: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5350: my $author=0;
5351: my $adv=0;
1.678 raeburn 5352: my %grouproles = ();
5353: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5354: my @groupkeys;
1.1000 raeburn 5355: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5356: push(@groupkeys,$role);
5357: }
5358: if (ref($groups_roles) eq 'HASH') {
5359: foreach my $key (keys(%{$groups_roles})) {
5360: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5361: push(@groupkeys,$key);
5362: }
5363: }
5364: }
5365: if (@groupkeys > 0) {
5366: foreach my $role (@groupkeys) {
5367: my ($trole,$area,$sec,$extendedarea);
5368: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5369: $trole = $1;
5370: $area = $2;
5371: $sec = $3;
5372: $extendedarea = $area.$sec;
5373: if (exists($$allgroups{$area})) {
5374: foreach my $group (keys(%{$$allgroups{$area}})) {
5375: my $spec = $trole.'.'.$extendedarea;
5376: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5377: $$allgroups{$area}{$group};
1.1064 raeburn 5378: }
1.678 raeburn 5379: }
5380: }
5381: }
5382: }
5383: }
1.800 albertel 5384: foreach my $group (keys(%grouproles)) {
5385: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5386: }
1.800 albertel 5387: foreach my $role (keys(%{$allroles})) {
5388: my %thesepriv;
1.941 raeburn 5389: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5390: foreach my $item (split(/:/,$$allroles{$role})) {
5391: if ($item ne '') {
5392: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5393: if ($restrictions eq '') {
5394: $thesepriv{$privilege}='F';
5395: } elsif ($thesepriv{$privilege} ne 'F') {
5396: $thesepriv{$privilege}.=$restrictions;
5397: }
5398: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5399: }
5400: }
5401: my $thesestr='';
1.1104 raeburn 5402: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5403: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5404: }
5405: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5406: }
5407: return ($author,$adv);
5408: }
5409:
1.994 raeburn 5410: sub role_status {
1.1104 raeburn 5411: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5412: my @pwhere = ();
5413: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5414: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5415: unless (!defined($$role) || $$role eq '') {
5416: $$where=join('.',@pwhere);
5417: $$trolecode=$$role.'.'.$$where;
5418: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5419: $$tstatus='is';
1.1104 raeburn 5420: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5421: $$tstatus='future';
1.1034 raeburn 5422: if ($$tstart<$now) {
5423: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5424: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5425: my (%allroles,%allgroups,$group_privs,
5426: %groups_roles,@rolecodes);
1.1002 raeburn 5427: my %userroles = (
5428: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5429: );
1.1064 raeburn 5430: @rolecodes = ('cm');
1.1002 raeburn 5431: my $spec=$$role.'.'.$$where;
5432: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5433: if ($$role =~ /^cr\//) {
5434: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5435: push(@rolecodes,'cr');
1.1002 raeburn 5436: } elsif ($$role eq 'gr') {
1.1064 raeburn 5437: push(@rolecodes,$$role);
1.1002 raeburn 5438: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5439: $env{'user.name'});
1.1064 raeburn 5440: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5441: (undef,my $group_privs) = split(/\//,$trole);
5442: $group_privs = &unescape($group_privs);
5443: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5444: 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 5445: &get_groups_roles($tdomain,$trest,
5446: \%course_roles,\@rolecodes,
5447: \%groups_roles);
1.1002 raeburn 5448: } else {
1.1064 raeburn 5449: push(@rolecodes,$$role);
1.1002 raeburn 5450: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5451: }
1.1064 raeburn 5452: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5453: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5454: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5455: }
5456: }
1.1034 raeburn 5457: $$tstatus = 'is';
1.1002 raeburn 5458: }
1.994 raeburn 5459: }
5460: if ($$tend) {
1.1104 raeburn 5461: if ($$tend<$update) {
1.994 raeburn 5462: $$tstatus='expired';
5463: } elsif ($$tend<$now) {
5464: $$tstatus='will_not';
5465: }
5466: }
5467: }
5468: }
5469: }
5470:
1.1104 raeburn 5471: sub get_groups_roles {
5472: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5473: return unless((ref($cdom_courseroles) eq 'HASH') &&
5474: (ref($rolecodes) eq 'ARRAY') &&
5475: (ref($groups_roles) eq 'HASH'));
5476: if (keys(%{$cdom_courseroles}) > 0) {
5477: my ($cnum) = ($rest =~ /^($match_courseid)/);
5478: if ($cdom ne '' && $cnum ne '') {
5479: foreach my $key (keys(%{$cdom_courseroles})) {
5480: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5481: my $crsrole = $1;
5482: my $crssec = $2;
5483: if ($crsrole =~ /^cr/) {
5484: unless (grep(/^cr$/,@{$rolecodes})) {
5485: push(@{$rolecodes},'cr');
5486: }
5487: } else {
5488: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5489: push(@{$rolecodes},$crsrole);
5490: }
5491: }
5492: my $rolekey = "$crsrole./$cdom/$cnum";
5493: if ($crssec ne '') {
5494: $rolekey .= "/$crssec";
5495: }
5496: $rolekey .= './';
5497: $groups_roles->{$rolekey} = $rolecodes;
5498: }
5499: }
5500: }
5501: }
5502: return;
5503: }
5504:
5505: sub delete_env_groupprivs {
5506: my ($where,$courseroles,$possroles) = @_;
5507: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5508: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5509: unless (ref($courseroles->{$udom}) eq 'HASH') {
5510: %{$courseroles->{$udom}} =
5511: &get_my_roles('','','userroles',['active'],
5512: $possroles,[$udom],1);
5513: }
5514: if (ref($courseroles->{$udom}) eq 'HASH') {
5515: foreach my $item (keys(%{$courseroles->{$udom}})) {
5516: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5517: my $area = '/'.$cdom.'/'.$cnum;
5518: my $privkey = "user.priv.$crsrole.$area";
5519: if ($crssec ne '') {
5520: $privkey .= '/'.$crssec;
5521: }
5522: $privkey .= ".$area/$group";
5523: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5524: }
5525: }
5526: return;
5527: }
5528:
1.994 raeburn 5529: sub check_adhoc_privs {
1.1104 raeburn 5530: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5531: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5532: my $setprivs;
1.994 raeburn 5533: if ($env{$cckey}) {
5534: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5535: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5536: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5537: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5538: $setprivs = 1;
1.994 raeburn 5539: }
5540: } else {
1.1088 raeburn 5541: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5542: $setprivs = 1;
1.994 raeburn 5543: }
1.1172.2.9 raeburn 5544: return $setprivs;
1.994 raeburn 5545: }
5546:
5547: sub set_adhoc_privileges {
5548: # role can be cc or ca
1.1088 raeburn 5549: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5550: my $area = '/'.$dcdom.'/'.$pickedcourse;
5551: my $spec = $role.'.'.$area;
5552: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5553: $env{'user.name'},1);
1.994 raeburn 5554: my %ccrole = ();
5555: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5556: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5557: &appenv(\%userroles,[$role,'cm']);
5558: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5559: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5560: &appenv( {'request.role' => $spec,
5561: 'request.role.domain' => $dcdom,
5562: 'request.course.sec' => ''
5563: }
5564: );
5565: my $tadv=0;
5566: if (&allowed('adv') eq 'F') { $tadv=1; }
5567: &appenv({'request.role.adv' => $tadv});
5568: }
1.994 raeburn 5569: }
5570:
1.12 www 5571: # --------------------------------------------------------------- get interface
5572:
5573: sub get {
1.131 albertel 5574: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5575: my $items='';
1.800 albertel 5576: foreach my $item (@$storearr) {
5577: $items.=&escape($item).'&';
1.191 harris41 5578: }
1.12 www 5579: $items=~s/\&$//;
1.620 albertel 5580: if (!$udomain) { $udomain=$env{'user.domain'}; }
5581: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5582: my $uhome=&homeserver($uname,$udomain);
5583:
1.133 albertel 5584: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5585: my @pairs=split(/\&/,$rep);
1.273 albertel 5586: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5587: return @pairs;
5588: }
1.15 www 5589: my %returnhash=();
1.42 www 5590: my $i=0;
1.800 albertel 5591: foreach my $item (@$storearr) {
5592: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5593: $i++;
1.191 harris41 5594: }
1.15 www 5595: return %returnhash;
1.27 www 5596: }
5597:
5598: # --------------------------------------------------------------- del interface
5599:
5600: sub del {
1.133 albertel 5601: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5602: my $items='';
1.800 albertel 5603: foreach my $item (@$storearr) {
5604: $items.=&escape($item).'&';
1.191 harris41 5605: }
1.984 neumanie 5606:
1.27 www 5607: $items=~s/\&$//;
1.620 albertel 5608: if (!$udomain) { $udomain=$env{'user.domain'}; }
5609: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5610: my $uhome=&homeserver($uname,$udomain);
5611: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5612: }
5613:
5614: # -------------------------------------------------------------- dump interface
5615:
1.1172.2.22 raeburn 5616: sub unserialize {
5617: my ($rep, $escapedkeys) = @_;
5618:
5619: return {} if $rep =~ /^error/;
5620:
5621: my %returnhash=();
5622: foreach my $item (split(/\&/,$rep)) {
5623: my ($key, $value) = split(/=/, $item, 2);
5624: $key = unescape($key) unless $escapedkeys;
5625: next if $key =~ /^error: 2 /;
5626: $returnhash{$key} = &thaw_unescape($value);
5627: }
5628: return \%returnhash;
5629: }
5630:
5631: # see Lond::dump_with_regexp
5632: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5633: sub dump {
1.1172.2.22 raeburn 5634: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5635: if (!$udomain) { $udomain=$env{'user.domain'}; }
5636: if (!$uname) { $uname=$env{'user.name'}; }
5637: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5638:
1.1172.2.22 raeburn 5639: my $reply;
5640: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5641: # user is hosted on this machine
5642: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5643: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5644: return %{&unserialize($reply, $escapedkeys)};
5645: }
1.755 albertel 5646: if ($regexp) {
5647: $regexp=&escape($regexp);
5648: } else {
5649: $regexp='.';
5650: }
1.1166 raeburn 5651: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5652: my @pairs=split(/\&/,$rep);
5653: my %returnhash=();
1.1098 foxr 5654: if (!($rep =~ /^error/ )) {
5655: foreach my $item (@pairs) {
5656: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5657: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5658: next if ($key =~ /^error: 2 /);
5659: $returnhash{$key}=&thaw_unescape($value);
5660: }
1.755 albertel 5661: }
5662: return %returnhash;
1.407 www 5663: }
5664:
1.1098 foxr 5665:
1.717 albertel 5666: # --------------------------------------------------------- dumpstore interface
5667:
5668: sub dumpstore {
5669: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5670: # same as dump but keys must be escaped. They may contain colon separated
5671: # lists of values that may themself contain colons (e.g. symbs).
5672: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5673: }
5674:
1.407 www 5675: # -------------------------------------------------------------- keys interface
5676:
5677: sub getkeys {
5678: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5679: if (!$udomain) { $udomain=$env{'user.domain'}; }
5680: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5681: my $uhome=&homeserver($uname,$udomain);
5682: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5683: my @keyarray=();
1.800 albertel 5684: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5685: next if ($key =~ /^error: 2 /);
1.800 albertel 5686: push(@keyarray,&unescape($key));
1.407 www 5687: }
5688: return @keyarray;
1.318 matthew 5689: }
5690:
1.319 matthew 5691: # --------------------------------------------------------------- currentdump
5692: sub currentdump {
1.328 matthew 5693: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5694: $courseid = $env{'request.course.id'} if (! defined($courseid));
5695: $sdom = $env{'user.domain'} if (! defined($sdom));
5696: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5697: my $uhome = &homeserver($sname,$sdom);
5698: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5699: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5700: #
1.318 matthew 5701: my %returnhash=();
1.319 matthew 5702: #
5703: if ($rep eq "unknown_cmd") {
5704: # an old lond will not know currentdump
5705: # Do a dump and make it look like a currentdump
1.822 albertel 5706: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5707: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5708: my %hash = @tmp;
5709: @tmp=();
1.424 matthew 5710: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5711: } else {
5712: my @pairs=split(/\&/,$rep);
1.800 albertel 5713: foreach my $pair (@pairs) {
5714: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5715: my ($symb,$param) = split(/:/,$key);
5716: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5717: &thaw_unescape($value);
1.319 matthew 5718: }
1.191 harris41 5719: }
1.12 www 5720: return %returnhash;
1.424 matthew 5721: }
5722:
5723: sub convert_dump_to_currentdump{
5724: my %hash = %{shift()};
5725: my %returnhash;
5726: # Code ripped from lond, essentially. The only difference
5727: # here is the unescaping done by lonnet::dump(). Conceivably
5728: # we might run in to problems with parameter names =~ /^v\./
5729: while (my ($key,$value) = each(%hash)) {
5730: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5731: $symb = &unescape($symb);
5732: $param = &unescape($param);
1.424 matthew 5733: next if ($v eq 'version' || $symb eq 'keys');
5734: next if (exists($returnhash{$symb}) &&
5735: exists($returnhash{$symb}->{$param}) &&
5736: $returnhash{$symb}->{'v.'.$param} > $v);
5737: $returnhash{$symb}->{$param}=$value;
5738: $returnhash{$symb}->{'v.'.$param}=$v;
5739: }
5740: #
5741: # Remove all of the keys in the hashes which keep track of
5742: # the version of the parameter.
5743: while (my ($symb,$param_hash) = each(%returnhash)) {
5744: # use a foreach because we are going to delete from the hash.
5745: foreach my $key (keys(%$param_hash)) {
5746: delete($param_hash->{$key}) if ($key =~ /^v\./);
5747: }
5748: }
5749: return \%returnhash;
1.12 www 5750: }
5751:
1.627 albertel 5752: # ------------------------------------------------------ critical inc interface
5753:
5754: sub cinc {
5755: return &inc(@_,'critical');
5756: }
5757:
1.449 matthew 5758: # --------------------------------------------------------------- inc interface
5759:
5760: sub inc {
1.627 albertel 5761: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5762: if (!$udomain) { $udomain=$env{'user.domain'}; }
5763: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5764: my $uhome=&homeserver($uname,$udomain);
5765: my $items='';
5766: if (! ref($store)) {
5767: # got a single value, so use that instead
5768: $items = &escape($store).'=&';
5769: } elsif (ref($store) eq 'SCALAR') {
5770: $items = &escape($$store).'=&';
5771: } elsif (ref($store) eq 'ARRAY') {
5772: $items = join('=&',map {&escape($_);} @{$store});
5773: } elsif (ref($store) eq 'HASH') {
5774: while (my($key,$value) = each(%{$store})) {
5775: $items.= &escape($key).'='.&escape($value).'&';
5776: }
5777: }
5778: $items=~s/\&$//;
1.627 albertel 5779: if ($critical) {
5780: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5781: } else {
5782: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5783: }
1.449 matthew 5784: }
5785:
1.12 www 5786: # --------------------------------------------------------------- put interface
5787:
5788: sub put {
1.134 albertel 5789: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5790: if (!$udomain) { $udomain=$env{'user.domain'}; }
5791: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5792: my $uhome=&homeserver($uname,$udomain);
1.12 www 5793: my $items='';
1.800 albertel 5794: foreach my $item (keys(%$storehash)) {
5795: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5796: }
1.12 www 5797: $items=~s/\&$//;
1.134 albertel 5798: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5799: }
5800:
1.631 albertel 5801: # ------------------------------------------------------------ newput interface
5802:
5803: sub newput {
5804: my ($namespace,$storehash,$udomain,$uname)=@_;
5805: if (!$udomain) { $udomain=$env{'user.domain'}; }
5806: if (!$uname) { $uname=$env{'user.name'}; }
5807: my $uhome=&homeserver($uname,$udomain);
5808: my $items='';
5809: foreach my $key (keys(%$storehash)) {
5810: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5811: }
5812: $items=~s/\&$//;
5813: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5814: }
5815:
5816: # --------------------------------------------------------- putstore interface
5817:
1.524 raeburn 5818: sub putstore {
1.715 albertel 5819: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5820: if (!$udomain) { $udomain=$env{'user.domain'}; }
5821: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5822: my $uhome=&homeserver($uname,$udomain);
5823: my $items='';
1.715 albertel 5824: foreach my $key (keys(%$storehash)) {
5825: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5826: }
1.715 albertel 5827: $items=~s/\&$//;
1.716 albertel 5828: my $esc_symb=&escape($symb);
5829: my $esc_v=&escape($version);
1.715 albertel 5830: my $reply =
1.716 albertel 5831: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5832: $uhome);
5833: if ($reply eq 'unknown_cmd') {
1.716 albertel 5834: # gfall back to way things use to be done
1.715 albertel 5835: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5836: $uname);
1.524 raeburn 5837: }
1.715 albertel 5838: return $reply;
5839: }
5840:
5841: sub old_putstore {
1.716 albertel 5842: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5843: if (!$udomain) { $udomain=$env{'user.domain'}; }
5844: if (!$uname) { $uname=$env{'user.name'}; }
5845: my $uhome=&homeserver($uname,$udomain);
5846: my %newstorehash;
1.800 albertel 5847: foreach my $item (keys(%$storehash)) {
5848: my $key = $version.':'.&escape($symb).':'.$item;
5849: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5850: }
5851: my $items='';
5852: my %allitems = ();
1.800 albertel 5853: foreach my $item (keys(%newstorehash)) {
5854: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5855: my $key = $1.':keys:'.$2;
5856: $allitems{$key} .= $3.':';
5857: }
1.800 albertel 5858: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5859: }
1.800 albertel 5860: foreach my $item (keys(%allitems)) {
5861: $allitems{$item} =~ s/\:$//;
5862: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5863: }
5864: $items=~s/\&$//;
5865: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5866: }
5867:
1.47 www 5868: # ------------------------------------------------------ critical put interface
5869:
5870: sub cput {
1.134 albertel 5871: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5872: if (!$udomain) { $udomain=$env{'user.domain'}; }
5873: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5874: my $uhome=&homeserver($uname,$udomain);
1.47 www 5875: my $items='';
1.800 albertel 5876: foreach my $item (keys(%$storehash)) {
5877: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5878: }
1.47 www 5879: $items=~s/\&$//;
1.134 albertel 5880: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5881: }
5882:
5883: # -------------------------------------------------------------- eget interface
5884:
5885: sub eget {
1.133 albertel 5886: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5887: my $items='';
1.800 albertel 5888: foreach my $item (@$storearr) {
5889: $items.=&escape($item).'&';
1.191 harris41 5890: }
1.12 www 5891: $items=~s/\&$//;
1.620 albertel 5892: if (!$udomain) { $udomain=$env{'user.domain'}; }
5893: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5894: my $uhome=&homeserver($uname,$udomain);
5895: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5896: my @pairs=split(/\&/,$rep);
5897: my %returnhash=();
1.42 www 5898: my $i=0;
1.800 albertel 5899: foreach my $item (@$storearr) {
5900: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5901: $i++;
1.191 harris41 5902: }
1.12 www 5903: return %returnhash;
5904: }
5905:
1.667 albertel 5906: # ------------------------------------------------------------ tmpput interface
5907: sub tmpput {
1.802 raeburn 5908: my ($storehash,$server,$context)=@_;
1.667 albertel 5909: my $items='';
1.800 albertel 5910: foreach my $item (keys(%$storehash)) {
5911: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5912: }
5913: $items=~s/\&$//;
1.802 raeburn 5914: if (defined($context)) {
5915: $items .= ':'.&escape($context);
5916: }
1.667 albertel 5917: return &reply("tmpput:$items",$server);
5918: }
5919:
5920: # ------------------------------------------------------------ tmpget interface
5921: sub tmpget {
1.688 albertel 5922: my ($token,$server)=@_;
5923: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5924: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5925: my %returnhash;
5926: foreach my $item (split(/\&/,$rep)) {
5927: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5928: next if ($key =~ /^error: 2 /);
1.667 albertel 5929: $returnhash{&unescape($key)}=&thaw_unescape($value);
5930: }
5931: return %returnhash;
5932: }
5933:
1.1113 raeburn 5934: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5935: sub tmpdel {
5936: my ($token,$server)=@_;
5937: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5938: return &reply("tmpdel:$token",$server);
5939: }
5940:
1.1172.2.13 raeburn 5941: # ------------------------------------------------------------ get_timebased_id
5942:
5943: sub get_timebased_id {
5944: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5945: $maxtries) = @_;
5946: my ($newid,$error,$dellock);
5947: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5948: return ('','ok','invalid call to get suffix');
5949: }
5950:
5951: # set defaults for any optional args for which values were not supplied
5952: if ($who eq '') {
5953: $who = $env{'user.name'}.':'.$env{'user.domain'};
5954: }
5955: if (!$locktries) {
5956: $locktries = 3;
5957: }
5958: if (!$maxtries) {
5959: $maxtries = 10;
5960: }
5961:
5962: if (($cdom eq '') || ($cnum eq '')) {
5963: if ($env{'request.course.id'}) {
5964: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5965: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5966: }
5967: if (($cdom eq '') || ($cnum eq '')) {
5968: return ('','ok','call to get suffix not in course context');
5969: }
5970: }
5971:
5972: # construct locking item
5973: my $lockhash = {
5974: $prefix."\0".'locked_'.$keyid => $who,
5975: };
5976: my $tries = 0;
5977:
5978: # attempt to get lock on nohist_$namespace file
5979: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5980: while (($gotlock ne 'ok') && $tries <$locktries) {
5981: $tries ++;
5982: sleep 1;
5983: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5984: }
5985:
5986: # attempt to get unique identifier, based on current timestamp
5987: if ($gotlock eq 'ok') {
5988: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5989: my $id = time;
5990: $newid = $id;
5991: my $idtries = 0;
5992: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5993: if ($idtype eq 'concat') {
5994: $newid = $id.$idtries;
5995: } else {
5996: $newid ++;
5997: }
5998: $idtries ++;
5999: }
6000: if (!exists($inuse{$prefix."\0".$newid})) {
6001: my %new_item = (
6002: $prefix."\0".$newid => $who,
6003: );
6004: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6005: $cdom,$cnum);
6006: if ($putresult ne 'ok') {
6007: undef($newid);
6008: $error = 'error saving new item: '.$putresult;
6009: }
6010: } else {
6011: $error = ('error: no unique suffix available for the new item ');
6012: }
6013: # remove lock
6014: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6015: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6016: } else {
6017: $error = "error: could not obtain lockfile\n";
6018: $dellock = 'ok';
6019: }
6020: return ($newid,$dellock,$error);
6021: }
6022:
1.765 albertel 6023: # -------------------------------------------------- portfolio access checking
6024:
6025: sub portfolio_access {
1.766 albertel 6026: my ($requrl) = @_;
1.765 albertel 6027: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6028: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6029: if ($result) {
6030: my %setters;
6031: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6032: my ($startblock,$endblock) =
6033: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6034: if ($startblock && $endblock) {
6035: return 'B';
6036: }
6037: } else {
6038: my ($startblock,$endblock) =
6039: &Apache::loncommon::blockcheck(\%setters,'port');
6040: if ($startblock && $endblock) {
6041: return 'B';
6042: }
6043: }
6044: }
1.765 albertel 6045: if ($result eq 'ok') {
1.766 albertel 6046: return 'F';
1.765 albertel 6047: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6048: return 'A';
1.765 albertel 6049: }
1.766 albertel 6050: return '';
1.765 albertel 6051: }
6052:
6053: sub get_portfolio_access {
1.767 albertel 6054: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6055:
6056: if (!ref($access_hash)) {
6057: my $current_perms = &get_portfile_permissions($udom,$unum);
6058: my %access_controls = &get_access_controls($current_perms,$group,
6059: $file_name);
6060: $access_hash = $access_controls{$file_name};
6061: }
6062:
1.765 albertel 6063: my ($public,$guest,@domains,@users,@courses,@groups);
6064: my $now = time;
6065: if (ref($access_hash) eq 'HASH') {
6066: foreach my $key (keys(%{$access_hash})) {
6067: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6068: if ($start > $now) {
6069: next;
6070: }
6071: if ($end && $end<$now) {
6072: next;
6073: }
6074: if ($scope eq 'public') {
6075: $public = $key;
6076: last;
6077: } elsif ($scope eq 'guest') {
6078: $guest = $key;
6079: } elsif ($scope eq 'domains') {
6080: push(@domains,$key);
6081: } elsif ($scope eq 'users') {
6082: push(@users,$key);
6083: } elsif ($scope eq 'course') {
6084: push(@courses,$key);
6085: } elsif ($scope eq 'group') {
6086: push(@groups,$key);
6087: }
6088: }
6089: if ($public) {
6090: return 'ok';
6091: }
6092: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6093: if ($guest) {
6094: return $guest;
6095: }
6096: } else {
6097: if (@domains > 0) {
6098: foreach my $domkey (@domains) {
6099: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6100: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6101: return 'ok';
6102: }
6103: }
6104: }
6105: }
6106: if (@users > 0) {
6107: foreach my $userkey (@users) {
1.865 raeburn 6108: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6109: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6110: if (ref($item) eq 'HASH') {
6111: if (($item->{'uname'} eq $env{'user.name'}) &&
6112: ($item->{'udom'} eq $env{'user.domain'})) {
6113: return 'ok';
6114: }
6115: }
6116: }
6117: }
1.765 albertel 6118: }
6119: }
6120: my %roleshash;
6121: my @courses_and_groups = @courses;
6122: push(@courses_and_groups,@groups);
6123: if (@courses_and_groups > 0) {
6124: my (%allgroups,%allroles);
6125: my ($start,$end,$role,$sec,$group);
6126: foreach my $envkey (%env) {
1.1060 raeburn 6127: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6128: my $cid = $2.'_'.$3;
6129: if ($1 eq 'gr') {
6130: $group = $4;
6131: $allgroups{$cid}{$group} = $env{$envkey};
6132: } else {
6133: if ($4 eq '') {
6134: $sec = 'none';
6135: } else {
6136: $sec = $4;
6137: }
6138: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6139: }
1.811 albertel 6140: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6141: my $cid = $2.'_'.$3;
6142: if ($4 eq '') {
6143: $sec = 'none';
6144: } else {
6145: $sec = $4;
6146: }
6147: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6148: }
6149: }
6150: if (keys(%allroles) == 0) {
6151: return;
6152: }
6153: foreach my $key (@courses_and_groups) {
6154: my %content = %{$$access_hash{$key}};
6155: my $cnum = $content{'number'};
6156: my $cdom = $content{'domain'};
6157: my $cid = $cdom.'_'.$cnum;
6158: if (!exists($allroles{$cid})) {
6159: next;
6160: }
6161: foreach my $role_id (keys(%{$content{'roles'}})) {
6162: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6163: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6164: my @status = @{$content{'roles'}{$role_id}{'access'}};
6165: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6166: foreach my $role (keys(%{$allroles{$cid}})) {
6167: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6168: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6169: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6170: if (grep/^all$/,@sections) {
6171: return 'ok';
6172: } else {
6173: if (grep/^$sec$/,@sections) {
6174: return 'ok';
6175: }
6176: }
6177: }
6178: }
6179: if (keys(%{$allgroups{$cid}}) == 0) {
6180: if (grep/^none$/,@groups) {
6181: return 'ok';
6182: }
6183: } else {
6184: if (grep/^all$/,@groups) {
6185: return 'ok';
6186: }
6187: foreach my $group (keys(%{$allgroups{$cid}})) {
6188: if (grep/^$group$/,@groups) {
6189: return 'ok';
6190: }
6191: }
6192: }
6193: }
6194: }
6195: }
6196: }
6197: }
6198: if ($guest) {
6199: return $guest;
6200: }
6201: }
6202: }
6203: return;
6204: }
6205:
6206: sub course_group_datechecker {
6207: my ($dates,$now,$status) = @_;
6208: my ($start,$end) = split(/\./,$dates);
6209: if (!$start && !$end) {
6210: return 'ok';
6211: }
6212: if (grep/^active$/,@{$status}) {
6213: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6214: return 'ok';
6215: }
6216: }
6217: if (grep/^previous$/,@{$status}) {
6218: if ($end > $now ) {
6219: return 'ok';
6220: }
6221: }
6222: if (grep/^future$/,@{$status}) {
6223: if ($start > $now) {
6224: return 'ok';
6225: }
6226: }
6227: return;
6228: }
6229:
6230: sub parse_portfolio_url {
6231: my ($url) = @_;
6232:
6233: my ($type,$udom,$unum,$group,$file_name);
6234:
1.823 albertel 6235: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6236: $type = 1;
6237: $udom = $1;
6238: $unum = $2;
6239: $file_name = $3;
1.823 albertel 6240: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6241: $type = 2;
6242: $udom = $1;
6243: $unum = $2;
6244: $group = $3;
6245: $file_name = $3.'/'.$4;
6246: }
6247: if (wantarray) {
6248: return ($type,$udom,$unum,$file_name,$group);
6249: }
6250: return $type;
6251: }
6252:
6253: sub is_portfolio_url {
6254: my ($url) = @_;
6255: return scalar(&parse_portfolio_url($url));
6256: }
6257:
1.798 raeburn 6258: sub is_portfolio_file {
6259: my ($file) = @_;
1.820 raeburn 6260: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6261: return 1;
6262: }
6263: return;
6264: }
6265:
1.976 raeburn 6266: sub usertools_access {
1.1084 raeburn 6267: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6268: my ($access,%tools);
6269: if ($context eq '') {
6270: $context = 'tools';
6271: }
6272: if ($context eq 'requestcourses') {
6273: %tools = (
6274: official => 1,
6275: unofficial => 1,
1.1006 raeburn 6276: community => 1,
1.985 raeburn 6277: );
1.1172.2.9 raeburn 6278: } elsif ($context eq 'requestauthor') {
6279: %tools = (
6280: requestauthor => 1,
6281: );
1.985 raeburn 6282: } else {
6283: %tools = (
6284: aboutme => 1,
6285: blog => 1,
1.1172.2.6 raeburn 6286: webdav => 1,
1.985 raeburn 6287: portfolio => 1,
6288: );
6289: }
1.976 raeburn 6290: return if (!defined($tools{$tool}));
6291:
1.1172.2.35 raeburn 6292: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6293: $udom = $env{'user.domain'};
6294: $uname = $env{'user.name'};
6295: }
6296:
1.978 raeburn 6297: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6298: if ($action ne 'reload') {
1.985 raeburn 6299: if ($context eq 'requestcourses') {
6300: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6301: } elsif ($context eq 'requestauthor') {
6302: return $env{'environment.canrequest.author'};
1.985 raeburn 6303: } else {
6304: return $env{'environment.availabletools.'.$tool};
6305: }
6306: }
1.976 raeburn 6307: }
6308:
1.1172.2.9 raeburn 6309: my ($toolstatus,$inststatus,$envkey);
6310: if ($context eq 'requestauthor') {
6311: $envkey = $context;
6312: } else {
6313: $envkey = $context.'.'.$tool;
6314: }
1.976 raeburn 6315:
1.985 raeburn 6316: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6317: ($action ne 'reload')) {
1.1172.2.9 raeburn 6318: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6319: $inststatus = $env{'environment.inststatus'};
6320: } else {
1.1084 raeburn 6321: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6322: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6323: $inststatus = $userenvref->{'inststatus'};
6324: } else {
1.1172.2.9 raeburn 6325: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6326: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6327: $inststatus = $userenv{'inststatus'};
6328: }
1.976 raeburn 6329: }
6330:
6331: if ($toolstatus ne '') {
6332: if ($toolstatus) {
6333: $access = 1;
6334: } else {
6335: $access = 0;
6336: }
6337: return $access;
6338: }
6339:
1.1084 raeburn 6340: my ($is_adv,%domdef);
6341: if (ref($is_advref) eq 'HASH') {
6342: $is_adv = $is_advref->{'is_adv'};
6343: } else {
6344: $is_adv = &is_advanced_user($udom,$uname);
6345: }
6346: if (ref($domdefref) eq 'HASH') {
6347: %domdef = %{$domdefref};
6348: } else {
6349: %domdef = &get_domain_defaults($udom);
6350: }
1.976 raeburn 6351: if (ref($domdef{$tool}) eq 'HASH') {
6352: if ($is_adv) {
6353: if ($domdef{$tool}{'_LC_adv'} ne '') {
6354: if ($domdef{$tool}{'_LC_adv'}) {
6355: $access = 1;
6356: } else {
6357: $access = 0;
6358: }
6359: return $access;
6360: }
6361: }
6362: if ($inststatus ne '') {
6363: my ($hasaccess,$hasnoaccess);
6364: foreach my $affiliation (split(/:/,$inststatus)) {
6365: if ($domdef{$tool}{$affiliation} ne '') {
6366: if ($domdef{$tool}{$affiliation}) {
6367: $hasaccess = 1;
6368: } else {
6369: $hasnoaccess = 1;
6370: }
6371: }
6372: }
6373: if ($hasaccess || $hasnoaccess) {
6374: if ($hasaccess) {
6375: $access = 1;
6376: } elsif ($hasnoaccess) {
6377: $access = 0;
6378: }
6379: return $access;
6380: }
6381: } else {
6382: if ($domdef{$tool}{'default'} ne '') {
6383: if ($domdef{$tool}{'default'}) {
6384: $access = 1;
6385: } elsif ($domdef{$tool}{'default'} == 0) {
6386: $access = 0;
6387: }
6388: return $access;
6389: }
6390: }
6391: } else {
1.1172.2.6 raeburn 6392: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6393: $access = 1;
6394: } else {
6395: $access = 0;
6396: }
1.976 raeburn 6397: return $access;
6398: }
6399: }
6400:
1.1050 raeburn 6401: sub is_course_owner {
6402: my ($cdom,$cnum,$udom,$uname) = @_;
6403: if (($udom eq '') || ($uname eq '')) {
6404: $udom = $env{'user.domain'};
6405: $uname = $env{'user.name'};
6406: }
6407: unless (($udom eq '') || ($uname eq '')) {
6408: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6409: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6410: return 1;
6411: } else {
6412: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6413: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6414: return 1;
6415: }
6416: }
6417: }
6418: }
6419: return;
6420: }
6421:
1.976 raeburn 6422: sub is_advanced_user {
6423: my ($udom,$uname) = @_;
1.1085 raeburn 6424: if ($udom ne '' && $uname ne '') {
6425: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6426: if (wantarray) {
6427: return ($env{'user.adv'},$env{'user.author'});
6428: } else {
6429: return $env{'user.adv'};
6430: }
1.1085 raeburn 6431: }
6432: }
1.976 raeburn 6433: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6434: my %allroles;
1.1128 raeburn 6435: my ($is_adv,$is_author);
1.976 raeburn 6436: foreach my $role (keys(%roleshash)) {
6437: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6438: my $area = '/'.$tdomain.'/'.$trest;
6439: if ($sec ne '') {
6440: $area .= '/'.$sec;
6441: }
6442: if (($area ne '') && ($trole ne '')) {
6443: my $spec=$trole.'.'.$area;
6444: if ($trole =~ /^cr\//) {
6445: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6446: } elsif ($trole ne 'gr') {
6447: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6448: }
1.1128 raeburn 6449: if ($trole eq 'au') {
6450: $is_author = 1;
6451: }
1.976 raeburn 6452: }
6453: }
6454: foreach my $role (keys(%allroles)) {
6455: last if ($is_adv);
6456: foreach my $item (split(/:/,$allroles{$role})) {
6457: if ($item ne '') {
6458: my ($privilege,$restrictions)=split(/&/,$item);
6459: if ($privilege eq 'adv') {
6460: $is_adv = 1;
6461: last;
6462: }
6463: }
6464: }
6465: }
1.1128 raeburn 6466: if (wantarray) {
6467: return ($is_adv,$is_author);
6468: }
1.976 raeburn 6469: return $is_adv;
6470: }
1.798 raeburn 6471:
1.1035 raeburn 6472: sub check_can_request {
1.1036 raeburn 6473: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6474: my $canreq = 0;
6475: my ($types,$typename) = &Apache::loncommon::course_types();
6476: my @options = ('approval','validate','autolimit');
6477: my $optregex = join('|',@options);
6478: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6479: foreach my $type (@{$types}) {
6480: if (&usertools_access($env{'user.name'},
6481: $env{'user.domain'},
6482: $type,undef,'requestcourses')) {
6483: $canreq ++;
1.1036 raeburn 6484: if (ref($request_domains) eq 'HASH') {
6485: push(@{$request_domains->{$type}},$env{'user.domain'});
6486: }
1.1035 raeburn 6487: if ($dom eq $env{'user.domain'}) {
6488: $can_request->{$type} = 1;
6489: }
6490: }
6491: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6492: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6493: if (@curr > 0) {
1.1036 raeburn 6494: foreach my $item (@curr) {
6495: if (ref($request_domains) eq 'HASH') {
6496: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6497: if ($otherdom ne '') {
6498: if (ref($request_domains->{$type}) eq 'ARRAY') {
6499: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6500: push(@{$request_domains->{$type}},$otherdom);
6501: }
6502: } else {
6503: push(@{$request_domains->{$type}},$otherdom);
6504: }
6505: }
6506: }
6507: }
6508: unless($dom eq $env{'user.domain'}) {
6509: $canreq ++;
1.1035 raeburn 6510: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6511: $can_request->{$type} = 1;
6512: }
6513: }
6514: }
6515: }
6516: }
6517: }
6518: return $canreq;
6519: }
6520:
1.341 www 6521: # ---------------------------------------------- Custom access rule evaluation
6522:
6523: sub customaccess {
6524: my ($priv,$uri)=@_;
1.807 albertel 6525: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6526: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6527: $udom = &LONCAPA::clean_domain($udom);
6528: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6529: my $access=0;
1.800 albertel 6530: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6531: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6532: if ($type eq 'user') {
6533: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6534: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6535: if ($tdom) {
6536: if ($tdom ne $env{'user.domain'}) { next; }
6537: }
1.896 albertel 6538: if ($tuname) {
6539: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6540: }
6541: $access=($effect eq 'allow');
6542: last;
6543: }
6544: } else {
6545: if ($role) {
6546: if ($role ne $urole) { next; }
6547: }
6548: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6549: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6550: if ($tdom) {
6551: if ($tdom ne $udom) { next; }
6552: }
6553: if ($tcrs) {
6554: if ($tcrs ne $ucrs) { next; }
6555: }
6556: if ($tsec) {
6557: if ($tsec ne $usec) { next; }
6558: }
6559: $access=($effect eq 'allow');
6560: last;
6561: }
6562: if ($realm eq '' && $role eq '') {
6563: $access=($effect eq 'allow');
6564: }
1.402 bowersj2 6565: }
1.341 www 6566: }
6567: return $access;
6568: }
6569:
1.103 harris41 6570: # ------------------------------------------------- Check for a user privilege
1.12 www 6571:
6572: sub allowed {
1.810 raeburn 6573: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6574: my $ver_orguri=$uri;
1.439 www 6575: $uri=&deversion($uri);
1.152 www 6576: my $orguri=$uri;
1.52 www 6577: $uri=&declutter($uri);
1.809 raeburn 6578:
1.810 raeburn 6579: if ($priv eq 'evb') {
6580: # Evade communication block restrictions for specified role in a course
6581: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6582: return $1;
6583: } else {
6584: return;
6585: }
6586: }
6587:
1.620 albertel 6588: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6589: # Free bre access to adm and meta resources
1.775 albertel 6590: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6591: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6592: && ($priv eq 'bre')) {
1.14 www 6593: return 'F';
1.159 www 6594: }
6595:
1.545 banghart 6596: # Free bre access to user's own portfolio contents
1.714 raeburn 6597: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6598: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6599: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6600: my %setters;
6601: my ($startblock,$endblock) =
6602: &Apache::loncommon::blockcheck(\%setters,'port');
6603: if ($startblock && $endblock) {
6604: return 'B';
6605: } else {
6606: return 'F';
6607: }
1.545 banghart 6608: }
6609:
1.762 raeburn 6610: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6611: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6612: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6613: if (exists($env{'request.course.id'})) {
6614: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6615: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6616: if (($domain eq $cdom) && ($name eq $cnum)) {
6617: my $courseprivid=$env{'request.course.id'};
6618: $courseprivid=~s/\_/\//;
6619: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6620: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6621: return $1;
1.762 raeburn 6622: } else {
6623: if ($env{'request.course.sec'}) {
6624: $courseprivid.='/'.$env{'request.course.sec'};
6625: }
6626: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6627: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6628: return $2;
6629: }
1.714 raeburn 6630: }
6631: }
6632: }
6633: }
6634:
1.159 www 6635: # Free bre to public access
6636:
6637: if ($priv eq 'bre') {
1.238 www 6638: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6639: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6640: return 'F';
6641: }
1.238 www 6642: if ($copyright eq 'priv') {
6643: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6644: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6645: return '';
6646: }
6647: }
6648: if ($copyright eq 'domain') {
6649: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6650: unless (($env{'user.domain'} eq $1) ||
6651: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6652: return '';
6653: }
1.262 matthew 6654: }
1.620 albertel 6655: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6656: # Library role, so allow browsing of resources in this domain.
6657: return 'F';
1.238 www 6658: }
1.341 www 6659: if ($copyright eq 'custom') {
6660: unless (&customaccess($priv,$uri)) { return ''; }
6661: }
1.14 www 6662: }
1.264 matthew 6663: # Domain coordinator is trying to create a course
1.620 albertel 6664: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6665: # uri is the requested domain in this case.
6666: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6667: # a role of dc for the domain in question.
1.620 albertel 6668: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6669: }
1.29 www 6670:
1.52 www 6671: my $thisallowed='';
6672: my $statecond=0;
6673: my $courseprivid='';
6674:
1.1039 raeburn 6675: my $ownaccess;
1.1043 raeburn 6676: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6677: if (($priv eq 'bro') && ($env{'user.author'})) {
6678: if ($uri eq '') {
6679: $ownaccess = 1;
6680: } else {
6681: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6682: my $udom = $env{'user.domain'};
6683: my $uname = $env{'user.name'};
6684: if ($uri =~ m{^\Q$udom\E/?$}) {
6685: $ownaccess = 1;
1.1040 raeburn 6686: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6687: unless ($uri =~ m{\.\./}) {
6688: $ownaccess = 1;
6689: }
6690: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6691: my $now = time;
6692: if ($uri =~ m{^([^/]+)/?$}) {
6693: my $adom = $1;
6694: foreach my $key (keys(%env)) {
1.1042 raeburn 6695: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6696: my ($start,$end) = split('.',$env{$key});
6697: if (($now >= $start) && (!$end || $end < $now)) {
6698: $ownaccess = 1;
6699: last;
6700: }
6701: }
6702: }
6703: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6704: my $adom = $1;
6705: my $aname = $2;
1.1042 raeburn 6706: foreach my $role ('ca','aa') {
6707: if ($env{"user.role.$role./$adom/$aname"}) {
6708: my ($start,$end) =
6709: split('.',$env{"user.role.$role./$adom/$aname"});
6710: if (($now >= $start) && (!$end || $end < $now)) {
6711: $ownaccess = 1;
6712: last;
6713: }
1.1039 raeburn 6714: }
6715: }
6716: }
6717: }
6718: }
6719: }
6720: }
6721:
1.52 www 6722: # Course
6723:
1.620 albertel 6724: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6725: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6726: $thisallowed.=$1;
6727: }
1.52 www 6728: }
1.29 www 6729:
1.52 www 6730: # Domain
6731:
1.620 albertel 6732: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6733: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6734: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6735: $thisallowed.=$1;
6736: }
1.12 www 6737: }
1.52 www 6738:
1.1141 raeburn 6739: # User who is not author or co-author might still be able to edit
6740: # resource of an author in the domain (e.g., if Domain Coordinator).
6741: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6742: (&allowed('mdc',$env{'request.course.id'}))) {
6743: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6744: $thisallowed.=$1;
6745: }
6746: }
6747:
1.52 www 6748: # Course: uri itself is a course
1.66 www 6749: my $courseuri=$uri;
6750: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6751: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6752:
1.620 albertel 6753: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6754: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6755: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6756: $thisallowed.=$1;
6757: }
1.12 www 6758: }
1.29 www 6759:
1.665 albertel 6760: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6761: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6762: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6763: $thisallowed='';
1.671 raeburn 6764: my ($match)=&is_on_map($uri);
6765: if ($match) {
6766: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6767: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6768: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6769: if (@blockers > 0) {
6770: $thisallowed = 'B';
6771: } else {
6772: $thisallowed.=$1;
6773: }
1.671 raeburn 6774: }
6775: } else {
1.705 albertel 6776: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6777: if ($refuri) {
6778: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6779: $thisallowed='F';
1.671 raeburn 6780: } else {
6781: $refuri=&declutter($refuri);
6782: my ($match) = &is_on_map($refuri);
6783: if ($match) {
1.1162 raeburn 6784: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6785: if (@blockers > 0) {
6786: $thisallowed = 'B';
6787: } else {
6788: $thisallowed='F';
6789: }
1.671 raeburn 6790: }
1.669 raeburn 6791: }
1.671 raeburn 6792: }
6793: }
1.314 www 6794: }
1.492 albertel 6795:
1.766 albertel 6796: if ($priv eq 'bre'
6797: && $thisallowed ne 'F'
6798: && $thisallowed ne '2'
6799: && &is_portfolio_url($uri)) {
6800: $thisallowed = &portfolio_access($uri);
6801: }
6802:
1.52 www 6803: # Full access at system, domain or course-wide level? Exit.
1.29 www 6804: if ($thisallowed=~/F/) {
6805: return 'F';
6806: }
6807:
1.52 www 6808: # If this is generating or modifying users, exit with special codes
1.29 www 6809:
1.643 www 6810: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6811: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6812: my ($audom,$auname)=split('/',$uri);
1.643 www 6813: # no author name given, so this just checks on the general right to make a co-author in this domain
6814: unless ($auname) { return $thisallowed; }
6815: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6816: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6817: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6818: ($audom ne $env{'request.role.domain'}))) { return ''; }
6819: }
1.52 www 6820: return $thisallowed;
6821: }
6822: #
1.103 harris41 6823: # Gathered so far: system, domain and course wide privileges
1.52 www 6824: #
6825: # Course: See if uri or referer is an individual resource that is part of
6826: # the course
6827:
1.620 albertel 6828: if ($env{'request.course.id'}) {
1.232 www 6829:
1.620 albertel 6830: $courseprivid=$env{'request.course.id'};
6831: if ($env{'request.course.sec'}) {
6832: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6833: }
6834: $courseprivid=~s/\_/\//;
6835: my $checkreferer=1;
1.232 www 6836: my ($match,$cond)=&is_on_map($uri);
6837: if ($match) {
6838: $statecond=$cond;
1.620 albertel 6839: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6840: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6841: my $value = $1;
6842: if ($priv eq 'bre') {
6843: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6844: if (@blockers > 0) {
6845: $thisallowed = 'B';
6846: } else {
6847: $thisallowed.=$value;
6848: }
6849: } else {
6850: $thisallowed.=$value;
6851: }
1.52 www 6852: $checkreferer=0;
6853: }
1.29 www 6854: }
1.83 www 6855:
1.148 www 6856: if ($checkreferer) {
1.620 albertel 6857: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6858: unless ($refuri) {
1.800 albertel 6859: foreach my $key (keys(%env)) {
6860: if ($key=~/^httpref\..*\*/) {
6861: my $pattern=$key;
1.156 www 6862: $pattern=~s/^httpref\.\/res\///;
1.148 www 6863: $pattern=~s/\*/\[\^\/\]\+/g;
6864: $pattern=~s/\//\\\//g;
1.152 www 6865: if ($orguri=~/$pattern/) {
1.800 albertel 6866: $refuri=$env{$key};
1.148 www 6867: }
6868: }
1.191 harris41 6869: }
1.148 www 6870: }
1.232 www 6871:
1.148 www 6872: if ($refuri) {
1.152 www 6873: $refuri=&declutter($refuri);
1.232 www 6874: my ($match,$cond)=&is_on_map($refuri);
6875: if ($match) {
6876: my $refstatecond=$cond;
1.620 albertel 6877: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6878: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6879: my $value = $1;
6880: if ($priv eq 'bre') {
6881: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6882: if (@blockers > 0) {
6883: $thisallowed = 'B';
6884: } else {
6885: $thisallowed.=$value;
6886: }
6887: } else {
6888: $thisallowed.=$value;
6889: }
1.53 www 6890: $uri=$refuri;
6891: $statecond=$refstatecond;
1.52 www 6892: }
6893: }
1.148 www 6894: }
1.29 www 6895: }
1.52 www 6896: }
1.29 www 6897:
1.52 www 6898: #
1.103 harris41 6899: # Gathered now: all privileges that could apply, and condition number
1.52 www 6900: #
6901: #
6902: # Full or no access?
6903: #
1.29 www 6904:
1.52 www 6905: if ($thisallowed=~/F/) {
6906: return 'F';
6907: }
1.29 www 6908:
1.52 www 6909: unless ($thisallowed) {
6910: return '';
6911: }
1.29 www 6912:
1.52 www 6913: # Restrictions exist, deal with them
6914: #
6915: # C:according to course preferences
6916: # R:according to resource settings
6917: # L:unless locked
6918: # X:according to user session state
6919: #
6920:
6921: # Possibly locked functionality, check all courses
1.54 www 6922: # Locks might take effect only after 10 minutes cache expiration for other
6923: # courses, and 2 minutes for current course
1.52 www 6924:
6925: my $envkey;
6926: if ($thisallowed=~/L/) {
1.1000 raeburn 6927: foreach $envkey (keys(%env)) {
1.54 www 6928: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6929: my $courseid=$2;
6930: my $roleid=$1.'.'.$2;
1.92 www 6931: $courseid=~s/^\///;
1.54 www 6932: my $expiretime=600;
1.620 albertel 6933: if ($env{'request.role'} eq $roleid) {
1.54 www 6934: $expiretime=120;
6935: }
6936: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6937: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6938: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6939: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6940: }
1.620 albertel 6941: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6942: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6943: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6944: &log($env{'user.domain'},$env{'user.name'},
6945: $env{'user.home'},
1.57 www 6946: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6947: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6948: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6949: return '';
6950: }
6951: }
1.620 albertel 6952: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6953: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6954: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6955: &log($env{'user.domain'},$env{'user.name'},
6956: $env{'user.home'},
1.57 www 6957: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6958: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6959: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6960: return '';
6961: }
6962: }
6963: }
1.29 www 6964: }
1.52 www 6965: }
6966:
6967: #
6968: # Rest of the restrictions depend on selected course
6969: #
6970:
1.620 albertel 6971: unless ($env{'request.course.id'}) {
1.766 albertel 6972: if ($thisallowed eq 'A') {
6973: return 'A';
1.814 raeburn 6974: } elsif ($thisallowed eq 'B') {
6975: return 'B';
1.766 albertel 6976: } else {
6977: return '1';
6978: }
1.52 www 6979: }
1.29 www 6980:
1.52 www 6981: #
6982: # Now user is definitely in a course
6983: #
1.53 www 6984:
6985:
6986: # Course preferences
6987:
6988: if ($thisallowed=~/C/) {
1.620 albertel 6989: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6990: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6991: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6992: =~/\Q$rolecode\E/) {
1.1103 raeburn 6993: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6994: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6995: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6996: $env{'request.course.id'});
6997: }
1.237 www 6998: return '';
6999: }
7000:
1.620 albertel 7001: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7002: =~/\Q$unamedom\E/) {
1.1103 raeburn 7003: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7004: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7005: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7006: $env{'request.course.id'});
7007: }
1.54 www 7008: return '';
7009: }
1.53 www 7010: }
7011:
7012: # Resource preferences
7013:
7014: if ($thisallowed=~/R/) {
1.620 albertel 7015: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7016: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7017: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7018: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7019: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7020: }
7021: return '';
1.54 www 7022: }
1.53 www 7023: }
1.30 www 7024:
1.246 www 7025: # Restricted by state or randomout?
1.30 www 7026:
1.52 www 7027: if ($thisallowed=~/X/) {
1.620 albertel 7028: if ($env{'acc.randomout'}) {
1.579 albertel 7029: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7030: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7031: return '';
7032: }
1.247 www 7033: }
7034: if (&condval($statecond)) {
1.52 www 7035: return '2';
7036: } else {
7037: return '';
7038: }
7039: }
1.30 www 7040:
1.766 albertel 7041: if ($thisallowed eq 'A') {
7042: return 'A';
1.814 raeburn 7043: } elsif ($thisallowed eq 'B') {
7044: return 'B';
1.766 albertel 7045: }
1.52 www 7046: return 'F';
1.232 www 7047: }
1.1162 raeburn 7048:
1.1172.2.13 raeburn 7049: # ------------------------------------------- Check construction space access
7050:
7051: sub constructaccess {
7052: my ($url,$setpriv)=@_;
7053:
7054: # We do not allow editing of previous versions of files
7055: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7056:
7057: # Get username and domain from URL
7058: my ($ownername,$ownerdomain,$ownerhome);
7059:
7060: ($ownerdomain,$ownername) =
7061: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7062:
7063: # The URL does not really point to any authorspace, forget it
7064: unless (($ownername) && ($ownerdomain)) { return ''; }
7065:
7066: # Now we need to see if the user has access to the authorspace of
7067: # $ownername at $ownerdomain
7068:
7069: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7070: # Real author for this?
7071: $ownerhome = $env{'user.home'};
7072: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7073: return ($ownername,$ownerdomain,$ownerhome);
7074: }
7075: } else {
7076: # Co-author for this?
7077: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7078: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7079: $ownerhome = &homeserver($ownername,$ownerdomain);
7080: return ($ownername,$ownerdomain,$ownerhome);
7081: }
7082: }
7083:
7084: # We don't have any access right now. If we are not possibly going to do anything about this,
7085: # we might as well leave
7086: unless ($setpriv) { return ''; }
7087:
7088: # Backdoor access?
7089: my $allowed=&allowed('eco',$ownerdomain);
7090: # Nope
7091: unless ($allowed) { return ''; }
7092: # Looks like we may have access, but could be locked by the owner of the construction space
7093: if ($allowed eq 'U') {
7094: my %blocked=&get('environment',['domcoord.author'],
7095: $ownerdomain,$ownername);
7096: # Is blocked by owner
7097: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7098: }
7099: if (($allowed eq 'F') || ($allowed eq 'U')) {
7100: # Grant temporary access
7101: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7102: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7103: if (!$update) { $update = $then; }
7104: my $refresh=$env{'user.refresh.time'};
7105: if (!$refresh) { $refresh = $update; }
7106: my $now = time;
7107: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7108: $now,'ca','constructaccess');
7109: $ownerhome = &homeserver($ownername,$ownerdomain);
7110: return($ownername,$ownerdomain,$ownerhome);
7111: }
7112: # No business here
7113: return '';
7114: }
7115:
1.1162 raeburn 7116: sub get_comm_blocks {
7117: my ($cdom,$cnum) = @_;
7118: if ($cdom eq '' || $cnum eq '') {
7119: return unless ($env{'request.course.id'});
7120: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7121: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7122: }
7123: my %commblocks;
7124: my $hashid=$cdom.'_'.$cnum;
7125: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7126: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7127: %commblocks = %{$blocksref};
7128: } else {
7129: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7130: my $cachetime = 600;
7131: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7132: }
7133: return %commblocks;
7134: }
7135:
7136: sub has_comm_blocking {
7137: my ($priv,$symb,$uri,$blocks) = @_;
7138: return unless ($env{'request.course.id'});
7139: return unless ($priv eq 'bre');
7140: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7141: my %commblocks;
7142: if (ref($blocks) eq 'HASH') {
7143: %commblocks = %{$blocks};
7144: } else {
7145: %commblocks = &get_comm_blocks();
7146: }
7147: return unless (keys(%commblocks) > 0);
7148: if (!$symb) { $symb=&symbread($uri,1); }
7149: my ($map,$resid,undef)=&decode_symb($symb);
7150: my %tocheck = (
7151: maps => $map,
7152: resources => $symb,
7153: );
7154: my @blockers;
7155: my $now = time;
1.1163 raeburn 7156: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7157: foreach my $block (keys(%commblocks)) {
7158: if ($block =~ /^(\d+)____(\d+)$/) {
7159: my ($start,$end) = ($1,$2);
7160: if ($start <= $now && $end >= $now) {
7161: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7162: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7163: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7164: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7165: unless (grep(/^\Q$block\E$/,@blockers)) {
7166: push(@blockers,$block);
7167: }
7168: }
7169: }
7170: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7171: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7172: unless (grep(/^\Q$block\E$/,@blockers)) {
7173: push(@blockers,$block);
7174: }
7175: }
7176: }
7177: }
7178: }
7179: }
7180: } elsif ($block =~ /^firstaccess____(.+)$/) {
7181: my $item = $1;
1.1163 raeburn 7182: my @to_test;
1.1162 raeburn 7183: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7184: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7185: my $check_interval;
7186: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7187: my @interval;
7188: my $type = 'map';
7189: if ($item eq 'course') {
7190: $type = 'course';
7191: @interval=&EXT("resource.0.interval");
7192: } else {
7193: if ($item =~ /___\d+___/) {
7194: $type = 'resource';
7195: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7196: if (ref($navmap)) {
7197: my $res = $navmap->getBySymb($item);
7198: push(@to_test,$res);
7199: }
1.1162 raeburn 7200: } else {
7201: my $mapsymb = &symbread($item,1);
7202: if ($mapsymb) {
7203: if (ref($navmap)) {
7204: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7205: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7206: foreach my $res (@to_test) {
1.1162 raeburn 7207: my $symb = $res->symb();
7208: next if ($symb eq $mapsymb);
7209: if ($symb ne '') {
7210: @interval=&EXT("resource.0.interval",$symb);
7211: last;
7212: }
7213: }
7214: }
7215: }
7216: }
7217: }
7218: if ($interval[0] =~ /\d+/) {
7219: my $first_access;
7220: if ($type eq 'resource') {
7221: $first_access=&get_first_access($interval[1],$item);
7222: } elsif ($type eq 'map') {
7223: $first_access=&get_first_access($interval[1],undef,$item);
7224: } else {
7225: $first_access=&get_first_access($interval[1]);
7226: }
7227: if ($first_access) {
7228: my $timesup = $first_access+$interval[0];
7229: if ($timesup > $now) {
1.1163 raeburn 7230: foreach my $res (@to_test) {
7231: if ($res->is_problem()) {
7232: if ($res->completable()) {
7233: unless (grep(/^\Q$block\E$/,@blockers)) {
7234: push(@blockers,$block);
7235: }
7236: last;
7237: }
7238: }
1.1162 raeburn 7239: }
7240: }
7241: }
7242: }
7243: }
7244: }
7245: }
7246: }
7247: }
7248: return @blockers;
7249: }
7250:
7251: sub check_docs_block {
7252: my ($docsblock,$tocheck) =@_;
7253: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7254: return;
7255: }
7256: if (ref($docsblock->{'maps'}) eq 'HASH') {
7257: if ($tocheck->{'maps'}) {
7258: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7259: return 1;
7260: }
7261: }
7262: }
7263: if (ref($docsblock->{'resources'}) eq 'HASH') {
7264: if ($tocheck->{'resources'}) {
7265: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7266: return 1;
7267: }
7268: }
7269: }
7270: return;
7271: }
7272:
1.1133 foxr 7273: #
7274: # Removes the versino from a URI and
7275: # splits it in to its filename and path to the filename.
7276: # Seems like File::Basename could have done this more clearly.
7277: # Parameters:
7278: # $uri - input URI
7279: # Returns:
7280: # Two element list consisting of
7281: # $pathname - the URI up to and excluding the trailing /
7282: # $filename - The part of the URI following the last /
7283: # NOTE:
7284: # Another realization of this is simply:
7285: # use File::Basename;
7286: # ...
7287: # $uri = shift;
7288: # $filename = basename($uri);
7289: # $path = dirname($uri);
7290: # return ($filename, $path);
7291: #
7292: # The implementation below is probably faster however.
7293: #
1.710 albertel 7294: sub split_uri_for_cond {
7295: my $uri=&deversion(&declutter(shift));
7296: my @uriparts=split(/\//,$uri);
7297: my $filename=pop(@uriparts);
7298: my $pathname=join('/',@uriparts);
7299: return ($pathname,$filename);
7300: }
1.232 www 7301: # --------------------------------------------------- Is a resource on the map?
7302:
7303: sub is_on_map {
1.710 albertel 7304: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7305: #Trying to find the conditional for the file
1.620 albertel 7306: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7307: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7308: if ($match) {
1.289 bowersj2 7309: return (1,$1);
7310: } else {
1.434 www 7311: return (0,0);
1.289 bowersj2 7312: }
1.12 www 7313: }
7314:
1.427 www 7315: # --------------------------------------------------------- Get symb from alias
7316:
7317: sub get_symb_from_alias {
7318: my $symb=shift;
7319: my ($map,$resid,$url)=&decode_symb($symb);
7320: # Already is a symb
7321: if ($url) { return $symb; }
7322: # Must be an alias
7323: my $aliassymb='';
7324: my %bighash;
1.620 albertel 7325: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7326: &GDBM_READER(),0640)) {
7327: my $rid=$bighash{'mapalias_'.$symb};
7328: if ($rid) {
7329: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7330: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7331: $resid,$bighash{'src_'.$rid});
1.427 www 7332: }
7333: untie %bighash;
7334: }
7335: return $aliassymb;
7336: }
7337:
1.12 www 7338: # ----------------------------------------------------------------- Define Role
7339:
7340: sub definerole {
7341: if (allowed('mcr','/')) {
7342: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7343: foreach my $role (split(':',$sysrole)) {
7344: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7345: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7346: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7347: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7348: return "refused:s:$crole&$cqual";
7349: }
7350: }
1.191 harris41 7351: }
1.800 albertel 7352: foreach my $role (split(':',$domrole)) {
7353: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7354: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7355: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7356: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7357: return "refused:d:$crole&$cqual";
7358: }
7359: }
1.191 harris41 7360: }
1.800 albertel 7361: foreach my $role (split(':',$courole)) {
7362: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7363: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7364: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7365: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7366: return "refused:c:$crole&$cqual";
7367: }
7368: }
1.191 harris41 7369: }
1.620 albertel 7370: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7371: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7372: "rolesdef_$rolename=".
7373: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7374: return reply($command,$env{'user.home'});
1.12 www 7375: } else {
7376: return 'refused';
7377: }
1.105 harris41 7378: }
7379:
7380: # ---------------- Make a metadata query against the network of library servers
7381:
7382: sub metadata_query {
1.1172.2.33 raeburn 7383: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7384: my %rhash;
1.845 albertel 7385: my %libserv = &all_library();
1.244 matthew 7386: my @server_list = (defined($server_array) ? @$server_array
7387: : keys(%libserv) );
7388: for my $server (@server_list) {
1.1172.2.33 raeburn 7389: my $domains = '';
7390: if (ref($domains_hash) eq 'HASH') {
7391: $domains = $domains_hash->{$server};
7392: }
1.118 harris41 7393: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7394: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7395: $rhash{$server}=$reply;
7396: }
7397: else {
7398: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7399: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7400: $server);
7401: $rhash{$server}=$reply;
7402: }
1.112 harris41 7403: }
1.118 harris41 7404: return \%rhash;
1.240 www 7405: }
7406:
7407: # ----------------------------------------- Send log queries and wait for reply
7408:
7409: sub log_query {
7410: my ($uname,$udom,$query,%filters)=@_;
7411: my $uhome=&homeserver($uname,$udom);
7412: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7413: my $uhost=&hostname($uhome);
1.800 albertel 7414: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7415: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7416: $uhome);
1.479 albertel 7417: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7418: return get_query_reply($queryid);
7419: }
7420:
1.818 raeburn 7421: # -------------------------- Update MySQL table for portfolio file
7422:
7423: sub update_portfolio_table {
1.821 raeburn 7424: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7425: if ($group ne '') {
7426: $file_name =~s /^\Q$group\E//;
7427: }
1.818 raeburn 7428: my $homeserver = &homeserver($uname,$udom);
7429: my $queryid=
1.821 raeburn 7430: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7431: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7432: my $reply = &get_query_reply($queryid);
7433: return $reply;
7434: }
7435:
1.899 raeburn 7436: # -------------------------- Update MySQL allusers table
7437:
7438: sub update_allusers_table {
7439: my ($uname,$udom,$names) = @_;
7440: my $homeserver = &homeserver($uname,$udom);
7441: my $queryid=
7442: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7443: 'lastname='.&escape($names->{'lastname'}).'%%'.
7444: 'firstname='.&escape($names->{'firstname'}).'%%'.
7445: 'middlename='.&escape($names->{'middlename'}).'%%'.
7446: 'generation='.&escape($names->{'generation'}).'%%'.
7447: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7448: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7449: return;
1.899 raeburn 7450: }
7451:
1.508 raeburn 7452: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7453:
7454: sub fetch_enrollment_query {
1.511 raeburn 7455: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7456: my $homeserver;
1.547 raeburn 7457: my $maxtries = 1;
1.508 raeburn 7458: if ($context eq 'automated') {
7459: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7460: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7461: } else {
7462: $homeserver = &homeserver($cnum,$dom);
7463: }
1.838 albertel 7464: my $host=&hostname($homeserver);
1.506 raeburn 7465: my $cmd = '';
1.1000 raeburn 7466: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7467: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7468: }
7469: $cmd =~ s/%%$//;
7470: $cmd = &escape($cmd);
7471: my $query = 'fetchenrollment';
1.620 albertel 7472: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7473: unless ($queryid=~/^\Q$host\E\_/) {
7474: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7475: return 'error: '.$queryid;
7476: }
1.506 raeburn 7477: my $reply = &get_query_reply($queryid);
1.547 raeburn 7478: my $tries = 1;
7479: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7480: $reply = &get_query_reply($queryid);
7481: $tries ++;
7482: }
1.526 raeburn 7483: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7484: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7485: } else {
1.901 albertel 7486: my @responses = split(/:/,$reply);
1.515 raeburn 7487: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7488: foreach my $line (@responses) {
7489: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7490: $$replyref{$key} = $value;
7491: }
7492: } else {
1.1117 foxr 7493: my $pathname = LONCAPA::tempdir();
1.800 albertel 7494: foreach my $line (@responses) {
7495: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7496: $$replyref{$key} = $value;
7497: if ($value > 0) {
1.800 albertel 7498: foreach my $item (@{$$affiliatesref{$key}}) {
7499: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7500: my $destname = $pathname.'/'.$filename;
7501: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7502: if ($xml_classlist =~ /^error/) {
7503: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7504: } else {
1.506 raeburn 7505: if ( open(FILE,">$destname") ) {
7506: print FILE &unescape($xml_classlist);
7507: close(FILE);
1.526 raeburn 7508: } else {
7509: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7510: }
7511: }
7512: }
7513: }
7514: }
7515: }
7516: return 'ok';
7517: }
7518: return 'error';
7519: }
7520:
1.242 www 7521: sub get_query_reply {
7522: my $queryid=shift;
1.1117 foxr 7523: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7524: my $reply='';
7525: for (1..100) {
7526: sleep 2;
7527: if (-e $replyfile.'.end') {
1.448 albertel 7528: if (open(my $fh,$replyfile)) {
1.904 albertel 7529: $reply = join('',<$fh>);
7530: close($fh);
1.240 www 7531: } else { return 'error: reply_file_error'; }
1.242 www 7532: return &unescape($reply);
7533: }
1.240 www 7534: }
1.242 www 7535: return 'timeout:'.$queryid;
1.240 www 7536: }
7537:
7538: sub courselog_query {
1.241 www 7539: #
7540: # possible filters:
7541: # url: url or symb
7542: # username
7543: # domain
7544: # action: view, submit, grade
7545: # start: timestamp
7546: # end: timestamp
7547: #
1.240 www 7548: my (%filters)=@_;
1.620 albertel 7549: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7550: if ($filters{'url'}) {
7551: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7552: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7553: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7554: }
1.620 albertel 7555: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7556: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7557: return &log_query($cname,$cdom,'courselog',%filters);
7558: }
7559:
7560: sub userlog_query {
1.858 raeburn 7561: #
7562: # possible filters:
7563: # action: log check role
7564: # start: timestamp
7565: # end: timestamp
7566: #
1.240 www 7567: my ($uname,$udom,%filters)=@_;
7568: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7569: }
7570:
1.506 raeburn 7571: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7572:
7573: sub auto_run {
1.508 raeburn 7574: my ($cnum,$cdom) = @_;
1.876 raeburn 7575: my $response = 0;
7576: my $settings;
7577: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7578: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7579: $settings = $domconfig{'autoenroll'};
7580: if ($settings->{'run'} eq '1') {
7581: $response = 1;
7582: }
7583: } else {
1.934 raeburn 7584: my $homeserver;
7585: if (&is_course($cdom,$cnum)) {
7586: $homeserver = &homeserver($cnum,$cdom);
7587: } else {
7588: $homeserver = &domain($cdom,'primary');
7589: }
7590: if ($homeserver ne 'no_host') {
7591: $response = &reply('autorun:'.$cdom,$homeserver);
7592: }
1.876 raeburn 7593: }
1.506 raeburn 7594: return $response;
7595: }
1.776 albertel 7596:
1.506 raeburn 7597: sub auto_get_sections {
1.508 raeburn 7598: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7599: my $homeserver;
7600: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7601: $homeserver = &homeserver($cnum,$cdom);
7602: }
7603: if (!defined($homeserver)) {
7604: if ($cdom =~ /^$match_domain$/) {
7605: $homeserver = &domain($cdom,'primary');
7606: }
7607: }
7608: my @secs;
7609: if (defined($homeserver)) {
7610: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7611: unless ($response eq 'refused') {
7612: @secs = split(/:/,$response);
7613: }
1.506 raeburn 7614: }
7615: return @secs;
7616: }
1.776 albertel 7617:
1.506 raeburn 7618: sub auto_new_course {
1.1099 raeburn 7619: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7620: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7621: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7622: return $response;
7623: }
1.776 albertel 7624:
1.506 raeburn 7625: sub auto_validate_courseID {
1.508 raeburn 7626: my ($cnum,$cdom,$inst_course_id) = @_;
7627: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7628: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7629: return $response;
7630: }
1.776 albertel 7631:
1.1007 raeburn 7632: sub auto_validate_instcode {
1.1020 raeburn 7633: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7634: my ($homeserver,$response);
7635: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7636: $homeserver = &homeserver($cnum,$cdom);
7637: }
7638: if (!defined($homeserver)) {
7639: if ($cdom =~ /^$match_domain$/) {
7640: $homeserver = &domain($cdom,'primary');
7641: }
7642: }
1.1065 raeburn 7643: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7644: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7645: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7646: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7647: }
7648:
1.506 raeburn 7649: sub auto_create_password {
1.873 raeburn 7650: my ($cnum,$cdom,$authparam,$udom) = @_;
7651: my ($homeserver,$response);
1.506 raeburn 7652: my $create_passwd = 0;
7653: my $authchk = '';
1.873 raeburn 7654: if ($udom =~ /^$match_domain$/) {
7655: $homeserver = &domain($udom,'primary');
7656: }
7657: if ($homeserver eq '') {
7658: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7659: $homeserver = &homeserver($cnum,$cdom);
7660: }
7661: }
7662: if ($homeserver eq '') {
7663: $authchk = 'nodomain';
1.506 raeburn 7664: } else {
1.873 raeburn 7665: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7666: if ($response eq 'refused') {
7667: $authchk = 'refused';
7668: } else {
1.901 albertel 7669: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7670: }
1.506 raeburn 7671: }
7672: return ($authparam,$create_passwd,$authchk);
7673: }
7674:
1.706 raeburn 7675: sub auto_photo_permission {
7676: my ($cnum,$cdom,$students) = @_;
7677: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7678: my ($outcome,$perm_reqd,$conditions) =
7679: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7680: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7681: return (undef,undef);
7682: }
1.706 raeburn 7683: return ($outcome,$perm_reqd,$conditions);
7684: }
7685:
7686: sub auto_checkphotos {
7687: my ($uname,$udom,$pid) = @_;
7688: my $homeserver = &homeserver($uname,$udom);
7689: my ($result,$resulttype);
7690: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7691: &escape($uname).':'.&escape($pid),
7692: $homeserver));
1.709 albertel 7693: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7694: return (undef,undef);
7695: }
1.706 raeburn 7696: if ($outcome) {
7697: ($result,$resulttype) = split(/:/,$outcome);
7698: }
7699: return ($result,$resulttype);
7700: }
7701:
7702: sub auto_photochoice {
7703: my ($cnum,$cdom) = @_;
7704: my $homeserver = &homeserver($cnum,$cdom);
7705: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7706: &escape($cdom),
7707: $homeserver)));
1.709 albertel 7708: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7709: return (undef,undef);
7710: }
1.706 raeburn 7711: return ($update,$comment);
7712: }
7713:
7714: sub auto_photoupdate {
7715: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7716: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7717: my $host=&hostname($homeserver);
1.706 raeburn 7718: my $cmd = '';
7719: my $maxtries = 1;
1.800 albertel 7720: foreach my $affiliate (keys(%{$affiliatesref})) {
7721: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7722: }
7723: $cmd =~ s/%%$//;
7724: $cmd = &escape($cmd);
7725: my $query = 'institutionalphotos';
7726: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7727: unless ($queryid=~/^\Q$host\E\_/) {
7728: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7729: return 'error: '.$queryid;
7730: }
7731: my $reply = &get_query_reply($queryid);
7732: my $tries = 1;
7733: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7734: $reply = &get_query_reply($queryid);
7735: $tries ++;
7736: }
7737: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7738: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7739: } else {
7740: my @responses = split(/:/,$reply);
7741: my $outcome = shift(@responses);
7742: foreach my $item (@responses) {
7743: my ($key,$value) = split(/=/,$item);
7744: $$photo{$key} = $value;
7745: }
7746: return $outcome;
7747: }
7748: return 'error';
7749: }
7750:
1.521 raeburn 7751: sub auto_instcode_format {
1.793 albertel 7752: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7753: $cat_order) = @_;
1.521 raeburn 7754: my $courses = '';
1.772 raeburn 7755: my @homeservers;
1.521 raeburn 7756: if ($caller eq 'global') {
1.841 albertel 7757: my %servers = &get_servers($codedom,'library');
7758: foreach my $tryserver (keys(%servers)) {
7759: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7760: push(@homeservers,$tryserver);
7761: }
1.584 raeburn 7762: }
1.1022 raeburn 7763: } elsif ($caller eq 'requests') {
7764: if ($codedom =~ /^$match_domain$/) {
7765: my $chome = &domain($codedom,'primary');
7766: unless ($chome eq 'no_host') {
7767: push(@homeservers,$chome);
7768: }
7769: }
1.521 raeburn 7770: } else {
1.772 raeburn 7771: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7772: }
1.793 albertel 7773: foreach my $code (keys(%{$instcodes})) {
7774: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7775: }
7776: chop($courses);
1.772 raeburn 7777: my $ok_response = 0;
7778: my $response;
7779: while (@homeservers > 0 && $ok_response == 0) {
7780: my $server = shift(@homeservers);
7781: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7782: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7783: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7784: split(/:/,$response);
1.772 raeburn 7785: %{$codes} = (%{$codes},&str2hash($codes_str));
7786: push(@{$codetitles},&str2array($codetitles_str));
7787: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7788: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7789: $ok_response = 1;
7790: }
7791: }
7792: if ($ok_response) {
1.521 raeburn 7793: return 'ok';
1.772 raeburn 7794: } else {
7795: return $response;
1.521 raeburn 7796: }
7797: }
7798:
1.792 raeburn 7799: sub auto_instcode_defaults {
7800: my ($domain,$returnhash,$code_order) = @_;
7801: my @homeservers;
1.841 albertel 7802:
7803: my %servers = &get_servers($domain,'library');
7804: foreach my $tryserver (keys(%servers)) {
7805: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7806: push(@homeservers,$tryserver);
7807: }
1.792 raeburn 7808: }
1.841 albertel 7809:
1.792 raeburn 7810: my $response;
1.841 albertel 7811: foreach my $server (@homeservers) {
1.792 raeburn 7812: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7813: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7814:
7815: foreach my $pair (split(/\&/,$response)) {
7816: my ($name,$value)=split(/\=/,$pair);
7817: if ($name eq 'code_order') {
7818: @{$code_order} = split(/\&/,&unescape($value));
7819: } else {
7820: $returnhash->{&unescape($name)}=&unescape($value);
7821: }
7822: }
7823: return 'ok';
1.792 raeburn 7824: }
1.841 albertel 7825:
7826: return $response;
1.1003 raeburn 7827: }
7828:
7829: sub auto_possible_instcodes {
1.1007 raeburn 7830: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7831: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7832: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7833: return;
7834: }
1.1003 raeburn 7835: my (@homeservers,$uhome);
7836: if (defined(&domain($domain,'primary'))) {
7837: $uhome=&domain($domain,'primary');
7838: push(@homeservers,&domain($domain,'primary'));
7839: } else {
7840: my %servers = &get_servers($domain,'library');
7841: foreach my $tryserver (keys(%servers)) {
7842: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7843: push(@homeservers,$tryserver);
7844: }
7845: }
7846: }
7847: my $response;
7848: foreach my $server (@homeservers) {
7849: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7850: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7851: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7852: split(':',$response);
7853: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7854: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7855: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7856: my ($name,$value)=split('=',$item);
7857: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7858: }
7859: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7860: my ($name,$value)=split('=',$item);
7861: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7862: }
7863: return 'ok';
7864: }
7865: return $response;
7866: }
1.792 raeburn 7867:
1.1010 raeburn 7868: sub auto_courserequest_checks {
7869: my ($dom) = @_;
1.1020 raeburn 7870: my ($homeserver,%validations);
7871: if ($dom =~ /^$match_domain$/) {
7872: $homeserver = &domain($dom,'primary');
7873: }
7874: unless ($homeserver eq 'no_host') {
7875: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7876: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7877: my @items = split(/&/,$response);
7878: foreach my $item (@items) {
7879: my ($key,$value) = split('=',$item);
7880: $validations{&unescape($key)} = &thaw_unescape($value);
7881: }
7882: }
7883: }
1.1010 raeburn 7884: return %validations;
7885: }
7886:
1.1020 raeburn 7887: sub auto_courserequest_validation {
7888: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7889: my ($homeserver,$response);
7890: if ($dom =~ /^$match_domain$/) {
7891: $homeserver = &domain($dom,'primary');
7892: }
7893: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7894:
1.1020 raeburn 7895: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7896: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7897: ':'.&escape($instcode).':'.&escape($instseclist),
7898: $homeserver));
7899: }
7900: return $response;
7901: }
7902:
1.777 albertel 7903: sub auto_validate_class_sec {
1.918 raeburn 7904: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7905: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7906: my $ownerlist;
7907: if (ref($owners) eq 'ARRAY') {
7908: $ownerlist = join(',',@{$owners});
7909: } else {
7910: $ownerlist = $owners;
7911: }
1.773 raeburn 7912: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7913: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7914: return $response;
7915: }
7916:
1.679 raeburn 7917: # ------------------------------------------------------- Course Group routines
7918:
7919: sub get_coursegroups {
1.809 raeburn 7920: my ($cdom,$cnum,$group,$namespace) = @_;
7921: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7922: }
7923:
1.679 raeburn 7924: sub modify_coursegroup {
7925: my ($cdom,$cnum,$groupsettings) = @_;
7926: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7927: }
7928:
1.809 raeburn 7929: sub toggle_coursegroup_status {
7930: my ($cdom,$cnum,$group,$action) = @_;
7931: my ($from_namespace,$to_namespace);
7932: if ($action eq 'delete') {
7933: $from_namespace = 'coursegroups';
7934: $to_namespace = 'deleted_groups';
7935: } else {
7936: $from_namespace = 'deleted_groups';
7937: $to_namespace = 'coursegroups';
7938: }
7939: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7940: if (my $tmp = &error(%curr_group)) {
7941: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7942: return ('read error',$tmp);
7943: } else {
7944: my %savedsettings = %curr_group;
1.809 raeburn 7945: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7946: my $deloutcome;
7947: if ($result eq 'ok') {
1.809 raeburn 7948: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7949: } else {
7950: return ('write error',$result);
7951: }
7952: if ($deloutcome eq 'ok') {
7953: return 'ok';
7954: } else {
7955: return ('delete error',$deloutcome);
7956: }
7957: }
7958: }
7959:
1.679 raeburn 7960: sub modify_group_roles {
1.957 raeburn 7961: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7962: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7963: my $role = 'gr/'.&escape($userprivs);
7964: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7965: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7966: if ($result eq 'ok') {
7967: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7968: }
1.679 raeburn 7969: return $result;
7970: }
7971:
7972: sub modify_coursegroup_membership {
7973: my ($cdom,$cnum,$membership) = @_;
7974: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7975: return $result;
7976: }
7977:
1.682 raeburn 7978: sub get_active_groups {
7979: my ($udom,$uname,$cdom,$cnum) = @_;
7980: my $now = time;
7981: my %groups = ();
7982: foreach my $key (keys(%env)) {
1.811 albertel 7983: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7984: my ($start,$end) = split(/\./,$env{$key});
7985: if (($end!=0) && ($end<$now)) { next; }
7986: if (($start!=0) && ($start>$now)) { next; }
7987: if ($1 eq $cdom && $2 eq $cnum) {
7988: $groups{$3} = $env{$key} ;
7989: }
7990: }
7991: }
7992: return %groups;
7993: }
7994:
1.683 raeburn 7995: sub get_group_membership {
7996: my ($cdom,$cnum,$group) = @_;
7997: return(&dump('groupmembership',$cdom,$cnum,$group));
7998: }
7999:
8000: sub get_users_groups {
8001: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8002: my @usersgroups;
1.683 raeburn 8003: my $cachetime=1800;
8004:
8005: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8006: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8007: if (defined($cached)) {
1.734 albertel 8008: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8009: } else {
8010: $grouplist = '';
1.816 raeburn 8011: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8012: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8013: my $access_end = $env{'course.'.$courseid.
8014: '.default_enrollment_end_date'};
8015: my $now = time;
8016: foreach my $key (keys(%roleshash)) {
8017: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8018: my $group = $1;
8019: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8020: my $start = $2;
8021: my $end = $1;
8022: if ($start == -1) { next; } # deleted from group
8023: if (($start!=0) && ($start>$now)) { next; }
8024: if (($end!=0) && ($end<$now)) {
8025: if ($access_end && $access_end < $now) {
8026: if ($access_end - $end < 86400) {
8027: push(@usersgroups,$group);
1.733 raeburn 8028: }
8029: }
1.817 raeburn 8030: next;
1.733 raeburn 8031: }
1.817 raeburn 8032: push(@usersgroups,$group);
1.683 raeburn 8033: }
8034: }
8035: }
1.817 raeburn 8036: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8037: $grouplist = join(':',@usersgroups);
8038: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8039: }
1.733 raeburn 8040: return @usersgroups;
1.683 raeburn 8041: }
8042:
8043: sub devalidate_getgroups_cache {
8044: my ($udom,$uname,$cdom,$cnum)=@_;
8045: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8046:
1.683 raeburn 8047: my $hashid="$udom:$uname:$courseid";
8048: &devalidate_cache_new('getgroups',$hashid);
8049: }
8050:
1.12 www 8051: # ------------------------------------------------------------------ Plain Text
8052:
8053: sub plaintext {
1.988 raeburn 8054: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8055: if ($short =~ m{^cr/}) {
1.758 albertel 8056: return (split('/',$short))[-1];
8057: }
1.742 raeburn 8058: if (!defined($cid)) {
8059: $cid = $env{'request.course.id'};
8060: }
8061: my %rolenames = (
1.1008 raeburn 8062: Course => 'std',
8063: Community => 'alt1',
1.742 raeburn 8064: );
1.1037 raeburn 8065: if ($cid ne '') {
8066: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8067: unless ($forcedefault) {
8068: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8069: &Apache::lonlocal::mt_escape(\$roletext);
8070: return &Apache::lonlocal::mt($roletext);
8071: }
8072: }
8073: }
8074: if ((defined($type)) && (defined($rolenames{$type})) &&
8075: (defined($rolenames{$type})) &&
8076: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8077: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8078: } elsif ($cid ne '') {
8079: my $crstype = $env{'course.'.$cid.'.type'};
8080: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8081: (defined($prp{$short}{$rolenames{$crstype}}))) {
8082: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8083: }
1.742 raeburn 8084: }
1.1037 raeburn 8085: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8086: }
8087:
8088: # ----------------------------------------------------------------- Assign Role
8089:
8090: sub assignrole {
1.957 raeburn 8091: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8092: $context)=@_;
1.21 www 8093: my $mrole;
8094: if ($role =~ /^cr\//) {
1.393 www 8095: my $cwosec=$url;
1.811 albertel 8096: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8097: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8098: my $refused = 1;
8099: if ($context eq 'requestcourses') {
8100: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8101: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8102: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8103: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8104: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8105: if ($crsenv{'internal.courseowner'} eq
8106: $env{'user.name'}.':'.$env{'user.domain'}) {
8107: $refused = '';
8108: }
8109: }
8110: }
8111: }
8112: }
8113: if ($refused) {
8114: &logthis('Refused custom assignrole: '.
8115: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8116: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8117: return 'refused';
8118: }
1.104 www 8119: }
1.21 www 8120: $mrole='cr';
1.678 raeburn 8121: } elsif ($role =~ /^gr\//) {
8122: my $cwogrp=$url;
1.811 albertel 8123: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8124: unless (&allowed('mdg',$cwogrp)) {
8125: &logthis('Refused group assignrole: '.
8126: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8127: $env{'user.name'}.' at '.$env{'user.domain'});
8128: return 'refused';
8129: }
8130: $mrole='gr';
1.21 www 8131: } else {
1.82 www 8132: my $cwosec=$url;
1.811 albertel 8133: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8134: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8135: my $refused;
8136: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8137: if (!(&allowed('c'.$role,$url))) {
8138: $refused = 1;
8139: }
8140: } else {
8141: $refused = 1;
8142: }
1.947 raeburn 8143: if ($refused) {
1.1045 raeburn 8144: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8145: if (!$selfenroll && $context eq 'course') {
8146: my %crsenv;
8147: if ($role eq 'cc' || $role eq 'co') {
8148: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8149: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8150: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8151: if ($crsenv{'internal.courseowner'} eq
8152: $env{'user.name'}.':'.$env{'user.domain'}) {
8153: $refused = '';
8154: }
8155: }
8156: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8157: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8158: if ($crsenv{'internal.courseowner'} eq
8159: $env{'user.name'}.':'.$env{'user.domain'}) {
8160: $refused = '';
8161: }
8162: }
8163: }
8164: }
8165: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8166: $refused = '';
1.1017 raeburn 8167: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8168: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8169: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8170: my $wrongcc;
8171: if ($cnum =~ /^$match_community$/) {
8172: $wrongcc = 1 if ($role eq 'cc');
8173: } else {
8174: $wrongcc = 1 if ($role eq 'co');
8175: }
8176: unless ($wrongcc) {
8177: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8178: if ($crsenv{'internal.courseowner'} eq
8179: $env{'user.name'}.':'.$env{'user.domain'}) {
8180: $refused = '';
8181: }
1.1017 raeburn 8182: }
8183: }
1.1172.2.9 raeburn 8184: } elsif ($context eq 'requestauthor') {
8185: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8186: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8187: if ($env{'environment.requestauthor'} eq 'automatic') {
8188: $refused = '';
8189: } else {
8190: my %domdefaults = &get_domain_defaults($udom);
8191: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8192: my $checkbystatus;
8193: if ($env{'user.adv'}) {
8194: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8195: if ($disposition eq 'automatic') {
8196: $refused = '';
8197: } elsif ($disposition eq '') {
8198: $checkbystatus = 1;
8199: }
8200: } else {
8201: $checkbystatus = 1;
8202: }
8203: if ($checkbystatus) {
8204: if ($env{'environment.inststatus'}) {
8205: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8206: foreach my $type (@inststatuses) {
8207: if (($type ne '') &&
8208: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8209: $refused = '';
8210: }
8211: }
8212: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8213: $refused = '';
8214: }
8215: }
8216: }
8217: }
8218: }
1.1017 raeburn 8219: }
8220: if ($refused) {
1.947 raeburn 8221: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8222: ' '.$role.' '.$end.' '.$start.' by '.
8223: $env{'user.name'}.' at '.$env{'user.domain'});
8224: return 'refused';
8225: }
1.932 raeburn 8226: }
1.1131 raeburn 8227: } elsif ($role eq 'au') {
8228: if ($url ne '/'.$udom.'/') {
8229: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8230: ' to assign author role for '.$uname.':'.$udom.
8231: ' in domain: '.$url.' refused (wrong domain).');
8232: return 'refused';
8233: }
1.104 www 8234: }
1.21 www 8235: $mrole=$role;
8236: }
1.620 albertel 8237: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8238: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8239: if ($end) { $command.='_'.$end; }
1.21 www 8240: if ($start) {
8241: if ($end) {
1.81 www 8242: $command.='_'.$start;
1.21 www 8243: } else {
1.81 www 8244: $command.='_0_'.$start;
1.21 www 8245: }
8246: }
1.739 raeburn 8247: my $origstart = $start;
8248: my $origend = $end;
1.957 raeburn 8249: my $delflag;
1.357 www 8250: # actually delete
8251: if ($deleteflag) {
1.373 www 8252: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8253: # modify command to delete the role
1.620 albertel 8254: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8255: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8256: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8257: # set start and finish to negative values for userrolelog
8258: $start=-1;
8259: $end=-1;
1.957 raeburn 8260: $delflag = 1;
1.357 www 8261: }
8262: }
8263: # send command
1.349 www 8264: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8265: # log new user role if status is ok
1.349 www 8266: if ($answer eq 'ok') {
1.663 raeburn 8267: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8268: if (($role eq 'cc') || ($role eq 'in') ||
8269: ($role eq 'ep') || ($role eq 'ad') ||
8270: ($role eq 'ta') || ($role eq 'st') ||
8271: ($role=~/^cr/) || ($role eq 'gr') ||
8272: ($role eq 'co')) {
1.1172.2.13 raeburn 8273: # for course roles, perform group memberships changes triggered by role change.
8274: unless ($role =~ /^gr/) {
8275: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8276: $origstart,$selfenroll,$context);
8277: }
1.1172.2.9 raeburn 8278: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8279: $selfenroll,$context);
8280: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8281: ($role eq 'au') || ($role eq 'dc')) {
8282: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8283: $context);
8284: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8285: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8286: $context);
8287: }
1.1053 raeburn 8288: if ($role eq 'cc') {
8289: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8290: }
1.349 www 8291: }
8292: return $answer;
1.169 harris41 8293: }
8294:
1.1053 raeburn 8295: sub autoupdate_coowners {
8296: my ($url,$end,$start,$uname,$udom) = @_;
8297: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8298: if (($cdom ne '') && ($cnum ne '')) {
8299: my $now = time;
8300: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8301: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8302: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8303: my $instcode = $coursehash{'internal.coursecode'};
8304: if ($instcode ne '') {
1.1056 raeburn 8305: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8306: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8307: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8308: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8309: if ($result eq 'valid') {
8310: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8311: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8312: push(@newcoowners,$coowner);
8313: }
8314: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8315: push(@newcoowners,$uname.':'.$udom);
8316: }
8317: @newcoowners = sort(@newcoowners);
8318: } else {
8319: push(@newcoowners,$uname.':'.$udom);
8320: }
8321: } else {
8322: if ($coursehash{'internal.co-owners'}) {
8323: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8324: unless ($coowner eq $uname.':'.$udom) {
8325: push(@newcoowners,$coowner);
8326: }
8327: }
8328: unless (@newcoowners > 0) {
8329: $delcoowners = 1;
8330: $coowners = '';
8331: }
8332: }
8333: }
8334: if (@newcoowners || $delcoowners) {
8335: &store_coowners($cdom,$cnum,$coursehash{'home'},
8336: $delcoowners,@newcoowners);
8337: }
8338: }
8339: }
8340: }
8341: }
8342: }
8343: }
8344:
8345: sub store_coowners {
8346: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8347: my $cid = $cdom.'_'.$cnum;
8348: my ($coowners,$delresult,$putresult);
8349: if (@newcoowners) {
8350: $coowners = join(',',@newcoowners);
8351: my %coownershash = (
8352: 'internal.co-owners' => $coowners,
8353: );
8354: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8355: if ($putresult eq 'ok') {
8356: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8357: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8358: }
8359: }
8360: }
8361: if ($delcoowners) {
8362: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8363: if ($delresult eq 'ok') {
8364: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8365: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8366: }
8367: }
8368: }
8369: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8370: my %crsinfo =
8371: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8372: if (ref($crsinfo{$cid}) eq 'HASH') {
8373: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8374: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8375: }
8376: }
8377: }
8378:
1.169 harris41 8379: # -------------------------------------------------- Modify user authentication
1.197 www 8380: # Overrides without validation
8381:
1.169 harris41 8382: sub modifyuserauth {
8383: my ($udom,$uname,$umode,$upass)=@_;
8384: my $uhome=&homeserver($uname,$udom);
1.197 www 8385: unless (&allowed('mau',$udom)) { return 'refused'; }
8386: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8387: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8388: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8389: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8390: &escape($upass),$uhome);
1.620 albertel 8391: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8392: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8393: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8394: &log($udom,,$uname,$uhome,
1.620 albertel 8395: 'Authentication changed by '.$env{'user.domain'}.', '.
8396: $env{'user.name'}.', '.$umode.
1.197 www 8397: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8398: unless ($reply eq 'ok') {
1.197 www 8399: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8400: return 'error: '.$reply;
8401: }
1.170 harris41 8402: return 'ok';
1.80 www 8403: }
8404:
1.81 www 8405: # --------------------------------------------------------------- Modify a user
1.80 www 8406:
1.81 www 8407: sub modifyuser {
1.206 matthew 8408: my ($udom, $uname, $uid,
8409: $umode, $upass, $first,
8410: $middle, $last, $gene,
1.1058 raeburn 8411: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8412: $udom= &LONCAPA::clean_domain($udom);
8413: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8414: my $showcandelete = 'none';
8415: if (ref($candelete) eq 'ARRAY') {
8416: if (@{$candelete} > 0) {
8417: $showcandelete = join(', ',@{$candelete});
8418: }
8419: }
1.81 www 8420: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8421: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8422: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8423: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8424: ' desiredhome not specified').
1.620 albertel 8425: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8426: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8427: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8428: my $newuser;
8429: if ($uhome eq 'no_host') {
8430: $newuser = 1;
8431: }
1.80 www 8432: # ----------------------------------------------------------------- Create User
1.406 albertel 8433: if (($uhome eq 'no_host') &&
8434: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8435: my $unhome='';
1.844 albertel 8436: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8437: $unhome = $desiredhome;
1.620 albertel 8438: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8439: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8440: } else { # load balancing routine for determining $unhome
1.81 www 8441: my $loadm=10000000;
1.841 albertel 8442: my %servers = &get_servers($udom,'library');
8443: foreach my $tryserver (keys(%servers)) {
8444: my $answer=reply('load',$tryserver);
8445: if (($answer=~/\d+/) && ($answer<$loadm)) {
8446: $loadm=$answer;
8447: $unhome=$tryserver;
8448: }
1.80 www 8449: }
8450: }
8451: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8452: return 'error: unable to find a home server for '.$uname.
8453: ' in domain '.$udom;
1.80 www 8454: }
8455: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8456: &escape($upass),$unhome);
8457: unless ($reply eq 'ok') {
8458: return 'error: '.$reply;
8459: }
1.230 stredwic 8460: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8461: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8462: return 'error: unable verify users home machine.';
1.80 www 8463: }
1.209 matthew 8464: } # End of creation of new user
1.80 www 8465: # ---------------------------------------------------------------------- Add ID
8466: if ($uid) {
8467: $uid=~tr/A-Z/a-z/;
8468: my %uidhash=&idrget($udom,$uname);
1.196 www 8469: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8470: && (!$forceid)) {
1.80 www 8471: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8472: return 'error: user id "'.$uid.'" does not match '.
8473: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8474: }
8475: } else {
8476: &idput($udom,($uname => $uid));
8477: }
8478: }
8479: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8480: my @tmp=&get('environment',
1.899 raeburn 8481: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8482: 'permanentemail','inststatus'],
1.134 albertel 8483: $udom,$uname);
1.1075 raeburn 8484: my (%names,%oldnames);
1.313 matthew 8485: if ($tmp[0] =~ m/^error:.*/) {
8486: %names=();
8487: } else {
8488: %names = @tmp;
1.1075 raeburn 8489: %oldnames = %names;
1.313 matthew 8490: }
1.388 www 8491: #
1.1058 raeburn 8492: # If name, email and/or uid are blank (e.g., because an uploaded file
8493: # of users did not contain them), do not overwrite existing values
8494: # unless field is in $candelete array ref.
8495: #
8496:
8497: my @fields = ('firstname','middlename','lastname','generation',
8498: 'permanentemail','id');
8499: my %newvalues;
8500: if (ref($candelete) eq 'ARRAY') {
8501: foreach my $field (@fields) {
8502: if (grep(/^\Q$field\E$/,@{$candelete})) {
8503: if ($field eq 'firstname') {
8504: $names{$field} = $first;
8505: } elsif ($field eq 'middlename') {
8506: $names{$field} = $middle;
8507: } elsif ($field eq 'lastname') {
8508: $names{$field} = $last;
8509: } elsif ($field eq 'generation') {
8510: $names{$field} = $gene;
8511: } elsif ($field eq 'permanentemail') {
8512: $names{$field} = $email;
8513: } elsif ($field eq 'id') {
8514: $names{$field} = $uid;
8515: }
8516: }
8517: }
8518: }
1.388 www 8519: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8520: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8521: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8522: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8523: if ($email) {
8524: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8525: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8526: }
1.899 raeburn 8527: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8528: if (defined($inststatus)) {
8529: $names{'inststatus'} = '';
8530: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8531: if (ref($usertypes) eq 'HASH') {
8532: my @okstatuses;
8533: foreach my $item (split(/:/,$inststatus)) {
8534: if (defined($usertypes->{$item})) {
8535: push(@okstatuses,$item);
8536: }
8537: }
8538: if (@okstatuses) {
8539: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8540: }
8541: }
8542: }
1.1075 raeburn 8543: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8544: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8545: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8546: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8547: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8548: } else {
8549: $logmsg .= ' during self creation';
8550: }
1.1075 raeburn 8551: my $changed;
8552: if ($newuser) {
8553: $changed = 1;
8554: } else {
8555: foreach my $field (@fields) {
8556: if ($names{$field} ne $oldnames{$field}) {
8557: $changed = 1;
8558: last;
8559: }
8560: }
8561: }
8562: unless ($changed) {
8563: $logmsg = 'No changes in user information needed for: '.$logmsg;
8564: &logthis($logmsg);
8565: return 'ok';
8566: }
8567: my $reply = &put('environment', \%names, $udom,$uname);
8568: if ($reply ne 'ok') {
8569: return 'error: '.$reply;
8570: }
1.1087 raeburn 8571: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8572: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8573: }
1.1075 raeburn 8574: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8575: &devalidate_cache_new('namescache',$uname.':'.$udom);
8576: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8577: &logthis($logmsg);
1.134 albertel 8578: return 'ok';
1.80 www 8579: }
8580:
1.81 www 8581: # -------------------------------------------------------------- Modify student
1.80 www 8582:
1.81 www 8583: sub modifystudent {
8584: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8585: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8586: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8587: if (!$cid) {
1.620 albertel 8588: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8589: return 'not_in_class';
8590: }
1.80 www 8591: }
8592: # --------------------------------------------------------------- Make the user
1.81 www 8593: my $reply=&modifyuser
1.209 matthew 8594: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8595: $desiredhome,$email,$inststatus);
1.80 www 8596: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8597: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8598: # student's environment
1.297 matthew 8599: $uid = undef if (!$forceid);
1.455 albertel 8600: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8601: $gene,$usec,$end,$start,$type,$locktype,
8602: $cid,$selfenroll,$context,$credits);
1.297 matthew 8603: return $reply;
8604: }
8605:
8606: sub modify_student_enrollment {
1.1172.2.23 raeburn 8607: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8608: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8609: my ($cdom,$cnum,$chome);
8610: if (!$cid) {
1.620 albertel 8611: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8612: return 'not_in_class';
8613: }
1.620 albertel 8614: $cdom=$env{'course.'.$cid.'.domain'};
8615: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8616: } else {
8617: ($cdom,$cnum)=split(/_/,$cid);
8618: }
1.620 albertel 8619: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8620: if (!$chome) {
1.457 raeburn 8621: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8622: }
1.455 albertel 8623: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8624: # Make sure the user exists
1.81 www 8625: my $uhome=&homeserver($uname,$udom);
8626: if (($uhome eq '') || ($uhome eq 'no_host')) {
8627: return 'error: no such user';
8628: }
1.297 matthew 8629: # Get student data if we were not given enough information
8630: if (!defined($first) || $first eq '' ||
8631: !defined($last) || $last eq '' ||
8632: !defined($uid) || $uid eq '' ||
8633: !defined($middle) || $middle eq '' ||
8634: !defined($gene) || $gene eq '') {
1.294 matthew 8635: # They did not supply us with enough data to enroll the student, so
8636: # we need to pick up more information.
1.297 matthew 8637: my %tmp = &get('environment',
1.294 matthew 8638: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8639: ,$udom,$uname);
8640:
1.800 albertel 8641: #foreach my $key (keys(%tmp)) {
8642: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8643: #}
1.294 matthew 8644: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8645: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8646: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8647: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8648: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8649: }
1.556 albertel 8650: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8651: my $user = "$uname:$udom";
8652: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8653: my $reply=cput('classlist',
1.1148 raeburn 8654: {$user =>
1.1172.2.19 raeburn 8655: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8656: $cdom,$cnum);
1.1148 raeburn 8657: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8658: &devalidate_getsection_cache($udom,$uname,$cid);
8659: } else {
1.81 www 8660: return 'error: '.$reply;
8661: }
1.297 matthew 8662: # Add student role to user
1.83 www 8663: my $uurl='/'.$cid;
1.81 www 8664: $uurl=~s/\_/\//g;
8665: if ($usec) {
8666: $uurl.='/'.$usec;
8667: }
1.1148 raeburn 8668: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8669: $selfenroll,$context);
8670: if ($result ne 'ok') {
8671: if ($old_entry{$user} ne '') {
8672: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8673: } else {
8674: $reply = &del('classlist',[$user],$cdom,$cnum);
8675: }
8676: }
8677: return $result;
1.21 www 8678: }
8679:
1.556 albertel 8680: sub format_name {
8681: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8682: my $name;
8683: if ($first ne 'lastname') {
8684: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8685: } else {
8686: if ($lastname=~/\S/) {
8687: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8688: $name=~s/\s+,/,/;
8689: } else {
8690: $name.= $firstname.' '.$middlename.' '.$generation;
8691: }
8692: }
8693: $name=~s/^\s+//;
8694: $name=~s/\s+$//;
8695: $name=~s/\s+/ /g;
8696: return $name;
8697: }
8698:
1.84 www 8699: # ------------------------------------------------- Write to course preferences
8700:
8701: sub writecoursepref {
8702: my ($courseid,%prefs)=@_;
8703: $courseid=~s/^\///;
8704: $courseid=~s/\_/\//g;
8705: my ($cdomain,$cnum)=split(/\//,$courseid);
8706: my $chome=homeserver($cnum,$cdomain);
8707: if (($chome eq '') || ($chome eq 'no_host')) {
8708: return 'error: no such course';
8709: }
8710: my $cstring='';
1.800 albertel 8711: foreach my $pref (keys(%prefs)) {
8712: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8713: }
1.84 www 8714: $cstring=~s/\&$//;
8715: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8716: }
8717:
8718: # ---------------------------------------------------------- Make/modify course
8719:
8720: sub createcourse {
1.741 raeburn 8721: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8722: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8723: $url=&declutter($url);
8724: my $cid='';
1.1028 raeburn 8725: if ($context eq 'requestcourses') {
8726: my $can_create = 0;
8727: my ($ownername,$ownerdom) = split(':',$course_owner);
8728: if ($udom eq $ownerdom) {
8729: if (&usertools_access($ownername,$ownerdom,$category,undef,
8730: $context)) {
8731: $can_create = 1;
8732: }
8733: } else {
8734: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8735: $category);
8736: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8737: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8738: if (@curr > 0) {
8739: my @options = qw(approval validate autolimit);
8740: my $optregex = join('|',@options);
8741: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8742: $can_create = 1;
8743: }
8744: }
8745: }
8746: }
8747: if ($can_create) {
8748: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8749: unless (&allowed('ccc',$udom)) {
8750: return 'refused';
8751: }
1.1017 raeburn 8752: }
8753: } else {
8754: return 'refused';
8755: }
1.1028 raeburn 8756: } elsif (!&allowed('ccc',$udom)) {
8757: return 'refused';
1.84 www 8758: }
1.1011 raeburn 8759: # --------------------------------------------------------------- Get Unique ID
8760: my $uname;
8761: if ($cnum =~ /^$match_courseid$/) {
8762: my $chome=&homeserver($cnum,$udom,'true');
8763: if (($chome eq '') || ($chome eq 'no_host')) {
8764: $uname = $cnum;
8765: } else {
1.1038 raeburn 8766: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8767: }
8768: } else {
1.1038 raeburn 8769: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8770: }
8771: return $uname if ($uname =~ /^error/);
8772: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8773: if (!defined($course_server)) {
8774: if (defined(&domain($udom,'primary'))) {
8775: $course_server = &domain($udom,'primary');
8776: } else {
8777: $course_server = $env{'user.home'};
8778: }
8779: }
8780: my %host_servers =
8781: &Apache::lonnet::get_servers($udom,'library');
8782: unless ($host_servers{$course_server}) {
8783: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8784: }
1.84 www 8785: # ------------------------------------------------------------- Make the course
8786: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8787: $course_server);
1.84 www 8788: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8789: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8790: if (($uhome eq '') || ($uhome eq 'no_host')) {
8791: return 'error: no such course';
8792: }
1.271 www 8793: # ----------------------------------------------------------------- Course made
1.516 raeburn 8794: # log existence
1.1029 raeburn 8795: my $now = time;
1.918 raeburn 8796: my $newcourse = {
8797: $udom.'_'.$uname => {
1.921 raeburn 8798: description => $description,
8799: inst_code => $inst_code,
8800: owner => $course_owner,
8801: type => $crstype,
1.1029 raeburn 8802: creator => $env{'user.name'}.':'.
8803: $env{'user.domain'},
8804: created => $now,
8805: context => $context,
1.918 raeburn 8806: },
8807: };
1.921 raeburn 8808: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8809: # set toplevel url
1.271 www 8810: my $topurl=$url;
8811: unless ($nonstandard) {
8812: # ------------------------------------------ For standard courses, make top url
8813: my $mapurl=&clutter($url);
1.278 www 8814: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8815: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8816: <map>
8817: <resource id="1" type="start"></resource>
8818: <resource id="2" src="$mapurl"></resource>
8819: <resource id="3" type="finish"></resource>
8820: <link index="1" from="1" to="2"></link>
8821: <link index="2" from="2" to="3"></link>
8822: </map>
8823: ENDINITMAP
8824: $topurl=&declutter(
1.638 albertel 8825: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8826: );
8827: }
8828: # ----------------------------------------------------------- Write preferences
1.84 www 8829: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8830: ('description' => $description,
8831: 'url' => $topurl,
8832: 'internal.creator' => $env{'user.name'}.':'.
8833: $env{'user.domain'},
8834: 'internal.created' => $now,
8835: 'internal.creationcontext' => $context)
8836: );
1.84 www 8837: return '/'.$udom.'/'.$uname;
8838: }
8839:
1.1011 raeburn 8840: # ------------------------------------------------------------------- Create ID
8841: sub generate_coursenum {
1.1038 raeburn 8842: my ($udom,$crstype) = @_;
1.1011 raeburn 8843: my $domdesc = &domain($udom);
8844: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8845: my $first;
8846: if ($crstype eq 'Community') {
8847: $first = '0';
8848: } else {
8849: $first = int(1+rand(9));
8850: }
8851: my $uname=$first.
1.1011 raeburn 8852: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8853: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8854: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8855: # ----------------------------------------------- Make sure that does not exist
8856: my $uhome=&homeserver($uname,$udom,'true');
8857: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8858: if ($crstype eq 'Community') {
8859: $first = '0';
8860: } else {
8861: $first = int(1+rand(9));
8862: }
8863: $uname=$first.
1.1011 raeburn 8864: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8865: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8866: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8867: $uhome=&homeserver($uname,$udom,'true');
8868: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8869: return 'error: unable to generate unique course-ID';
8870: }
8871: }
8872: return $uname;
8873: }
8874:
1.813 albertel 8875: sub is_course {
1.1167 droeschl 8876: my ($cdom, $cnum) = scalar(@_) == 1 ?
8877: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8878:
8879: return unless $cdom and $cnum;
8880:
8881: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8882: '.');
8883:
1.1172.2.23 raeburn 8884: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8885: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8886: }
8887:
1.1015 raeburn 8888: sub store_userdata {
8889: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8890: my $result;
1.1016 raeburn 8891: if ($datakey ne '') {
1.1013 raeburn 8892: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8893: if ($udom eq '' || $uname eq '') {
8894: $udom = $env{'user.domain'};
8895: $uname = $env{'user.name'};
8896: }
8897: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8898: if (($uhome eq '') || ($uhome eq 'no_host')) {
8899: $result = 'error: no_host';
8900: } else {
8901: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8902: $storehash->{'host'} = $perlvar{'lonHostID'};
8903:
8904: my $namevalue='';
8905: foreach my $key (keys(%{$storehash})) {
8906: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8907: }
8908: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8909: unless ($namespace eq 'courserequests') {
8910: $datakey = &escape($datakey);
8911: }
1.1105 raeburn 8912: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8913: $namevalue,$uhome);
1.1013 raeburn 8914: }
8915: } else {
8916: $result = 'error: data to store was not a hash reference';
8917: }
8918: } else {
8919: $result= 'error: invalid requestkey';
8920: }
8921: return $result;
8922: }
8923:
1.21 www 8924: # ---------------------------------------------------------- Assign Custom Role
8925:
8926: sub assigncustomrole {
1.957 raeburn 8927: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8928: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8929: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8930: }
8931:
8932: # ----------------------------------------------------------------- Revoke Role
8933:
8934: sub revokerole {
1.957 raeburn 8935: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8936: my $now=time;
1.965 raeburn 8937: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8938: }
8939:
8940: # ---------------------------------------------------------- Revoke Custom Role
8941:
8942: sub revokecustomrole {
1.957 raeburn 8943: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8944: my $now=time;
1.357 www 8945: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8946: $deleteflag,$selfenroll,$context);
1.17 www 8947: }
8948:
1.533 banghart 8949: # ------------------------------------------------------------ Disk usage
1.535 albertel 8950: sub diskusage {
1.955 raeburn 8951: my ($udom,$uname,$directorypath,$getpropath)=@_;
8952: $directorypath =~ s/\/$//;
8953: my $listing=&reply('du2:'.&escape($directorypath).':'
8954: .&escape($getpropath).':'.&escape($uname).':'
8955: .&escape($udom),homeserver($uname,$udom));
8956: if ($listing eq 'unknown_cmd') {
8957: if ($getpropath) {
8958: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8959: }
8960: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8961: }
1.514 albertel 8962: return $listing;
1.512 banghart 8963: }
8964:
1.566 banghart 8965: sub is_locked {
1.1096 raeburn 8966: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8967: my @check;
8968: my $is_locked;
1.1093 raeburn 8969: push (@check,$file_name);
1.613 albertel 8970: my %locked = &get('file_permissions',\@check,
1.620 albertel 8971: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8972: my ($tmp)=keys(%locked);
8973: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8974:
1.566 banghart 8975: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8976: $is_locked = 'false';
8977: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8978: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8979: $is_locked = 'true';
1.1096 raeburn 8980: if (ref($which) eq 'ARRAY') {
8981: push(@{$which},$entry);
8982: } else {
8983: last;
8984: }
1.745 raeburn 8985: }
8986: }
1.566 banghart 8987: } else {
8988: $is_locked = 'false';
8989: }
1.1093 raeburn 8990: return $is_locked;
1.566 banghart 8991: }
8992:
1.759 albertel 8993: sub declutter_portfile {
8994: my ($file) = @_;
1.833 albertel 8995: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8996: return $file;
8997: }
8998:
1.559 banghart 8999: # ------------------------------------------------------------- Mark as Read Only
9000:
9001: sub mark_as_readonly {
9002: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9003: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9004: my ($tmp)=keys(%current_permissions);
9005: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9006: foreach my $file (@{$files}) {
1.759 albertel 9007: $file = &declutter_portfile($file);
1.561 banghart 9008: push(@{$current_permissions{$file}},$what);
1.559 banghart 9009: }
1.613 albertel 9010: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9011: return;
9012: }
9013:
1.572 banghart 9014: # ------------------------------------------------------------Save Selected Files
9015:
9016: sub save_selected_files {
9017: my ($user, $path, @files) = @_;
9018: my $filename = $user."savedfiles";
1.573 banghart 9019: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9020: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9021: foreach my $file (@files) {
1.620 albertel 9022: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9023: }
9024: foreach my $file (@other_files) {
1.574 banghart 9025: print (OUT $file."\n");
1.572 banghart 9026: }
1.574 banghart 9027: close (OUT);
1.572 banghart 9028: return 'ok';
9029: }
9030:
1.574 banghart 9031: sub clear_selected_files {
9032: my ($user) = @_;
9033: my $filename = $user."savedfiles";
1.1117 foxr 9034: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9035: print (OUT undef);
9036: close (OUT);
9037: return ("ok");
9038: }
9039:
1.572 banghart 9040: sub files_in_path {
9041: my ($user, $path) = @_;
9042: my $filename = $user."savedfiles";
9043: my %return_files;
1.1117 foxr 9044: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9045: while (my $line_in = <IN>) {
1.574 banghart 9046: chomp ($line_in);
9047: my @paths_and_file = split (m!/!, $line_in);
9048: my $file_part = pop (@paths_and_file);
9049: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9050: $path_part.='/';
9051: my $path_and_file = $path_part.$file_part;
9052: if ($path_part eq $path) {
9053: $return_files{$file_part}= 'selected';
9054: }
9055: }
1.574 banghart 9056: close (IN);
9057: return (\%return_files);
1.572 banghart 9058: }
9059:
9060: # called in portfolio select mode, to show files selected NOT in current directory
9061: sub files_not_in_path {
9062: my ($user, $path) = @_;
9063: my $filename = $user."savedfiles";
9064: my @return_files;
9065: my $path_part;
1.1117 foxr 9066: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9067: while (my $line = <IN>) {
1.572 banghart 9068: #ok, I know it's clunky, but I want it to work
1.800 albertel 9069: my @paths_and_file = split(m|/|, $line);
9070: my $file_part = pop(@paths_and_file);
9071: chomp($file_part);
9072: my $path_part = join('/', @paths_and_file);
1.572 banghart 9073: $path_part .= '/';
9074: my $path_and_file = $path_part.$file_part;
9075: if ($path_part ne $path) {
1.800 albertel 9076: push(@return_files, ($path_and_file));
1.572 banghart 9077: }
9078: }
1.800 albertel 9079: close(OUT);
1.574 banghart 9080: return (@return_files);
1.572 banghart 9081: }
9082:
1.745 raeburn 9083: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9084:
1.745 raeburn 9085: sub get_portfile_permissions {
9086: my ($domain,$user) = @_;
1.613 albertel 9087: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9088: my ($tmp)=keys(%current_permissions);
9089: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9090: return \%current_permissions;
9091: }
9092:
9093: #---------------------------------------------Get portfolio file access controls
9094:
1.749 raeburn 9095: sub get_access_controls {
1.745 raeburn 9096: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9097: my %access;
9098: my $real_file = $file;
9099: $file =~ s/\.meta$//;
1.745 raeburn 9100: if (defined($file)) {
1.749 raeburn 9101: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9102: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9103: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9104: }
9105: }
1.745 raeburn 9106: } else {
1.749 raeburn 9107: foreach my $key (keys(%{$current_permissions})) {
9108: if ($key =~ /\0accesscontrol$/) {
9109: if (defined($group)) {
9110: if ($key !~ m-^\Q$group\E/-) {
9111: next;
9112: }
9113: }
9114: my ($fullpath) = split(/\0/,$key);
9115: if (ref($$current_permissions{$key}) eq 'HASH') {
9116: foreach my $control (keys(%{$$current_permissions{$key}})) {
9117: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9118: }
9119: }
9120: }
9121: }
9122: }
9123: return %access;
9124: }
9125:
9126: sub modify_access_controls {
9127: my ($file_name,$changes,$domain,$user)=@_;
9128: my ($outcome,$deloutcome);
9129: my %store_permissions;
9130: my %new_values;
9131: my %new_control;
9132: my %translation;
9133: my @deletions = ();
9134: my $now = time;
9135: if (exists($$changes{'activate'})) {
9136: if (ref($$changes{'activate'}) eq 'HASH') {
9137: my @newitems = sort(keys(%{$$changes{'activate'}}));
9138: my $numnew = scalar(@newitems);
9139: for (my $i=0; $i<$numnew; $i++) {
9140: my $newkey = $newitems[$i];
9141: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9142: if ($newkey =~ /^\d+:/) {
9143: $newkey =~ s/^(\d+)/$newid/;
9144: $translation{$1} = $newid;
9145: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9146: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9147: $translation{$1} = $newid;
9148: }
1.749 raeburn 9149: $new_values{$file_name."\0".$newkey} =
9150: $$changes{'activate'}{$newitems[$i]};
9151: $new_control{$newkey} = $now;
9152: }
9153: }
9154: }
9155: my %todelete;
9156: my %changed_items;
9157: foreach my $action ('delete','update') {
9158: if (exists($$changes{$action})) {
9159: if (ref($$changes{$action}) eq 'HASH') {
9160: foreach my $key (keys(%{$$changes{$action}})) {
9161: my ($itemnum) = ($key =~ /^([^:]+):/);
9162: if ($action eq 'delete') {
9163: $todelete{$itemnum} = 1;
9164: } else {
9165: $changed_items{$itemnum} = $key;
9166: }
9167: }
1.745 raeburn 9168: }
9169: }
1.749 raeburn 9170: }
9171: # get lock on access controls for file.
9172: my $lockhash = {
9173: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9174: ':'.$env{'user.domain'},
9175: };
9176: my $tries = 0;
9177: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9178:
9179: while (($gotlock ne 'ok') && $tries <3) {
9180: $tries ++;
9181: sleep 1;
9182: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9183: }
9184: if ($gotlock eq 'ok') {
9185: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9186: my ($tmp)=keys(%curr_permissions);
9187: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9188: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9189: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9190: if (ref($curr_controls) eq 'HASH') {
9191: foreach my $control_item (keys(%{$curr_controls})) {
9192: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9193: if (defined($todelete{$itemnum})) {
9194: push(@deletions,$file_name."\0".$control_item);
9195: } else {
9196: if (defined($changed_items{$itemnum})) {
9197: $new_control{$changed_items{$itemnum}} = $now;
9198: push(@deletions,$file_name."\0".$control_item);
9199: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9200: } else {
9201: $new_control{$control_item} = $$curr_controls{$control_item};
9202: }
9203: }
1.745 raeburn 9204: }
9205: }
9206: }
1.970 raeburn 9207: my ($group);
9208: if (&is_course($domain,$user)) {
9209: ($group,my $file) = split(/\//,$file_name,2);
9210: }
1.749 raeburn 9211: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9212: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9213: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9214: # remove lock
9215: my @del_lock = ($file_name."\0".'locked_access_records');
9216: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9217: my $sqlresult =
1.970 raeburn 9218: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9219: $group);
1.749 raeburn 9220: } else {
9221: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9222: }
1.749 raeburn 9223: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9224: }
9225:
1.827 raeburn 9226: sub make_public_indefinitely {
9227: my ($requrl) = @_;
9228: my $now = time;
9229: my $action = 'activate';
9230: my $aclnum = 0;
9231: if (&is_portfolio_url($requrl)) {
9232: my (undef,$udom,$unum,$file_name,$group) =
9233: &parse_portfolio_url($requrl);
9234: my $current_perms = &get_portfile_permissions($udom,$unum);
9235: my %access_controls = &get_access_controls($current_perms,
9236: $group,$file_name);
9237: foreach my $key (keys(%{$access_controls{$file_name}})) {
9238: my ($num,$scope,$end,$start) =
9239: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9240: if ($scope eq 'public') {
9241: if ($start <= $now && $end == 0) {
9242: $action = 'none';
9243: } else {
9244: $action = 'update';
9245: $aclnum = $num;
9246: }
9247: last;
9248: }
9249: }
9250: if ($action eq 'none') {
9251: return 'ok';
9252: } else {
9253: my %changes;
9254: my $newend = 0;
9255: my $newstart = $now;
9256: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9257: $changes{$action}{$newkey} = {
9258: type => 'public',
9259: time => {
9260: start => $newstart,
9261: end => $newend,
9262: },
9263: };
9264: my ($outcome,$deloutcome,$new_values,$translation) =
9265: &modify_access_controls($file_name,\%changes,$udom,$unum);
9266: return $outcome;
9267: }
9268: } else {
9269: return 'invalid';
9270: }
9271: }
9272:
1.745 raeburn 9273: #------------------------------------------------------Get Marked as Read Only
9274:
9275: sub get_marked_as_readonly {
9276: my ($domain,$user,$what,$group) = @_;
9277: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9278: my @readonly_files;
1.629 banghart 9279: my $cmp1=$what;
9280: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9281: while (my ($file_name,$value) = each(%{$current_permissions})) {
9282: if (defined($group)) {
9283: if ($file_name !~ m-^\Q$group\E/-) {
9284: next;
9285: }
9286: }
1.561 banghart 9287: if (ref($value) eq "ARRAY"){
9288: foreach my $stored_what (@{$value}) {
1.629 banghart 9289: my $cmp2=$stored_what;
1.759 albertel 9290: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9291: $cmp2=join('',@{$stored_what});
1.745 raeburn 9292: }
1.629 banghart 9293: if ($cmp1 eq $cmp2) {
1.561 banghart 9294: push(@readonly_files, $file_name);
1.745 raeburn 9295: last;
1.563 banghart 9296: } elsif (!defined($what)) {
9297: push(@readonly_files, $file_name);
1.745 raeburn 9298: last;
1.561 banghart 9299: }
9300: }
1.745 raeburn 9301: }
1.561 banghart 9302: }
9303: return @readonly_files;
9304: }
1.577 banghart 9305: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9306:
1.577 banghart 9307: sub get_marked_as_readonly_hash {
1.745 raeburn 9308: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9309: my %readonly_files;
1.745 raeburn 9310: while (my ($file_name,$value) = each(%{$current_permissions})) {
9311: if (defined($group)) {
9312: if ($file_name !~ m-^\Q$group\E/-) {
9313: next;
9314: }
9315: }
1.577 banghart 9316: if (ref($value) eq "ARRAY"){
9317: foreach my $stored_what (@{$value}) {
1.745 raeburn 9318: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9319: foreach my $lock_descriptor(@{$stored_what}) {
9320: if ($lock_descriptor eq 'graded') {
9321: $readonly_files{$file_name} = 'graded';
9322: } elsif ($lock_descriptor eq 'handback') {
9323: $readonly_files{$file_name} = 'handback';
9324: } else {
9325: if (!exists($readonly_files{$file_name})) {
9326: $readonly_files{$file_name} = 'locked';
9327: }
9328: }
1.745 raeburn 9329: }
1.750 banghart 9330: }
1.577 banghart 9331: }
9332: }
9333: }
9334: return %readonly_files;
9335: }
1.559 banghart 9336: # ------------------------------------------------------------ Unmark as Read Only
9337:
9338: sub unmark_as_readonly {
1.629 banghart 9339: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9340: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9341: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9342: $file_name = &declutter_portfile($file_name);
1.634 albertel 9343: my $symb_crs = $what;
9344: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9345: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9346: my ($tmp)=keys(%current_permissions);
9347: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9348: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9349: foreach my $file (@readonly_files) {
1.759 albertel 9350: my $clean_file = &declutter_portfile($file);
9351: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9352: my $current_locks = $current_permissions{$file};
1.563 banghart 9353: my @new_locks;
9354: my @del_keys;
9355: if (ref($current_locks) eq "ARRAY"){
9356: foreach my $locker (@{$current_locks}) {
1.632 albertel 9357: my $compare=$locker;
1.749 raeburn 9358: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9359: $compare=join('',@{$locker});
1.746 raeburn 9360: if ($compare ne $symb_crs) {
9361: push(@new_locks, $locker);
9362: }
1.563 banghart 9363: }
9364: }
1.650 albertel 9365: if (scalar(@new_locks) > 0) {
1.563 banghart 9366: $current_permissions{$file} = \@new_locks;
9367: } else {
9368: push(@del_keys, $file);
1.613 albertel 9369: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9370: delete($current_permissions{$file});
1.563 banghart 9371: }
9372: }
1.561 banghart 9373: }
1.613 albertel 9374: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9375: return;
9376: }
1.512 banghart 9377:
1.17 www 9378: # ------------------------------------------------------------ Directory lister
9379:
9380: sub dirlist {
1.955 raeburn 9381: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9382: $uri=~s/^\///;
9383: $uri=~s/\/$//;
1.253 stredwic 9384: my ($udom, $uname);
1.955 raeburn 9385: if ($getuserdir) {
1.253 stredwic 9386: $udom = $userdomain;
9387: $uname = $username;
1.955 raeburn 9388: } else {
9389: (undef,$udom,$uname)=split(/\//,$uri);
9390: if(defined($userdomain)) {
9391: $udom = $userdomain;
9392: }
9393: if(defined($username)) {
9394: $uname = $username;
9395: }
1.253 stredwic 9396: }
1.955 raeburn 9397: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9398:
1.955 raeburn 9399: $dirRoot = $perlvar{'lonDocRoot'};
9400: if (defined($getpropath)) {
9401: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9402: $dirRoot =~ s/\/$//;
1.955 raeburn 9403: } elsif (defined($getuserdir)) {
9404: my $subdir=$uname.'__';
9405: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9406: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9407: ."/$udom/$subdir/$uname";
9408: } elsif (defined($alternateRoot)) {
9409: $dirRoot = $alternateRoot;
1.751 banghart 9410: }
1.253 stredwic 9411:
9412: if($udom) {
9413: if($uname) {
1.1135 raeburn 9414: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9415: if ($uhome eq 'no_host') {
9416: return ([],'no_host');
9417: }
1.955 raeburn 9418: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9419: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9420: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9421: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9422: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9423: } else {
9424: @listing_results = map { &unescape($_); } split(/:/,$listing);
9425: }
1.605 matthew 9426: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9427: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9428: @listing_results = split(/:/,$listing);
9429: } else {
9430: @listing_results = map { &unescape($_); } split(/:/,$listing);
9431: }
1.1135 raeburn 9432: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9433: ($listing eq 'rejected') || ($listing eq 'refused') ||
9434: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9435: return ([],$listing);
9436: } else {
9437: return (\@listing_results);
1.1135 raeburn 9438: }
1.955 raeburn 9439: } elsif(!$alternateRoot) {
1.1136 raeburn 9440: my (%allusers,%listerror);
1.841 albertel 9441: my %servers = &get_servers($udom,'library');
1.955 raeburn 9442: foreach my $tryserver (keys(%servers)) {
9443: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9444: &escape($udom),$tryserver);
9445: if ($listing eq 'unknown_cmd') {
9446: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9447: $udom, $tryserver);
9448: } else {
9449: @listing_results = map { &unescape($_); } split(/:/,$listing);
9450: }
1.841 albertel 9451: if ($listing eq 'unknown_cmd') {
9452: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9453: $udom, $tryserver);
9454: @listing_results = split(/:/,$listing);
9455: } else {
9456: @listing_results =
9457: map { &unescape($_); } split(/:/,$listing);
9458: }
1.1136 raeburn 9459: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9460: ($listing eq 'rejected') || ($listing eq 'refused') ||
9461: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9462: $listerror{$tryserver} = $listing;
9463: } else {
1.841 albertel 9464: foreach my $line (@listing_results) {
9465: my ($entry) = split(/&/,$line,2);
9466: $allusers{$entry} = 1;
9467: }
9468: }
1.253 stredwic 9469: }
1.1136 raeburn 9470: my @alluserslist=();
1.800 albertel 9471: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9472: push(@alluserslist,$user.'&user');
1.253 stredwic 9473: }
1.1136 raeburn 9474: return (\@alluserslist);
1.253 stredwic 9475: } else {
1.1136 raeburn 9476: return ([],'missing username');
1.253 stredwic 9477: }
1.955 raeburn 9478: } elsif(!defined($getpropath)) {
1.1136 raeburn 9479: my $path = $perlvar{'lonDocRoot'}.'/res/';
9480: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9481: return (\@all_domains);
1.955 raeburn 9482: } else {
1.1136 raeburn 9483: return ([],'missing domain');
1.275 stredwic 9484: }
9485: }
9486:
9487: # --------------------------------------------- GetFileTimestamp
9488: # This function utilizes dirlist and returns the date stamp for
9489: # when it was last modified. It will also return an error of -1
9490: # if an error occurs
9491:
9492: sub GetFileTimestamp {
1.955 raeburn 9493: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9494: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9495: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9496: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9497: undef,$getuserdir);
9498: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9499: return -1;
9500: }
9501: if (ref($fileref) eq 'ARRAY') {
9502: my @stats = split('&',$fileref->[0]);
1.375 matthew 9503: # @stats contains first the filename, then the stat output
9504: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9505: } else {
9506: return -1;
1.253 stredwic 9507: }
1.26 www 9508: }
9509:
1.712 albertel 9510: sub stat_file {
9511: my ($uri) = @_;
1.787 albertel 9512: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9513:
1.955 raeburn 9514: my ($udom,$uname,$file);
1.712 albertel 9515: if ($uri =~ m-^/(uploaded|editupload)/-) {
9516: ($udom,$uname,$file) =
1.811 albertel 9517: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9518: $file = 'userfiles/'.$file;
9519: }
9520: if ($uri =~ m-^/res/-) {
9521: ($udom,$uname) =
1.807 albertel 9522: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9523: $file = $uri;
9524: }
9525:
9526: if (!$udom || !$uname || !$file) {
9527: # unable to handle the uri
9528: return ();
9529: }
1.956 raeburn 9530: my $getpropath;
9531: if ($file =~ /^userfiles\//) {
9532: $getpropath = 1;
9533: }
1.1136 raeburn 9534: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9535: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9536: return ();
9537: } else {
9538: if (ref($listref) eq 'ARRAY') {
9539: my @stats = split('&',$listref->[0]);
9540: shift(@stats); #filename is first
9541: return @stats;
9542: }
1.712 albertel 9543: }
9544: return ();
9545: }
9546:
1.26 www 9547: # -------------------------------------------------------- Value of a Condition
9548:
1.713 albertel 9549: # gets the value of a specific preevaluated condition
9550: # stored in the string $env{user.state.<cid>}
9551: # or looks up a condition reference in the bighash and if if hasn't
9552: # already been evaluated recurses into docondval to get the value of
9553: # the condition, then memoizing it to
9554: # $env{user.state.<cid>.<condition>}
1.40 www 9555: sub directcondval {
9556: my $number=shift;
1.620 albertel 9557: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9558: &Apache::lonuserstate::evalstate();
9559: }
1.713 albertel 9560: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9561: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9562: } elsif ($number =~ /^_/) {
9563: my $sub_condition;
9564: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9565: &GDBM_READER(),0640)) {
9566: $sub_condition=$bighash{'conditions'.$number};
9567: untie(%bighash);
9568: }
9569: my $value = &docondval($sub_condition);
1.949 raeburn 9570: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9571: return $value;
9572: }
1.620 albertel 9573: if ($env{'user.state.'.$env{'request.course.id'}}) {
9574: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9575: } else {
9576: return 2;
9577: }
9578: }
9579:
1.713 albertel 9580: # get the collection of conditions for this resource
1.26 www 9581: sub condval {
9582: my $condidx=shift;
1.54 www 9583: my $allpathcond='';
1.713 albertel 9584: foreach my $cond (split(/\|/,$condidx)) {
9585: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9586: $allpathcond.=
9587: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9588: }
1.191 harris41 9589: }
1.54 www 9590: $allpathcond=~s/\|$//;
1.713 albertel 9591: return &docondval($allpathcond);
9592: }
9593:
9594: #evaluates an expression of conditions
9595: sub docondval {
9596: my ($allpathcond) = @_;
9597: my $result=0;
9598: if ($env{'request.course.id'}
9599: && defined($allpathcond)) {
9600: my $operand='|';
9601: my @stack;
9602: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9603: if ($chunk eq '(') {
9604: push @stack,($operand,$result);
9605: } elsif ($chunk eq ')') {
9606: my $before=pop @stack;
9607: if (pop @stack eq '&') {
9608: $result=$result>$before?$before:$result;
9609: } else {
9610: $result=$result>$before?$result:$before;
9611: }
9612: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9613: $operand=$chunk;
9614: } else {
9615: my $new=directcondval($chunk);
9616: if ($operand eq '&') {
9617: $result=$result>$new?$new:$result;
9618: } else {
9619: $result=$result>$new?$result:$new;
9620: }
9621: }
9622: }
1.26 www 9623: }
9624: return $result;
1.421 albertel 9625: }
9626:
9627: # ---------------------------------------------------- Devalidate courseresdata
9628:
9629: sub devalidatecourseresdata {
9630: my ($coursenum,$coursedomain)=@_;
9631: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9632: &devalidate_cache_new('courseres',$hashid);
1.28 www 9633: }
9634:
1.763 www 9635:
1.200 www 9636: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9637: #
9638: # Parameters:
9639: # $coursenum - Number of the course.
9640: # $coursedomain - Domain at which the course was created.
9641: # Returns:
9642: # A hash of the course parameters along (I think) with timestamps
9643: # and version info.
1.877 foxr 9644:
1.624 albertel 9645: sub get_courseresdata {
9646: my ($coursenum,$coursedomain)=@_;
1.200 www 9647: my $coursehom=&homeserver($coursenum,$coursedomain);
9648: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9649: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9650: my %dumpreply;
1.417 albertel 9651: unless (defined($cached)) {
1.624 albertel 9652: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9653: $result=\%dumpreply;
1.251 albertel 9654: my ($tmp) = keys(%dumpreply);
9655: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9656: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9657: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9658: return $tmp;
1.416 albertel 9659: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9660: $result=undef;
1.599 albertel 9661: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9662: }
9663: }
1.624 albertel 9664: return $result;
9665: }
9666:
1.633 albertel 9667: sub devalidateuserresdata {
9668: my ($uname,$udom)=@_;
9669: my $hashid="$udom:$uname";
9670: &devalidate_cache_new('userres',$hashid);
9671: }
9672:
1.624 albertel 9673: sub get_userresdata {
9674: my ($uname,$udom)=@_;
9675: #most student don\'t have any data set, check if there is some data
9676: if (&EXT_cache_status($udom,$uname)) { return undef; }
9677:
9678: my $hashid="$udom:$uname";
9679: my ($result,$cached)=&is_cached_new('userres',$hashid);
9680: if (!defined($cached)) {
9681: my %resourcedata=&dump('resourcedata',$udom,$uname);
9682: $result=\%resourcedata;
9683: &do_cache_new('userres',$hashid,$result,600);
9684: }
9685: my ($tmp)=keys(%$result);
9686: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9687: return $result;
9688: }
9689: #error 2 occurs when the .db doesn't exist
9690: if ($tmp!~/error: 2 /) {
1.672 albertel 9691: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9692: " Trying to get resource data for ".
9693: $uname." at ".$udom.": ".
9694: $tmp."</font>");
9695: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9696: #&EXT_cache_set($udom,$uname);
9697: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9698: undef($tmp); # not really an error so don't send it back
1.624 albertel 9699: }
9700: return $tmp;
9701: }
1.879 foxr 9702: #----------------------------------------------- resdata - return resource data
9703: # Purpose:
9704: # Return resource data for either users or for a course.
9705: # Parameters:
9706: # $name - Course/user name.
9707: # $domain - Name of the domain the user/course is registered on.
9708: # $type - Type of thing $name is (must be 'course' or 'user'
9709: # @which - Array of names of resources desired.
9710: # Returns:
9711: # The value of the first reasource in @which that is found in the
9712: # resource hash.
9713: # Exceptional Conditions:
9714: # If the $type passed in is not valid (not the string 'course' or
9715: # 'user', an undefined reference is returned.
9716: # If none of the resources are found, an undef is returned
1.624 albertel 9717: sub resdata {
9718: my ($name,$domain,$type,@which)=@_;
9719: my $result;
9720: if ($type eq 'course') {
9721: $result=&get_courseresdata($name,$domain);
9722: } elsif ($type eq 'user') {
9723: $result=&get_userresdata($name,$domain);
9724: }
9725: if (!ref($result)) { return $result; }
1.251 albertel 9726: foreach my $item (@which) {
1.927 albertel 9727: if (defined($result->{$item->[0]})) {
9728: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9729: }
1.250 albertel 9730: }
1.291 albertel 9731: return undef;
1.200 www 9732: }
9733:
1.1172.2.31 raeburn 9734: sub get_numsuppfiles {
9735: my ($cnum,$cdom,$ignorecache)=@_;
9736: my $hashid=$cnum.':'.$cdom;
9737: my ($suppcount,$cached);
9738: unless ($ignorecache) {
9739: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9740: }
9741: unless (defined($cached)) {
9742: my $chome=&homeserver($cnum,$cdom);
9743: unless ($chome eq 'no_host') {
9744: ($suppcount,my $errors) = (0,0);
9745: my $suppmap = 'supplemental.sequence';
9746: ($suppcount,$errors) =
9747: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9748: }
9749: &do_cache_new('suppcount',$hashid,$suppcount,600);
9750: }
9751: return $suppcount;
9752: }
9753:
1.379 matthew 9754: #
9755: # EXT resource caching routines
9756: #
9757:
9758: sub clear_EXT_cache_status {
1.383 albertel 9759: &delenv('cache.EXT.');
1.379 matthew 9760: }
9761:
9762: sub EXT_cache_status {
9763: my ($target_domain,$target_user) = @_;
1.383 albertel 9764: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9765: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9766: # We know already the user has no data
9767: return 1;
9768: } else {
9769: return 0;
9770: }
9771: }
9772:
9773: sub EXT_cache_set {
9774: my ($target_domain,$target_user) = @_;
1.383 albertel 9775: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9776: #&appenv({$cachename => time});
1.379 matthew 9777: }
9778:
1.28 www 9779: # --------------------------------------------------------- Value of a Variable
1.58 www 9780: sub EXT {
1.715 albertel 9781:
1.1172.2.28 raeburn 9782: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9783: unless ($varname) { return ''; }
1.218 albertel 9784: #get real user name/domain, courseid and symb
9785: my $courseid;
1.359 albertel 9786: my $publicuser;
1.427 www 9787: if ($symbparm) {
9788: $symbparm=&get_symb_from_alias($symbparm);
9789: }
1.218 albertel 9790: if (!($uname && $udom)) {
1.790 albertel 9791: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9792: if (!$symbparm) { $symbparm=$cursymb; }
9793: } else {
1.620 albertel 9794: $courseid=$env{'request.course.id'};
1.218 albertel 9795: }
1.48 www 9796: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9797: my $rest;
1.320 albertel 9798: if (defined($therest[0])) {
1.48 www 9799: $rest=join('.',@therest);
9800: } else {
9801: $rest='';
9802: }
1.320 albertel 9803:
1.57 www 9804: my $qualifierrest=$qualifier;
9805: if ($rest) { $qualifierrest.='.'.$rest; }
9806: my $spacequalifierrest=$space;
9807: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9808: if ($realm eq 'user') {
1.48 www 9809: # --------------------------------------------------------------- user.resource
9810: if ($space eq 'resource') {
1.651 albertel 9811: if ( (defined($Apache::lonhomework::parsing_a_problem)
9812: || defined($Apache::lonhomework::parsing_a_task))
9813: &&
1.744 albertel 9814: ($symbparm eq &symbread()) ) {
9815: # if we are in the middle of processing the resource the
9816: # get the value we are planning on committing
9817: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9818: return $Apache::lonhomework::results{$qualifierrest};
9819: } else {
9820: return $Apache::lonhomework::history{$qualifierrest};
9821: }
1.335 albertel 9822: } else {
1.359 albertel 9823: my %restored;
1.620 albertel 9824: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9825: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9826: } else {
9827: %restored=&restore($symbparm,$courseid,$udom,$uname);
9828: }
1.335 albertel 9829: return $restored{$qualifierrest};
9830: }
1.48 www 9831: # ----------------------------------------------------------------- user.access
9832: } elsif ($space eq 'access') {
1.218 albertel 9833: # FIXME - not supporting calls for a specific user
1.48 www 9834: return &allowed($qualifier,$rest);
9835: # ------------------------------------------ user.preferences, user.environment
9836: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9837: if (($uname eq $env{'user.name'}) &&
9838: ($udom eq $env{'user.domain'})) {
9839: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9840: } else {
1.359 albertel 9841: my %returnhash;
9842: if (!$publicuser) {
9843: %returnhash=&userenvironment($udom,$uname,
9844: $qualifierrest);
9845: }
1.218 albertel 9846: return $returnhash{$qualifierrest};
9847: }
1.48 www 9848: # ----------------------------------------------------------------- user.course
9849: } elsif ($space eq 'course') {
1.218 albertel 9850: # FIXME - not supporting calls for a specific user
1.620 albertel 9851: return $env{join('.',('request.course',$qualifier))};
1.48 www 9852: # ------------------------------------------------------------------- user.role
9853: } elsif ($space eq 'role') {
1.218 albertel 9854: # FIXME - not supporting calls for a specific user
1.620 albertel 9855: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9856: if ($qualifier eq 'value') {
9857: return $role;
9858: } elsif ($qualifier eq 'extent') {
9859: return $where;
9860: }
9861: # ----------------------------------------------------------------- user.domain
9862: } elsif ($space eq 'domain') {
1.218 albertel 9863: return $udom;
1.48 www 9864: # ------------------------------------------------------------------- user.name
9865: } elsif ($space eq 'name') {
1.218 albertel 9866: return $uname;
1.48 www 9867: # ---------------------------------------------------- Any other user namespace
1.29 www 9868: } else {
1.359 albertel 9869: my %reply;
9870: if (!$publicuser) {
9871: %reply=&get($space,[$qualifierrest],$udom,$uname);
9872: }
9873: return $reply{$qualifierrest};
1.48 www 9874: }
1.236 www 9875: } elsif ($realm eq 'query') {
9876: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9877: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9878: [$spacequalifierrest]);
1.620 albertel 9879: return $env{'form.'.$spacequalifierrest};
1.236 www 9880: } elsif ($realm eq 'request') {
1.48 www 9881: # ------------------------------------------------------------- request.browser
9882: if ($space eq 'browser') {
1.1145 bisitz 9883: return $env{'browser.'.$qualifier};
1.57 www 9884: # ------------------------------------------------------------ request.filename
9885: } else {
1.620 albertel 9886: return $env{'request.'.$spacequalifierrest};
1.29 www 9887: }
1.28 www 9888: } elsif ($realm eq 'course') {
1.48 www 9889: # ---------------------------------------------------------- course.description
1.620 albertel 9890: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9891: } elsif ($realm eq 'resource') {
1.165 www 9892:
1.620 albertel 9893: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9894: if (!$symbparm) { $symbparm=&symbread(); }
9895: }
1.693 albertel 9896:
1.1172.2.30 raeburn 9897: if ($qualifier eq '') {
9898: if ($space eq 'title') {
9899: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9900: return &gettitle($symbparm);
9901: }
1.693 albertel 9902:
1.1172.2.30 raeburn 9903: if ($space eq 'map') {
9904: my ($map) = &decode_symb($symbparm);
9905: return &symbread($map);
9906: }
9907: if ($space eq 'maptitle') {
9908: my ($map) = &decode_symb($symbparm);
9909: return &gettitle($map);
9910: }
9911: if ($space eq 'filename') {
9912: if ($symbparm) {
9913: return &clutter((&decode_symb($symbparm))[2]);
9914: }
9915: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9916: }
1.1172.2.30 raeburn 9917:
9918: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9919: if ($space eq 'visibleparts') {
9920: my $navmap = Apache::lonnavmaps::navmap->new();
9921: my $item;
9922: if (ref($navmap)) {
9923: my $res = $navmap->getBySymb($symbparm);
9924: my $parts = $res->parts();
9925: if (ref($parts) eq 'ARRAY') {
9926: $item = join(',',@{$parts});
9927: }
9928: undef($navmap);
9929: }
9930: return $item;
9931: }
9932: }
9933: }
1.693 albertel 9934:
9935: my ($section, $group, @groups);
1.593 albertel 9936: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 9937: if (($courseid eq '') && ($cid)) {
9938: $courseid = $cid;
9939: }
9940: if (($symbparm && $courseid) &&
9941: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9942:
1.218 albertel 9943: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9944:
1.60 www 9945: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9946: my $symbp=$symbparm;
1.735 albertel 9947: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9948:
9949: my $symbparm=$symbp.'.'.$spacequalifierrest;
9950: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9951:
1.620 albertel 9952: if (($env{'user.name'} eq $uname) &&
9953: ($env{'user.domain'} eq $udom)) {
9954: $section=$env{'request.course.sec'};
1.733 raeburn 9955: @groups = split(/:/,$env{'request.course.groups'});
9956: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9957: } else {
1.539 albertel 9958: if (! defined($usection)) {
1.551 albertel 9959: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9960: } else {
9961: $section = $usection;
9962: }
1.733 raeburn 9963: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9964: }
9965:
9966: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9967: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9968: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9969:
1.593 albertel 9970: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9971: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9972: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9973:
1.60 www 9974: # ----------------------------------------------------------- first, check user
1.624 albertel 9975:
9976: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9977: ([$courselevelr,'resource'],
9978: [$courselevelm,'map' ],
9979: [$courselevel, 'course' ]));
1.931 albertel 9980: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9981:
1.594 albertel 9982: # ------------------------------------------------ second, check some of course
1.684 raeburn 9983: my $coursereply;
1.691 raeburn 9984: if (@groups > 0) {
9985: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9986: $mapparm,$spacequalifierrest);
1.927 albertel 9987: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9988: }
1.96 www 9989:
1.684 raeburn 9990: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9991: $env{'course.'.$courseid.'.domain'},
9992: 'course',
9993: ([$seclevelr, 'resource'],
9994: [$seclevelm, 'map' ],
9995: [$seclevel, 'course' ],
9996: [$courselevelr,'resource']));
9997: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9998:
1.60 www 9999: # ------------------------------------------------------ third, check map parms
1.218 albertel 10000: my %parmhash=();
10001: my $thisparm='';
10002: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10003: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10004: &GDBM_READER(),0640)) {
1.218 albertel 10005: $thisparm=$parmhash{$symbparm};
10006: untie(%parmhash);
10007: }
1.927 albertel 10008: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10009: }
1.594 albertel 10010: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10011:
1.218 albertel 10012: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10013: my $filename;
10014: if (!$symbparm) { $symbparm=&symbread(); }
10015: if ($symbparm) {
1.409 www 10016: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10017: } else {
1.620 albertel 10018: $filename=$env{'request.filename'};
1.282 albertel 10019: }
10020: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10021: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10022: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10023: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10024:
1.927 albertel 10025: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10026: if ($symbparm && defined($courseid) &&
1.620 albertel 10027: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10028: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10029: $env{'course.'.$courseid.'.domain'},
10030: 'course',
1.927 albertel 10031: ([$courselevelm,'map' ],
10032: [$courselevel, 'course']));
10033: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10034: }
1.145 www 10035: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10036: unless ($space eq '0') {
1.336 albertel 10037: my @parts=split(/_/,$space);
10038: my $id=pop(@parts);
10039: my $part=join('_',@parts);
10040: if ($part eq '') { $part='0'; }
1.927 albertel 10041: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10042: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10043: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10044: }
1.395 albertel 10045: if ($recurse) { return undef; }
10046: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10047: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10048: # ---------------------------------------------------- Any other user namespace
10049: } elsif ($realm eq 'environment') {
10050: # ----------------------------------------------------------------- environment
1.620 albertel 10051: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10052: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10053: } else {
1.770 albertel 10054: if ($uname eq 'anonymous' && $udom eq '') {
10055: return '';
10056: }
1.219 albertel 10057: my %returnhash=&userenvironment($udom,$uname,
10058: $spacequalifierrest);
10059: return $returnhash{$spacequalifierrest};
10060: }
1.28 www 10061: } elsif ($realm eq 'system') {
1.48 www 10062: # ----------------------------------------------------------------- system.time
10063: if ($space eq 'time') {
10064: return time;
10065: }
1.696 albertel 10066: } elsif ($realm eq 'server') {
10067: # ----------------------------------------------------------------- system.time
10068: if ($space eq 'name') {
10069: return $ENV{'SERVER_NAME'};
10070: }
1.28 www 10071: }
1.48 www 10072: return '';
1.61 www 10073: }
10074:
1.927 albertel 10075: sub get_reply {
10076: my ($reply_value) = @_;
1.940 raeburn 10077: if (ref($reply_value) eq 'ARRAY') {
10078: if (wantarray) {
10079: return @$reply_value;
10080: }
10081: return $reply_value->[0];
10082: } else {
10083: return $reply_value;
1.927 albertel 10084: }
10085: }
10086:
1.691 raeburn 10087: sub check_group_parms {
10088: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10089: my @groupitems = ();
10090: my $resultitem;
1.927 albertel 10091: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10092: foreach my $group (@{$groups}) {
10093: foreach my $level (@levels) {
1.927 albertel 10094: my $item = $courseid.'.['.$group.'].'.$level->[0];
10095: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10096: }
10097: }
10098: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10099: $env{'course.'.$courseid.'.domain'},
10100: 'course',@groupitems);
10101: return $coursereply;
10102: }
10103:
10104: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10105: my ($courseid,@groups) = @_;
10106: @groups = sort(@groups);
1.691 raeburn 10107: return @groups;
10108: }
10109:
1.395 albertel 10110: sub packages_tab_default {
10111: my ($uri,$varname)=@_;
10112: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10113:
10114: my (@extension,@specifics,$do_default);
10115: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10116: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10117: if ($pack_type eq 'default') {
10118: $do_default=1;
10119: } elsif ($pack_type eq 'extension') {
10120: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10121: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10122: # only look at packages defaults for packages that this id is
1.738 albertel 10123: push(@specifics,[$package,$pack_type,$pack_part]);
10124: }
10125: }
10126: # first look for a package that matches the requested part id
10127: foreach my $package (@specifics) {
10128: my (undef,$pack_type,$pack_part)=@{$package};
10129: next if ($pack_part ne $part);
10130: if (defined($packagetab{"$pack_type&$name&default"})) {
10131: return $packagetab{"$pack_type&$name&default"};
10132: }
10133: }
10134: # look for any possible matching non extension_ package
10135: foreach my $package (@specifics) {
10136: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10137: if (defined($packagetab{"$pack_type&$name&default"})) {
10138: return $packagetab{"$pack_type&$name&default"};
10139: }
1.585 albertel 10140: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10141: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10142: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10143: }
10144: }
1.738 albertel 10145: # look for any posible extension_ match
10146: foreach my $package (@extension) {
10147: my ($package,$pack_type)=@{$package};
10148: if (defined($packagetab{"$pack_type&$name&default"})) {
10149: return $packagetab{"$pack_type&$name&default"};
10150: }
10151: if (defined($packagetab{$package."&$name&default"})) {
10152: return $packagetab{$package."&$name&default"};
10153: }
10154: }
10155: # look for a global default setting
10156: if ($do_default && defined($packagetab{"default&$name&default"})) {
10157: return $packagetab{"default&$name&default"};
10158: }
1.395 albertel 10159: return undef;
10160: }
10161:
1.334 albertel 10162: sub add_prefix_and_part {
10163: my ($prefix,$part)=@_;
10164: my $keyroot;
10165: if (defined($prefix) && $prefix !~ /^__/) {
10166: # prefix that has a part already
10167: $keyroot=$prefix;
10168: } elsif (defined($prefix)) {
10169: # prefix that is missing a part
10170: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10171: } else {
10172: # no prefix at all
10173: if (defined($part)) { $keyroot='_'.$part; }
10174: }
10175: return $keyroot;
10176: }
10177:
1.71 www 10178: # ---------------------------------------------------------------- Get metadata
10179:
1.599 albertel 10180: my %metaentry;
1.1070 www 10181: my %importedpartids;
1.71 www 10182: sub metadata {
1.176 www 10183: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10184: $uri=&declutter($uri);
1.288 albertel 10185: # if it is a non metadata possible uri return quickly
1.529 albertel 10186: if (($uri eq '') ||
10187: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10188: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10189: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10190: return undef;
10191: }
1.1140 www 10192: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10193: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10194: return undef;
1.288 albertel 10195: }
1.73 www 10196: my $filename=$uri;
10197: $uri=~s/\.meta$//;
1.172 www 10198: #
10199: # Is the metadata already cached?
1.177 www 10200: # Look at timestamp of caching
1.172 www 10201: # Everything is cached by the main uri, libraries are never directly cached
10202: #
1.428 albertel 10203: if (!defined($liburi)) {
1.599 albertel 10204: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10205: if (defined($cached)) { return $result->{':'.$what}; }
10206: }
10207: {
1.1069 www 10208: # Imported parts would go here
1.1070 www 10209: my %importedids=();
10210: my @origfileimportpartids=();
1.1069 www 10211: my $importedparts=0;
1.172 www 10212: #
10213: # Is this a recursive call for a library?
10214: #
1.599 albertel 10215: # if (! exists($metacache{$uri})) {
10216: # $metacache{$uri}={};
10217: # }
1.924 albertel 10218: my $cachetime = 60*60;
1.171 www 10219: if ($liburi) {
10220: $liburi=&declutter($liburi);
10221: $filename=$liburi;
1.401 bowersj2 10222: } else {
1.599 albertel 10223: &devalidate_cache_new('meta',$uri);
10224: undef(%metaentry);
1.401 bowersj2 10225: }
1.140 www 10226: my %metathesekeys=();
1.73 www 10227: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10228: my $metastring;
1.1140 www 10229: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10230: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10231: $metastring =
1.929 albertel 10232: &Apache::lonnet::ssi_body($which,
1.924 albertel 10233: ('grade_target' => 'meta'));
10234: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10235: } elsif (($uri !~ m -^(editupload)/-) &&
10236: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10237: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10238: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10239: $metastring=&getfile($file);
1.489 albertel 10240: }
1.208 albertel 10241: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10242: my $token;
1.140 www 10243: undef %metathesekeys;
1.71 www 10244: while ($token=$parser->get_token) {
1.339 albertel 10245: if ($token->[0] eq 'S') {
10246: if (defined($token->[2]->{'package'})) {
1.172 www 10247: #
10248: # This is a package - get package info
10249: #
1.339 albertel 10250: my $package=$token->[2]->{'package'};
10251: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10252: if (defined($token->[2]->{'id'})) {
10253: $keyroot.='_'.$token->[2]->{'id'};
10254: }
1.599 albertel 10255: if ($metaentry{':packages'}) {
10256: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10257: } else {
1.599 albertel 10258: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10259: }
1.736 albertel 10260: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10261: my $part=$keyroot;
10262: $part=~s/^\_//;
1.736 albertel 10263: if ($pack_entry=~/^\Q$package\E\&/ ||
10264: $pack_entry=~/^\Q$package\E_0\&/) {
10265: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10266: # ignore package.tab specified default values
10267: # here &package_tab_default() will fetch those
10268: if ($subp eq 'default') { next; }
1.736 albertel 10269: my $value=$packagetab{$pack_entry};
1.432 albertel 10270: my $unikey;
10271: if ($pack =~ /_0$/) {
10272: $unikey='parameter_0_'.$name;
10273: $part=0;
10274: } else {
10275: $unikey='parameter'.$keyroot.'_'.$name;
10276: }
1.339 albertel 10277: if ($subp eq 'display') {
10278: $value.=' [Part: '.$part.']';
10279: }
1.599 albertel 10280: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10281: $metathesekeys{$unikey}=1;
1.599 albertel 10282: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10283: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10284: }
1.599 albertel 10285: if (defined($metaentry{':'.$unikey.'.default'})) {
10286: $metaentry{':'.$unikey}=
10287: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10288: }
1.339 albertel 10289: }
10290: }
10291: } else {
1.172 www 10292: #
10293: # This is not a package - some other kind of start tag
1.339 albertel 10294: #
10295: my $entry=$token->[1];
1.1068 www 10296: my $unikey='';
1.175 www 10297:
1.339 albertel 10298: if ($entry eq 'import') {
1.175 www 10299: #
10300: # Importing a library here
1.339 albertel 10301: #
1.1067 www 10302: my $location=$parser->get_text('/import');
10303: my $dir=$filename;
10304: $dir=~s|[^/]*$||;
10305: $location=&filelocation($dir,$location);
1.1069 www 10306:
1.1068 www 10307: my $importmode=$token->[2]->{'importmode'};
10308: if ($importmode eq 'problem') {
1.1069 www 10309: # Import as problem/response
1.1068 www 10310: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10311: } elsif ($importmode eq 'part') {
10312: # Import as part(s)
1.1069 www 10313: $importedparts=1;
10314: # We need to get the original file and the imported file to get the part order correct
10315: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10316: # Load and inspect original file
1.1070 www 10317: if ($#origfileimportpartids<0) {
10318: undef(%importedpartids);
10319: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10320: my $origfile=&getfile($origfilelocation);
10321: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10322: }
10323:
1.1069 www 10324: # Load and inspect imported file
10325: my $impfile=&getfile($location);
10326: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10327: if ($#impfilepartids>=0) {
10328: # This problem had parts
1.1070 www 10329: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10330: } else {
10331: # Importing by turning a single problem into a problem part
10332: # It gets the import-tags ID as part-ID
10333: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10334: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10335: }
1.1068 www 10336: } else {
10337: # Normal import
10338: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10339: if (defined($token->[2]->{'id'})) {
10340: $unikey.='_'.$token->[2]->{'id'};
10341: }
1.1067 www 10342: }
10343:
1.339 albertel 10344: if ($depthcount<20) {
1.736 albertel 10345: my $metadata =
10346: &metadata($uri,'keys', $location,$unikey,
10347: $depthcount+1);
10348: foreach my $meta (split(',',$metadata)) {
10349: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10350: $metathesekeys{$meta}=1;
1.339 albertel 10351: }
1.1068 www 10352:
10353: }
1.1067 www 10354: } else {
10355: #
10356: # Not importing, some other kind of non-package, non-library start tag
10357: #
10358: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10359: if (defined($token->[2]->{'id'})) {
10360: $unikey.='_'.$token->[2]->{'id'};
10361: }
1.339 albertel 10362: if (defined($token->[2]->{'name'})) {
10363: $unikey.='_'.$token->[2]->{'name'};
10364: }
10365: $metathesekeys{$unikey}=1;
1.736 albertel 10366: foreach my $param (@{$token->[3]}) {
10367: $metaentry{':'.$unikey.'.'.$param} =
10368: $token->[2]->{$param};
1.339 albertel 10369: }
10370: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10371: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10372: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10373: # only ws inside the tag, and not in default, so use default
10374: # as value
1.599 albertel 10375: $metaentry{':'.$unikey}=$default;
1.908 albertel 10376: } elsif ( $internaltext =~ /\S/ ) {
10377: # something interesting inside the tag
10378: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10379: } else {
1.908 albertel 10380: # no interesting values, don't set a default
1.339 albertel 10381: }
1.172 www 10382: # end of not-a-package not-a-library import
1.339 albertel 10383: }
1.172 www 10384: # end of not-a-package start tag
1.339 albertel 10385: }
1.172 www 10386: # the next is the end of "start tag"
1.339 albertel 10387: }
10388: }
1.483 albertel 10389: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10390: $extension = lc($extension);
10391: if ($extension eq 'htm') { $extension='html'; }
10392:
1.737 albertel 10393: foreach my $key (keys(%packagetab)) {
1.483 albertel 10394: #no specific packages #how's our extension
10395: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10396: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10397: \%metathesekeys);
10398: }
1.883 albertel 10399:
10400: if (!exists($metaentry{':packages'})
10401: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10402: foreach my $key (keys(%packagetab)) {
1.483 albertel 10403: #no specific packages well let's get default then
10404: if ($key!~/^default&/) { next; }
1.488 albertel 10405: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10406: \%metathesekeys);
10407: }
10408: }
1.338 www 10409: # are there custom rights to evaluate
1.599 albertel 10410: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10411:
1.338 www 10412: #
10413: # Importing a rights file here
1.339 albertel 10414: #
10415: unless ($depthcount) {
1.599 albertel 10416: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10417: my $dir=$filename;
10418: $dir=~s|[^/]*$||;
10419: $location=&filelocation($dir,$location);
1.736 albertel 10420: my $rights_metadata =
10421: &metadata($uri,'keys',$location,'_rights',
10422: $depthcount+1);
10423: foreach my $rights (split(',',$rights_metadata)) {
10424: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10425: $metathesekeys{$rights}=1;
1.339 albertel 10426: }
10427: }
10428: }
1.737 albertel 10429: # uniqifiy package listing
10430: my %seen;
10431: my @uniq_packages =
10432: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10433: $metaentry{':packages'} = join(',',@uniq_packages);
10434:
1.1070 www 10435: if ($importedparts) {
10436: # We had imported parts and need to rebuild partorder
10437: $metaentry{':partorder'}='';
10438: $metathesekeys{'partorder'}=1;
10439: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10440: if ($origfileimportpartids[$index] eq 'part') {
10441: # original part, part of the problem
10442: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10443: } else {
10444: # we have imported parts at this position
10445: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10446: }
10447: }
10448: $metaentry{':partorder'}=~s/^\,//;
10449: }
10450:
1.737 albertel 10451: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10452: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10453: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10454: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10455: # this is the end of "was not already recently cached
1.71 www 10456: }
1.599 albertel 10457: return $metaentry{':'.$what};
1.261 albertel 10458: }
10459:
1.488 albertel 10460: sub metadata_create_package_def {
1.483 albertel 10461: my ($uri,$key,$package,$metathesekeys)=@_;
10462: my ($pack,$name,$subp)=split(/\&/,$key);
10463: if ($subp eq 'default') { next; }
10464:
1.599 albertel 10465: if (defined($metaentry{':packages'})) {
10466: $metaentry{':packages'}.=','.$package;
1.483 albertel 10467: } else {
1.599 albertel 10468: $metaentry{':packages'}=$package;
1.483 albertel 10469: }
10470: my $value=$packagetab{$key};
10471: my $unikey;
10472: $unikey='parameter_0_'.$name;
1.599 albertel 10473: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10474: $$metathesekeys{$unikey}=1;
1.599 albertel 10475: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10476: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10477: }
1.599 albertel 10478: if (defined($metaentry{':'.$unikey.'.default'})) {
10479: $metaentry{':'.$unikey}=
10480: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10481: }
10482: }
10483:
1.261 albertel 10484: sub metadata_generate_part0 {
10485: my ($metadata,$metacache,$uri) = @_;
10486: my %allnames;
1.737 albertel 10487: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10488: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10489: my $part=$$metacache{':'.$metakey.'.part'};
10490: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10491: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10492: $allnames{$name}=$part;
10493: }
10494: }
10495: }
10496: foreach my $name (keys(%allnames)) {
10497: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10498: my $key=":parameter_0_$name";
1.261 albertel 10499: $$metacache{"$key.part"}='0';
10500: $$metacache{"$key.name"}=$name;
1.428 albertel 10501: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10502: $allnames{$name}.'_'.$name.
10503: '.type'};
1.428 albertel 10504: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10505: '.display'};
1.644 www 10506: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10507: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10508: $$metacache{"$key.display"}=$olddis;
10509: }
1.71 www 10510: }
10511:
1.764 albertel 10512: # ------------------------------------------------------ Devalidate title cache
10513:
10514: sub devalidate_title_cache {
10515: my ($url)=@_;
10516: if (!$env{'request.course.id'}) { return; }
10517: my $symb=&symbread($url);
10518: if (!$symb) { return; }
10519: my $key=$env{'request.course.id'}."\0".$symb;
10520: &devalidate_cache_new('title',$key);
10521: }
10522:
1.1014 droeschl 10523: # ------------------------------------------------- Get the title of a course
10524:
10525: sub current_course_title {
10526: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10527: }
1.301 www 10528: # ------------------------------------------------- Get the title of a resource
10529:
10530: sub gettitle {
10531: my $urlsymb=shift;
10532: my $symb=&symbread($urlsymb);
1.534 albertel 10533: if ($symb) {
1.620 albertel 10534: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10535: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10536: if (defined($cached)) {
10537: return $result;
10538: }
1.534 albertel 10539: my ($map,$resid,$url)=&decode_symb($symb);
10540: my $title='';
1.907 albertel 10541: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10542: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10543: } else {
10544: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10545: &GDBM_READER(),0640)) {
10546: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10547: $title=$bighash{'title_'.$mapid.'.'.$resid};
10548: untie(%bighash);
10549: }
1.534 albertel 10550: }
10551: $title=~s/\&colon\;/\:/gs;
10552: if ($title) {
1.1159 www 10553: # Remember both $symb and $title for dynamic metadata
10554: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10555: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10556: # Cache this title and then return it
1.599 albertel 10557: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10558: }
10559: $urlsymb=$url;
10560: }
10561: my $title=&metadata($urlsymb,'title');
10562: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10563: return $title;
1.301 www 10564: }
1.613 albertel 10565:
1.614 albertel 10566: sub get_slot {
10567: my ($which,$cnum,$cdom)=@_;
10568: if (!$cnum || !$cdom) {
1.790 albertel 10569: (undef,my $courseid)=&whichuser();
1.620 albertel 10570: $cdom=$env{'course.'.$courseid.'.domain'};
10571: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10572: }
1.703 albertel 10573: my $key=join("\0",'slots',$cdom,$cnum,$which);
10574: my %slotinfo;
10575: if (exists($remembered{$key})) {
10576: $slotinfo{$which} = $remembered{$key};
10577: } else {
10578: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10579: &Apache::lonhomework::showhash(%slotinfo);
10580: my ($tmp)=keys(%slotinfo);
10581: if ($tmp=~/^error:/) { return (); }
10582: $remembered{$key} = $slotinfo{$which};
10583: }
1.616 albertel 10584: if (ref($slotinfo{$which}) eq 'HASH') {
10585: return %{$slotinfo{$which}};
10586: }
10587: return $slotinfo{$which};
1.614 albertel 10588: }
1.1150 raeburn 10589:
10590: sub get_reservable_slots {
10591: my ($cnum,$cdom,$uname,$udom) = @_;
10592: my $now = time;
10593: my $reservable_info;
10594: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10595: if (exists($remembered{$key})) {
10596: $reservable_info = $remembered{$key};
10597: } else {
10598: my %resv;
10599: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10600: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10601: $reservable_info = \%resv;
10602: $remembered{$key} = $reservable_info;
10603: }
10604: return $reservable_info;
10605: }
10606:
10607: sub get_course_slots {
10608: my ($cnum,$cdom) = @_;
10609: my $hashid=$cnum.':'.$cdom;
10610: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10611: if (defined($cached)) {
10612: if (ref($result) eq 'HASH') {
10613: return %{$result};
10614: }
10615: } else {
10616: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10617: my ($tmp) = keys(%slots);
10618: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10619: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10620: return %slots;
10621: }
10622: }
10623: return;
10624: }
10625:
10626: sub devalidate_slots_cache {
10627: my ($cnum,$cdom)=@_;
10628: my $hashid=$cnum.':'.$cdom;
10629: &devalidate_cache_new('allslots',$hashid);
10630: }
10631:
1.1172.2.8 raeburn 10632: sub get_coursechange {
10633: my ($cdom,$cnum) = @_;
10634: if ($cdom eq '' || $cnum eq '') {
10635: return unless ($env{'request.course.id'});
10636: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10637: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10638: }
10639: my $hashid=$cdom.'_'.$cnum;
10640: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10641: if ((defined($cached)) && ($change ne '')) {
10642: return $change;
10643: } else {
10644: my %crshash;
10645: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10646: if ($crshash{'internal.contentchange'} eq '') {
10647: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10648: if ($change eq '') {
10649: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10650: $change = $crshash{'internal.created'};
10651: }
10652: } else {
10653: $change = $crshash{'internal.contentchange'};
10654: }
10655: my $cachetime = 600;
10656: &do_cache_new('crschange',$hashid,$change,$cachetime);
10657: }
10658: return $change;
10659: }
10660:
10661: sub devalidate_coursechange_cache {
10662: my ($cnum,$cdom)=@_;
10663: my $hashid=$cnum.':'.$cdom;
10664: &devalidate_cache_new('crschange',$hashid);
10665: }
10666:
1.31 www 10667: # ------------------------------------------------- Update symbolic store links
10668:
10669: sub symblist {
10670: my ($mapname,%newhash)=@_;
1.438 www 10671: $mapname=&deversion(&declutter($mapname));
1.31 www 10672: my %hash;
1.620 albertel 10673: if (($env{'request.course.fn'}) && (%newhash)) {
10674: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10675: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10676: foreach my $url (keys(%newhash)) {
1.711 albertel 10677: next if ($url eq 'last_known'
10678: && $env{'form.no_update_last_known'});
10679: $hash{declutter($url)}=&encode_symb($mapname,
10680: $newhash{$url}->[1],
10681: $newhash{$url}->[0]);
1.191 harris41 10682: }
1.31 www 10683: if (untie(%hash)) {
10684: return 'ok';
10685: }
10686: }
10687: }
10688: return 'error';
1.212 www 10689: }
10690:
10691: # --------------------------------------------------------------- Verify a symb
10692:
10693: sub symbverify {
1.1172.2.11 raeburn 10694: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10695: my $thisfn=$thisurl;
1.439 www 10696: $thisfn=&declutter($thisfn);
1.215 www 10697: # direct jump to resource in page or to a sequence - will construct own symbs
10698: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10699: # check URL part
1.409 www 10700: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10701:
1.431 www 10702: unless ($url eq $thisfn) { return 0; }
1.213 www 10703:
1.216 www 10704: $symb=&symbclean($symb);
1.510 www 10705: $thisurl=&deversion($thisurl);
1.439 www 10706: $thisfn=&deversion($thisfn);
1.213 www 10707:
10708: my %bighash;
10709: my $okay=0;
1.431 www 10710:
1.620 albertel 10711: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10712: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10713: my $noclutter;
1.1032 raeburn 10714: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10715: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10716: if ($map =~ m{^uploaded/.+\.page$}) {
10717: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10718: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10719: $noclutter = 1;
10720: }
10721: }
10722: my $ids;
10723: if ($noclutter) {
10724: $ids=$bighash{'ids_'.$thisurl};
10725: } else {
10726: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10727: }
1.1102 raeburn 10728: unless ($ids) {
1.1172.2.13 raeburn 10729: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10730: $ids=$bighash{$idkey};
1.216 www 10731: }
10732: if ($ids) {
10733: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10734: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10735: $symb =~ s/\?.+$//;
10736: }
1.800 albertel 10737: foreach my $id (split(/\,/,$ids)) {
10738: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10739: if (
10740: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10741: eq $symb) {
1.1172.2.11 raeburn 10742: if (ref($encstate)) {
10743: $$encstate = $bighash{'encrypted_'.$id};
10744: }
1.1172.2.13 raeburn 10745: if (($env{'request.role.adv'}) ||
10746: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10747: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10748: $okay=1;
10749: last;
10750: }
10751: }
10752: }
1.216 www 10753: }
1.213 www 10754: untie(%bighash);
10755: }
10756: return $okay;
1.31 www 10757: }
10758:
1.210 www 10759: # --------------------------------------------------------------- Clean-up symb
10760:
10761: sub symbclean {
10762: my $symb=shift;
1.568 albertel 10763: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10764: # remove version from map
10765: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10766:
1.210 www 10767: # remove version from URL
10768: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10769:
1.507 www 10770: # remove wrapper
10771:
1.510 www 10772: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10773: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10774: return $symb;
1.409 www 10775: }
10776:
10777: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10778:
10779: sub encode_symb {
10780: my ($map,$resid,$url)=@_;
10781: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10782: }
1.409 www 10783:
10784: sub decode_symb {
1.568 albertel 10785: my $symb=shift;
10786: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10787: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10788: return (&fixversion($map),$resid,&fixversion($url));
10789: }
10790:
10791: sub fixversion {
10792: my $fn=shift;
1.609 banghart 10793: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10794: my %bighash;
10795: my $uri=&clutter($fn);
1.620 albertel 10796: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10797: # is this cached?
1.599 albertel 10798: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10799: if (defined($cached)) { return $result; }
10800: # unfortunately not cached, or expired
1.620 albertel 10801: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10802: &GDBM_READER(),0640)) {
10803: if ($bighash{'version_'.$uri}) {
10804: my $version=$bighash{'version_'.$uri};
1.444 www 10805: unless (($version eq 'mostrecent') ||
10806: ($version==&getversion($uri))) {
1.440 www 10807: $uri=~s/\.(\w+)$/\.$version\.$1/;
10808: }
10809: }
10810: untie %bighash;
1.413 www 10811: }
1.599 albertel 10812: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10813: }
10814:
10815: sub deversion {
10816: my $url=shift;
10817: $url=~s/\.\d+\.(\w+)$/\.$1/;
10818: return $url;
1.210 www 10819: }
10820:
1.31 www 10821: # ------------------------------------------------------ Return symb list entry
10822:
10823: sub symbread {
1.249 www 10824: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10825: my $cache_str;
10826: if ($thisfn ne '') {
10827: $cache_str='request.symbread.cached.'.$thisfn;
10828: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10829: return $env{$cache_str};
10830: }
1.1172.2.13 raeburn 10831: } else {
1.242 www 10832: # no filename provided? try from environment
1.620 albertel 10833: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10834: return $env{$cache_str}=&symbclean($env{'request.symb'});
10835: }
10836: $thisfn=$env{'request.filename'};
1.44 www 10837: }
1.569 albertel 10838: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10839: # is that filename actually a symb? Verify, clean, and return
10840: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10841: if (&symbverify($thisfn,$1)) {
1.620 albertel 10842: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10843: }
1.242 www 10844: }
1.44 www 10845: $thisfn=declutter($thisfn);
1.31 www 10846: my %hash;
1.37 www 10847: my %bighash;
10848: my $syval='';
1.620 albertel 10849: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10850: my $targetfn = $thisfn;
1.609 banghart 10851: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10852: $targetfn = 'adm/wrapper/'.$thisfn;
10853: }
1.687 albertel 10854: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10855: $targetfn=$1;
10856: }
1.620 albertel 10857: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10858: &GDBM_READER(),0640)) {
1.481 raeburn 10859: $syval=$hash{$targetfn};
1.37 www 10860: untie(%hash);
10861: }
10862: # ---------------------------------------------------------- There was an entry
10863: if ($syval) {
1.601 albertel 10864: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10865: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10866: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10867: #return $env{$cache_str}='';
1.601 albertel 10868: #}
10869: #$syval.=$1;
10870: #}
1.37 www 10871: } else {
10872: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10873: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10874: &GDBM_READER(),0640)) {
1.37 www 10875: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10876: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10877: unless ($ids) {
10878: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10879: }
10880: unless ($ids) {
10881: # alias?
10882: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10883: }
1.37 www 10884: if ($ids) {
10885: # ------------------------------------------------------------------- Has ID(s)
10886: my @possibilities=split(/\,/,$ids);
1.39 www 10887: if ($#possibilities==0) {
10888: # ----------------------------------------------- There is only one possibility
1.37 www 10889: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10890: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10891: $resid,$thisfn);
1.249 www 10892: } elsif (!$donotrecurse) {
1.39 www 10893: # ------------------------------------------ There is more than one possibility
10894: my $realpossible=0;
1.800 albertel 10895: foreach my $id (@possibilities) {
10896: my $file=$bighash{'src_'.$id};
1.39 www 10897: if (&allowed('bre',$file)) {
1.800 albertel 10898: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10899: if ($bighash{'map_type_'.$mapid} ne 'page') {
10900: $realpossible++;
1.626 albertel 10901: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10902: $resid,$thisfn);
1.39 www 10903: }
10904: }
1.191 harris41 10905: }
1.39 www 10906: if ($realpossible!=1) { $syval=''; }
1.249 www 10907: } else {
10908: $syval='';
1.37 www 10909: }
10910: }
10911: untie(%bighash)
1.481 raeburn 10912: }
1.31 www 10913: }
1.62 www 10914: if ($syval) {
1.620 albertel 10915: return $env{$cache_str}=$syval;
1.62 www 10916: }
1.31 www 10917: }
1.949 raeburn 10918: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10919: return $env{$cache_str}='';
1.31 www 10920: }
10921:
10922: # ---------------------------------------------------------- Return random seed
10923:
1.32 www 10924: sub numval {
10925: my $txt=shift;
10926: $txt=~tr/A-J/0-9/;
10927: $txt=~tr/a-j/0-9/;
10928: $txt=~tr/K-T/0-9/;
10929: $txt=~tr/k-t/0-9/;
10930: $txt=~tr/U-Z/0-5/;
10931: $txt=~tr/u-z/0-5/;
10932: $txt=~s/\D//g;
1.564 albertel 10933: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10934: return int($txt);
1.368 albertel 10935: }
10936:
1.484 albertel 10937: sub numval2 {
10938: my $txt=shift;
10939: $txt=~tr/A-J/0-9/;
10940: $txt=~tr/a-j/0-9/;
10941: $txt=~tr/K-T/0-9/;
10942: $txt=~tr/k-t/0-9/;
10943: $txt=~tr/U-Z/0-5/;
10944: $txt=~tr/u-z/0-5/;
10945: $txt=~s/\D//g;
10946: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10947: my $total;
10948: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10949: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10950: return int($total);
10951: }
10952:
1.575 albertel 10953: sub numval3 {
10954: use integer;
10955: my $txt=shift;
10956: $txt=~tr/A-J/0-9/;
10957: $txt=~tr/a-j/0-9/;
10958: $txt=~tr/K-T/0-9/;
10959: $txt=~tr/k-t/0-9/;
10960: $txt=~tr/U-Z/0-5/;
10961: $txt=~tr/u-z/0-5/;
10962: $txt=~s/\D//g;
10963: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10964: my $total;
10965: foreach my $val (@txts) { $total+=$val; }
10966: if ($_64bit) { $total=(($total<<32)>>32); }
10967: return $total;
10968: }
10969:
1.675 albertel 10970: sub digest {
10971: my ($data)=@_;
10972: my $digest=&Digest::MD5::md5($data);
10973: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10974: my ($e,$f);
10975: {
10976: use integer;
10977: $e=($a+$b);
10978: $f=($c+$d);
10979: if ($_64bit) {
10980: $e=(($e<<32)>>32);
10981: $f=(($f<<32)>>32);
10982: }
10983: }
10984: if (wantarray) {
10985: return ($e,$f);
10986: } else {
10987: my $g;
10988: {
10989: use integer;
10990: $g=($e+$f);
10991: if ($_64bit) {
10992: $g=(($g<<32)>>32);
10993: }
10994: }
10995: return $g;
10996: }
10997: }
10998:
1.368 albertel 10999: sub latest_rnd_algorithm_id {
1.675 albertel 11000: return '64bit5';
1.366 albertel 11001: }
1.32 www 11002:
1.503 albertel 11003: sub get_rand_alg {
11004: my ($courseid)=@_;
1.790 albertel 11005: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11006: if ($courseid) {
1.620 albertel 11007: return $env{"course.$courseid.rndseed"};
1.503 albertel 11008: }
11009: return &latest_rnd_algorithm_id();
11010: }
11011:
1.562 albertel 11012: sub validCODE {
11013: my ($CODE)=@_;
11014: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11015: return 0;
11016: }
11017:
1.491 albertel 11018: sub getCODE {
1.620 albertel 11019: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11020: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11021: defined($Apache::lonhomework::parsing_a_task) ) &&
11022: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11023: return $Apache::lonhomework::history{'resource.CODE'};
11024: }
11025: return undef;
11026: }
1.1133 foxr 11027: #
11028: # Determines the random seed for a specific context:
11029: #
11030: # parameters:
11031: # symb - in course context the symb for the seed.
11032: # course_id - The course id of the form domain_coursenum.
11033: # domain - Domain for the user.
11034: # course - Course for the user.
11035: # cenv - environment of the course.
11036: #
11037: # NOTE:
11038: # All parameters are picked out of the environment if missing
11039: # or not defined.
11040: # If a symb cannot be determined the current time is used instead.
11041: #
11042: # For a given well defined symb, courside, domain, username,
11043: # and course environment, the seed is reproducible.
11044: #
1.31 www 11045: sub rndseed {
1.1133 foxr 11046: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11047: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11048: if (!defined($symb)) {
1.366 albertel 11049: unless ($symb=$wsymb) { return time; }
11050: }
1.1146 foxr 11051: if (!defined $courseid) {
11052: $courseid=$wcourseid;
11053: }
11054: if (!defined $domain) { $domain=$wdomain; }
11055: if (!defined $username) { $username=$wusername }
1.1133 foxr 11056:
11057: my $which;
11058: if (defined($cenv->{'rndseed'})) {
11059: $which = $cenv->{'rndseed'};
11060: } else {
11061: $which =&get_rand_alg($courseid);
11062: }
1.491 albertel 11063: if (defined(&getCODE())) {
1.675 albertel 11064: if ($which eq '64bit5') {
11065: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11066: } elsif ($which eq '64bit4') {
1.575 albertel 11067: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11068: } else {
11069: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11070: }
1.675 albertel 11071: } elsif ($which eq '64bit5') {
11072: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11073: } elsif ($which eq '64bit4') {
11074: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11075: } elsif ($which eq '64bit3') {
11076: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11077: } elsif ($which eq '64bit2') {
11078: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11079: } elsif ($which eq '64bit') {
11080: return &rndseed_64bit($symb,$courseid,$domain,$username);
11081: }
11082: return &rndseed_32bit($symb,$courseid,$domain,$username);
11083: }
11084:
11085: sub rndseed_32bit {
11086: my ($symb,$courseid,$domain,$username)=@_;
11087: {
11088: use integer;
11089: my $symbchck=unpack("%32C*",$symb) << 27;
11090: my $symbseed=numval($symb) << 22;
11091: my $namechck=unpack("%32C*",$username) << 17;
11092: my $nameseed=numval($username) << 12;
11093: my $domainseed=unpack("%32C*",$domain) << 7;
11094: my $courseseed=unpack("%32C*",$courseid);
11095: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11096: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11097: #&logthis("rndseed :$num:$symb");
1.564 albertel 11098: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11099: return $num;
11100: }
11101: }
11102:
11103: sub rndseed_64bit {
11104: my ($symb,$courseid,$domain,$username)=@_;
11105: {
11106: use integer;
11107: my $symbchck=unpack("%32S*",$symb) << 21;
11108: my $symbseed=numval($symb) << 10;
11109: my $namechck=unpack("%32S*",$username);
11110:
11111: my $nameseed=numval($username) << 21;
11112: my $domainseed=unpack("%32S*",$domain) << 10;
11113: my $courseseed=unpack("%32S*",$courseid);
11114:
11115: my $num1=$symbchck+$symbseed+$namechck;
11116: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11117: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11118: #&logthis("rndseed :$num:$symb");
1.564 albertel 11119: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11120: return "$num1,$num2";
1.155 albertel 11121: }
1.366 albertel 11122: }
11123:
1.443 albertel 11124: sub rndseed_64bit2 {
11125: my ($symb,$courseid,$domain,$username)=@_;
11126: {
11127: use integer;
11128: # strings need to be an even # of cahracters long, it it is odd the
11129: # last characters gets thrown away
11130: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11131: my $symbseed=numval($symb) << 10;
11132: my $namechck=unpack("%32S*",$username.' ');
11133:
11134: my $nameseed=numval($username) << 21;
1.501 albertel 11135: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11136: my $courseseed=unpack("%32S*",$courseid.' ');
11137:
11138: my $num1=$symbchck+$symbseed+$namechck;
11139: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11140: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11141: #&logthis("rndseed :$num:$symb");
1.803 albertel 11142: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11143: return "$num1,$num2";
11144: }
11145: }
11146:
11147: sub rndseed_64bit3 {
11148: my ($symb,$courseid,$domain,$username)=@_;
11149: {
11150: use integer;
11151: # strings need to be an even # of cahracters long, it it is odd the
11152: # last characters gets thrown away
11153: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11154: my $symbseed=numval2($symb) << 10;
11155: my $namechck=unpack("%32S*",$username.' ');
11156:
11157: my $nameseed=numval2($username) << 21;
1.443 albertel 11158: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11159: my $courseseed=unpack("%32S*",$courseid.' ');
11160:
11161: my $num1=$symbchck+$symbseed+$namechck;
11162: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11163: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11164: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11165: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11166:
1.503 albertel 11167: return "$num1:$num2";
1.443 albertel 11168: }
11169: }
11170:
1.575 albertel 11171: sub rndseed_64bit4 {
11172: my ($symb,$courseid,$domain,$username)=@_;
11173: {
11174: use integer;
11175: # strings need to be an even # of cahracters long, it it is odd the
11176: # last characters gets thrown away
11177: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11178: my $symbseed=numval3($symb) << 10;
11179: my $namechck=unpack("%32S*",$username.' ');
11180:
11181: my $nameseed=numval3($username) << 21;
11182: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11183: my $courseseed=unpack("%32S*",$courseid.' ');
11184:
11185: my $num1=$symbchck+$symbseed+$namechck;
11186: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11187: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11188: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11189: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11190:
1.575 albertel 11191: return "$num1:$num2";
11192: }
11193: }
11194:
1.675 albertel 11195: sub rndseed_64bit5 {
11196: my ($symb,$courseid,$domain,$username)=@_;
11197: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11198: return "$num1:$num2";
11199: }
11200:
1.366 albertel 11201: sub rndseed_CODE_64bit {
11202: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11203: {
1.366 albertel 11204: use integer;
1.443 albertel 11205: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11206: my $symbseed=numval2($symb);
1.491 albertel 11207: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11208: my $CODEseed=numval(&getCODE());
1.443 albertel 11209: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11210: my $num1=$symbseed+$CODEchck;
11211: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11212: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11213: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11214: if ($_64bit) { $num1=(($num1<<32)>>32); }
11215: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11216: return "$num1:$num2";
1.366 albertel 11217: }
11218: }
11219:
1.575 albertel 11220: sub rndseed_CODE_64bit4 {
11221: my ($symb,$courseid,$domain,$username)=@_;
11222: {
11223: use integer;
11224: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11225: my $symbseed=numval3($symb);
11226: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11227: my $CODEseed=numval3(&getCODE());
11228: my $courseseed=unpack("%32S*",$courseid.' ');
11229: my $num1=$symbseed+$CODEchck;
11230: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11231: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11232: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11233: if ($_64bit) { $num1=(($num1<<32)>>32); }
11234: if ($_64bit) { $num2=(($num2<<32)>>32); }
11235: return "$num1:$num2";
11236: }
11237: }
11238:
1.675 albertel 11239: sub rndseed_CODE_64bit5 {
11240: my ($symb,$courseid,$domain,$username)=@_;
11241: my $code = &getCODE();
11242: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11243: return "$num1:$num2";
11244: }
11245:
1.366 albertel 11246: sub setup_random_from_rndseed {
11247: my ($rndseed)=@_;
1.503 albertel 11248: if ($rndseed =~/([,:])/) {
11249: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11250: &Math::Random::random_set_seed(abs($num1),abs($num2));
11251: } else {
11252: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11253: }
1.36 albertel 11254: }
11255:
1.474 albertel 11256: sub latest_receipt_algorithm_id {
1.835 albertel 11257: return 'receipt3';
1.474 albertel 11258: }
11259:
1.480 www 11260: sub recunique {
11261: my $fucourseid=shift;
11262: my $unique;
1.835 albertel 11263: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11264: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11265: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11266: } else {
11267: $unique=$perlvar{'lonReceipt'};
11268: }
11269: return unpack("%32C*",$unique);
11270: }
11271:
11272: sub recprefix {
11273: my $fucourseid=shift;
11274: my $prefix;
1.835 albertel 11275: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11276: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11277: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11278: } else {
11279: $prefix=$perlvar{'lonHostID'};
11280: }
11281: return unpack("%32C*",$prefix);
11282: }
11283:
1.76 www 11284: sub ireceipt {
1.474 albertel 11285: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11286:
11287: my $return =&recprefix($fucourseid).'-';
11288:
11289: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11290: $env{'request.state'} eq 'construct') {
11291: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11292: return $return;
11293: }
11294:
1.76 www 11295: my $cuname=unpack("%32C*",$funame);
11296: my $cudom=unpack("%32C*",$fudom);
11297: my $cucourseid=unpack("%32C*",$fucourseid);
11298: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11299: my $cunique=&recunique($fucourseid);
1.474 albertel 11300: my $cpart=unpack("%32S*",$part);
1.835 albertel 11301: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11302:
1.790 albertel 11303: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11304:
11305: $return.= ($cunique%$cuname+
11306: $cunique%$cudom+
11307: $cusymb%$cuname+
11308: $cusymb%$cudom+
11309: $cucourseid%$cuname+
11310: $cucourseid%$cudom+
11311: $cpart%$cuname+
11312: $cpart%$cudom);
11313: } else {
11314: $return.= ($cunique%$cuname+
11315: $cunique%$cudom+
11316: $cusymb%$cuname+
11317: $cusymb%$cudom+
11318: $cucourseid%$cuname+
11319: $cucourseid%$cudom);
11320: }
11321: return $return;
1.76 www 11322: }
11323:
11324: sub receipt {
1.474 albertel 11325: my ($part)=@_;
1.790 albertel 11326: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11327: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11328: }
1.260 ng 11329:
1.790 albertel 11330: sub whichuser {
11331: my ($passedsymb)=@_;
11332: my ($symb,$courseid,$domain,$name,$publicuser);
11333: if (defined($env{'form.grade_symb'})) {
11334: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11335: my $allowed=&allowed('vgr',$tmp_courseid);
11336: if (!$allowed &&
11337: exists($env{'request.course.sec'}) &&
11338: $env{'request.course.sec'} !~ /^\s*$/) {
11339: $allowed=&allowed('vgr',$tmp_courseid.
11340: '/'.$env{'request.course.sec'});
11341: }
11342: if ($allowed) {
11343: ($symb)=&get_env_multiple('form.grade_symb');
11344: $courseid=$tmp_courseid;
11345: ($domain)=&get_env_multiple('form.grade_domain');
11346: ($name)=&get_env_multiple('form.grade_username');
11347: return ($symb,$courseid,$domain,$name,$publicuser);
11348: }
11349: }
11350: if (!$passedsymb) {
11351: $symb=&symbread();
11352: } else {
11353: $symb=$passedsymb;
11354: }
11355: $courseid=$env{'request.course.id'};
11356: $domain=$env{'user.domain'};
11357: $name=$env{'user.name'};
11358: if ($name eq 'public' && $domain eq 'public') {
11359: if (!defined($env{'form.username'})) {
11360: $env{'form.username'}.=time.rand(10000000);
11361: }
11362: $name.=$env{'form.username'};
11363: }
11364: return ($symb,$courseid,$domain,$name,$publicuser);
11365:
11366: }
11367:
1.36 albertel 11368: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11369: # returns either the contents of the file or
11370: # -1 if the file doesn't exist
1.481 raeburn 11371: #
11372: # if the target is a file that was uploaded via DOCS,
11373: # a check will be made to see if a current copy exists on the local server,
11374: # if it does this will be served, otherwise a copy will be retrieved from
11375: # the home server for the course and stored in /home/httpd/html/userfiles on
11376: # the local server.
1.472 albertel 11377:
1.36 albertel 11378: sub getfile {
1.538 albertel 11379: my ($file) = @_;
1.609 banghart 11380: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11381: &repcopy($file);
11382: return &readfile($file);
11383: }
11384:
11385: sub repcopy_userfile {
11386: my ($file)=@_;
1.1142 raeburn 11387: my $londocroot = $perlvar{'lonDocRoot'};
11388: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11389: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11390: my ($cdom,$cnum,$filename) =
1.811 albertel 11391: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11392: my $uri="/uploaded/$cdom/$cnum/$filename";
11393: if (-e "$file") {
1.828 www 11394: # we already have a local copy, check it out
1.538 albertel 11395: my @fileinfo = stat($file);
1.828 www 11396: my $rtncode;
11397: my $info;
1.538 albertel 11398: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11399: if ($lwpresp ne 'ok') {
1.828 www 11400: # there is no such file anymore, even though we had a local copy
1.482 albertel 11401: if ($rtncode eq '404') {
1.538 albertel 11402: unlink($file);
1.482 albertel 11403: }
11404: return -1;
11405: }
11406: if ($info < $fileinfo[9]) {
1.828 www 11407: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11408: return 'ok';
1.828 www 11409: } else {
11410: # the file is outdated, get rid of it
11411: unlink($file);
1.482 albertel 11412: }
1.828 www 11413: }
11414: # one way or the other, at this point, we don't have the file
11415: # construct the correct path for the file
11416: my @parts = ($cdom,$cnum);
11417: if ($filename =~ m|^(.+)/[^/]+$|) {
11418: push @parts, split(/\//,$1);
11419: }
11420: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11421: foreach my $part (@parts) {
11422: $path .= '/'.$part;
11423: if (!-e $path) {
11424: mkdir($path,0770);
1.482 albertel 11425: }
11426: }
1.828 www 11427: # now the path exists for sure
11428: # get a user agent
11429: my $ua=new LWP::UserAgent;
11430: my $transferfile=$file.'.in.transfer';
11431: # FIXME: this should flock
11432: if (-e $transferfile) { return 'ok'; }
11433: my $request;
11434: $uri=~s/^\///;
1.980 raeburn 11435: my $homeserver = &homeserver($cnum,$cdom);
11436: my $protocol = $protocol{$homeserver};
11437: $protocol = 'http' if ($protocol ne 'https');
11438: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11439: my $response=$ua->request($request,$transferfile);
11440: # did it work?
11441: if ($response->is_error()) {
11442: unlink($transferfile);
11443: &logthis("Userfile repcopy failed for $uri");
11444: return -1;
11445: }
11446: # worked, rename the transfer file
11447: rename($transferfile,$file);
1.607 raeburn 11448: return 'ok';
1.481 raeburn 11449: }
11450:
1.517 albertel 11451: sub tokenwrapper {
11452: my $uri=shift;
1.980 raeburn 11453: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11454: $uri=~s|^/||;
1.620 albertel 11455: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11456: my $token=$1;
1.552 albertel 11457: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11458: if ($udom && $uname && $file) {
11459: $file=~s|(\?\.*)*$||;
1.949 raeburn 11460: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11461: my $homeserver = &homeserver($uname,$udom);
11462: my $protocol = $protocol{$homeserver};
11463: $protocol = 'http' if ($protocol ne 'https');
11464: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11465: (($uri=~/\?/)?'&':'?').'token='.$token.
11466: '&tokenissued='.$perlvar{'lonHostID'};
11467: } else {
11468: return '/adm/notfound.html';
11469: }
11470: }
11471:
1.828 www 11472: # call with reqtype HEAD: get last modification time
11473: # call with reqtype GET: get the file contents
11474: # Do not call this with reqtype GET for large files! It loads everything into memory
11475: #
1.481 raeburn 11476: sub getuploaded {
11477: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11478: $uri=~s/^\///;
1.980 raeburn 11479: my $homeserver = &homeserver($cnum,$cdom);
11480: my $protocol = $protocol{$homeserver};
11481: $protocol = 'http' if ($protocol ne 'https');
11482: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11483: my $ua=new LWP::UserAgent;
11484: my $request=new HTTP::Request($reqtype,$uri);
11485: my $response=$ua->request($request);
11486: $$rtncode = $response->code;
1.482 albertel 11487: if (! $response->is_success()) {
11488: return 'failed';
11489: }
11490: if ($reqtype eq 'HEAD') {
1.486 www 11491: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11492: } elsif ($reqtype eq 'GET') {
11493: $$info = $response->content;
1.472 albertel 11494: }
1.482 albertel 11495: return 'ok';
1.36 albertel 11496: }
11497:
1.481 raeburn 11498: sub readfile {
11499: my $file = shift;
11500: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11501: my $fh;
11502: open($fh,"<$file");
11503: my $a='';
1.800 albertel 11504: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11505: return $a;
11506: }
11507:
1.36 albertel 11508: sub filelocation {
1.590 banghart 11509: my ($dir,$file) = @_;
11510: my $location;
11511: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11512:
11513: if ($file =~ m-^/adm/-) {
11514: $file=~s-^/adm/wrapper/-/-;
11515: $file=~s-^/adm/coursedocs/showdoc/-/-;
11516: }
1.882 albertel 11517:
1.1139 www 11518: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11519: $location = $file;
1.609 banghart 11520: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11521: my ($udom,$uname,$filename)=
1.811 albertel 11522: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11523: my $home=&homeserver($uname,$udom);
11524: my $is_me=0;
11525: my @ids=¤t_machine_ids();
11526: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11527: if ($is_me) {
1.1117 foxr 11528: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11529: } else {
11530: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11531: $udom.'/'.$uname.'/'.$filename;
11532: }
1.882 albertel 11533: } elsif ($file =~ m-^/adm/-) {
11534: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11535: } else {
11536: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11537: $file=~s:^/(res|priv)/:/:;
11538: my $space=$1;
1.590 banghart 11539: if ( !( $file =~ m:^/:) ) {
11540: $location = $dir. '/'.$file;
11541: } else {
1.1142 raeburn 11542: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11543: }
1.59 albertel 11544: }
1.590 banghart 11545: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11546: while ($location=~m{/\.\./}) {
11547: if ($location =~ m{/[^/]+/\.\./}) {
11548: $location=~ s{/[^/]+/\.\./}{/}g;
11549: } else {
11550: $location=~ s{/\.\./}{/}g;
11551: }
11552: } #remove dir/..
1.590 banghart 11553: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11554: return $location;
1.46 www 11555: }
1.36 albertel 11556:
1.46 www 11557: sub hreflocation {
11558: my ($dir,$file)=@_;
1.980 raeburn 11559: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11560: $file=filelocation($dir,$file);
1.700 albertel 11561: } elsif ($file=~m-^/adm/-) {
11562: $file=~s-^/adm/wrapper/-/-;
11563: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11564: }
11565: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11566: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11567: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11568: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11569: {/uploaded/$1/$2/}x;
1.46 www 11570: }
1.913 albertel 11571: if ($file=~ m{^/userfiles/}) {
11572: $file =~ s{^/userfiles/}{/uploaded/};
11573: }
1.462 albertel 11574: return $file;
1.465 albertel 11575: }
11576:
1.1139 www 11577:
11578:
11579:
11580:
1.465 albertel 11581: sub current_machine_domains {
1.853 albertel 11582: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11583: }
11584:
11585: sub machine_domains {
11586: my ($hostname) = @_;
1.465 albertel 11587: my @domains;
1.838 albertel 11588: my %hostname = &all_hostnames();
1.465 albertel 11589: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11590: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11591: if ($hostname eq $name) {
1.844 albertel 11592: push(@domains,&host_domain($id));
1.465 albertel 11593: }
11594: }
11595: return @domains;
11596: }
11597:
11598: sub current_machine_ids {
1.853 albertel 11599: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11600: }
11601:
11602: sub machine_ids {
11603: my ($hostname) = @_;
11604: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11605: my @ids;
1.888 albertel 11606: my %name_to_host = &all_names();
1.889 albertel 11607: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11608: return @{ $name_to_host{$hostname} };
11609: }
11610: return;
1.31 www 11611: }
11612:
1.824 raeburn 11613: sub additional_machine_domains {
11614: my @domains;
11615: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11616: while( my $line = <$fh>) {
11617: $line =~ s/\s//g;
11618: push(@domains,$line);
11619: }
11620: return @domains;
11621: }
11622:
11623: sub default_login_domain {
11624: my $domain = $perlvar{'lonDefDomain'};
11625: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11626: foreach my $posdom (¤t_machine_domains(),
11627: &additional_machine_domains()) {
11628: if (lc($posdom) eq lc($testdomain)) {
11629: $domain=$posdom;
11630: last;
11631: }
11632: }
11633: return $domain;
11634: }
11635:
1.31 www 11636: # ------------------------------------------------------------- Declutters URLs
11637:
11638: sub declutter {
11639: my $thisfn=shift;
1.569 albertel 11640: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11641: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11642: $thisfn=~s/^\///;
1.697 albertel 11643: $thisfn=~s|^adm/wrapper/||;
11644: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11645: $thisfn=~s/^res\///;
1.1172 bisitz 11646: $thisfn=~s/^priv\///;
1.1032 raeburn 11647: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11648: $thisfn=~s/\?.+$//;
11649: }
1.268 www 11650: return $thisfn;
11651: }
11652:
11653: # ------------------------------------------------------------- Clutter up URLs
11654:
11655: sub clutter {
11656: my $thisfn='/'.&declutter(shift);
1.887 albertel 11657: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11658: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11659: $thisfn='/res'.$thisfn;
11660: }
1.1031 raeburn 11661: if ($thisfn !~m|^/adm|) {
11662: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11663: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11664: } else {
11665: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11666: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11667: if ($embstyle eq 'ssi'
11668: || ($embstyle eq 'hdn')
11669: || ($embstyle eq 'rat')
11670: || ($embstyle eq 'prv')
11671: || ($embstyle eq 'ign')) {
11672: #do nothing with these
11673: } elsif (($embstyle eq 'img')
1.695 albertel 11674: || ($embstyle eq 'emb')
11675: || ($embstyle eq 'wrp')) {
11676: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11677: } elsif ($embstyle eq 'unk'
11678: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11679: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11680: } else {
1.718 www 11681: # &logthis("Got a blank emb style");
1.695 albertel 11682: }
1.694 albertel 11683: }
11684: }
1.31 www 11685: return $thisfn;
1.12 www 11686: }
11687:
1.787 albertel 11688: sub clutter_with_no_wrapper {
11689: my $uri = &clutter(shift);
11690: if ($uri =~ m-^/adm/-) {
11691: $uri =~ s-^/adm/wrapper/-/-;
11692: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11693: }
11694: return $uri;
11695: }
11696:
1.557 albertel 11697: sub freeze_escape {
11698: my ($value)=@_;
11699: if (ref($value)) {
11700: $value=&nfreeze($value);
11701: return '__FROZEN__'.&escape($value);
11702: }
11703: return &escape($value);
11704: }
11705:
1.11 www 11706:
1.557 albertel 11707: sub thaw_unescape {
11708: my ($value)=@_;
11709: if ($value =~ /^__FROZEN__/) {
11710: substr($value,0,10,undef);
11711: $value=&unescape($value);
11712: return &thaw($value);
11713: }
11714: return &unescape($value);
11715: }
11716:
1.436 albertel 11717: sub correct_line_ends {
11718: my ($result)=@_;
11719: $$result =~s/\r\n/\n/mg;
11720: $$result =~s/\r/\n/mg;
1.415 albertel 11721: }
1.1 albertel 11722: # ================================================================ Main Program
11723:
1.184 www 11724: sub goodbye {
1.204 albertel 11725: &logthis("Starting Shut down");
1.443 albertel 11726: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11727: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11728: #converted
1.599 albertel 11729: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11730: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11731: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11732: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11733: #1.1 only
1.870 albertel 11734: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11735: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11736: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11737: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11738: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11739: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11740: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11741: &flushcourselogs();
11742: &logthis("Shutting down");
11743: }
11744:
1.852 albertel 11745: sub get_dns {
1.1172.2.17 raeburn 11746: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11747: if (!$ignore_cache) {
11748: my ($content,$cached)=
11749: &Apache::lonnet::is_cached_new('dns',$url);
11750: if ($cached) {
1.1172.2.17 raeburn 11751: &$func($content,$hashref);
1.869 albertel 11752: return;
11753: }
11754: }
11755:
11756: my %alldns;
1.852 albertel 11757: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11758: foreach my $dns (<$config>) {
11759: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11760: my $line = $1;
11761: my ($host,$protocol) = split(/:/,$line);
11762: if ($protocol ne 'https') {
11763: $protocol = 'http';
11764: }
11765: $alldns{$host} = $protocol;
1.869 albertel 11766: }
11767: while (%alldns) {
11768: my ($dns) = keys(%alldns);
1.852 albertel 11769: my $ua=new LWP::UserAgent;
1.1134 raeburn 11770: $ua->timeout(30);
1.979 raeburn 11771: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11772: my $response=$ua->request($request);
1.979 raeburn 11773: delete($alldns{$dns});
1.852 albertel 11774: next if ($response->is_error());
11775: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11776: unless ($nocache) {
1.1172.2.23 raeburn 11777: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11778: }
11779: &$func(\@content,$hashref);
1.869 albertel 11780: return;
1.852 albertel 11781: }
11782: close($config);
1.871 albertel 11783: my $which = (split('/',$url))[3];
11784: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11785: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11786: my @content = <$config>;
1.1172.2.17 raeburn 11787: &$func(\@content,$hashref);
11788: return;
11789: }
11790:
11791: # ------------------------------------------------------Get DNS checksums file
11792: sub parse_dns_checksums_tab {
11793: my ($lines,$hashref) = @_;
11794: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11795: my $loncaparev = &get_server_loncaparev($machine_dom);
11796: my ($release,$timestamp) = split(/\-/,$loncaparev);
11797: my (%chksum,%revnum);
11798: if (ref($lines) eq 'ARRAY') {
11799: chomp(@{$lines});
1.1172.2.34 raeburn 11800: my $version = shift(@{$lines});
11801: if ($version eq $release) {
1.1172.2.17 raeburn 11802: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11803: my ($file,$version,$shasum) = split(/,/,$line);
11804: $chksum{$file} = $shasum;
11805: $revnum{$file} = $version;
1.1172.2.17 raeburn 11806: }
11807: if (ref($hashref) eq 'HASH') {
11808: %{$hashref} = (
11809: sums => \%chksum,
11810: versions => \%revnum,
11811: );
11812: }
11813: }
11814: }
1.869 albertel 11815: return;
1.852 albertel 11816: }
1.1172.2.17 raeburn 11817:
11818: sub fetch_dns_checksums {
11819: my %checksums;
1.1172.2.34 raeburn 11820: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11821: my $loncaparev = &get_server_loncaparev($machine_dom);
11822: my ($release,$timestamp) = split(/\-/,$loncaparev);
11823: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11824: \%checksums);
11825: return \%checksums;
11826: }
11827:
1.327 albertel 11828: # ------------------------------------------------------------ Read domain file
11829: {
1.852 albertel 11830: my $loaded;
1.846 albertel 11831: my %domain;
11832:
1.852 albertel 11833: sub parse_domain_tab {
11834: my ($lines) = @_;
11835: foreach my $line (@$lines) {
11836: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11837:
1.846 albertel 11838: chomp($line);
1.852 albertel 11839: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11840: my %this_domain;
11841: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11842: 'lang_def', 'city', 'longi', 'lati',
11843: 'primary') {
11844: $this_domain{$field} = shift(@elements);
11845: }
11846: $domain{$name} = \%this_domain;
1.852 albertel 11847: }
11848: }
1.864 albertel 11849:
11850: sub reset_domain_info {
11851: undef($loaded);
11852: undef(%domain);
11853: }
11854:
1.852 albertel 11855: sub load_domain_tab {
1.869 albertel 11856: my ($ignore_cache) = @_;
11857: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11858: my $fh;
11859: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11860: my @lines = <$fh>;
11861: &parse_domain_tab(\@lines);
1.448 albertel 11862: }
1.852 albertel 11863: close($fh);
11864: $loaded = 1;
1.327 albertel 11865: }
1.846 albertel 11866:
11867: sub domain {
1.852 albertel 11868: &load_domain_tab() if (!$loaded);
11869:
1.846 albertel 11870: my ($name,$what) = @_;
11871: return if ( !exists($domain{$name}) );
11872:
11873: if (!$what) {
11874: return $domain{$name}{'description'};
11875: }
11876: return $domain{$name}{$what};
11877: }
1.974 raeburn 11878:
11879: sub domain_info {
11880: &load_domain_tab() if (!$loaded);
11881: return %domain;
11882: }
11883:
1.327 albertel 11884: }
11885:
11886:
1.1 albertel 11887: # ------------------------------------------------------------- Read hosts file
11888: {
1.838 albertel 11889: my %hostname;
1.844 albertel 11890: my %hostdom;
1.845 albertel 11891: my %libserv;
1.852 albertel 11892: my $loaded;
1.888 albertel 11893: my %name_to_host;
1.1074 raeburn 11894: my %internetdom;
1.1107 raeburn 11895: my %LC_dns_serv;
1.852 albertel 11896:
11897: sub parse_hosts_tab {
11898: my ($file) = @_;
11899: foreach my $configline (@$file) {
11900: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11901: chomp($configline);
11902: if ($configline =~ /^\^/) {
11903: if ($configline =~ /^\^([\w.\-]+)/) {
11904: $LC_dns_serv{$1} = 1;
11905: }
11906: next;
11907: }
1.1074 raeburn 11908: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11909: $name=~s/\s//g;
11910: if ($id && $domain && $role && $name) {
11911: $hostname{$id}=$name;
1.888 albertel 11912: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11913: $hostdom{$id}=$domain;
11914: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11915: if (defined($protocol)) {
11916: if ($protocol eq 'https') {
11917: $protocol{$id} = $protocol;
11918: } else {
11919: $protocol{$id} = 'http';
11920: }
1.968 raeburn 11921: } else {
1.969 raeburn 11922: $protocol{$id} = 'http';
1.968 raeburn 11923: }
1.1074 raeburn 11924: if (defined($intdom)) {
11925: $internetdom{$id} = $intdom;
11926: }
1.852 albertel 11927: }
11928: }
11929: }
1.864 albertel 11930:
11931: sub reset_hosts_info {
1.897 albertel 11932: &purge_remembered();
1.864 albertel 11933: &reset_domain_info();
11934: &reset_hosts_ip_info();
1.892 albertel 11935: undef(%name_to_host);
1.864 albertel 11936: undef(%hostname);
11937: undef(%hostdom);
11938: undef(%libserv);
11939: undef($loaded);
11940: }
1.1 albertel 11941:
1.852 albertel 11942: sub load_hosts_tab {
1.869 albertel 11943: my ($ignore_cache) = @_;
11944: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11945: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11946: my @config = <$config>;
11947: &parse_hosts_tab(\@config);
11948: close($config);
11949: $loaded=1;
1.1 albertel 11950: }
1.852 albertel 11951:
1.838 albertel 11952: sub hostname {
1.852 albertel 11953: &load_hosts_tab() if (!$loaded);
11954:
1.838 albertel 11955: my ($lonid) = @_;
11956: return $hostname{$lonid};
11957: }
1.845 albertel 11958:
1.838 albertel 11959: sub all_hostnames {
1.852 albertel 11960: &load_hosts_tab() if (!$loaded);
11961:
1.838 albertel 11962: return %hostname;
11963: }
1.845 albertel 11964:
1.888 albertel 11965: sub all_names {
11966: &load_hosts_tab() if (!$loaded);
11967:
11968: return %name_to_host;
11969: }
11970:
1.974 raeburn 11971: sub all_host_domain {
11972: &load_hosts_tab() if (!$loaded);
11973: return %hostdom;
11974: }
11975:
1.845 albertel 11976: sub is_library {
1.852 albertel 11977: &load_hosts_tab() if (!$loaded);
11978:
1.845 albertel 11979: return exists($libserv{$_[0]});
11980: }
11981:
11982: sub all_library {
1.852 albertel 11983: &load_hosts_tab() if (!$loaded);
11984:
1.845 albertel 11985: return %libserv;
11986: }
11987:
1.1062 droeschl 11988: sub unique_library {
11989: #2x reverse removes all hostnames that appear more than once
11990: my %unique = reverse &all_library();
11991: return reverse %unique;
11992: }
11993:
1.841 albertel 11994: sub get_servers {
1.852 albertel 11995: &load_hosts_tab() if (!$loaded);
11996:
1.841 albertel 11997: my ($domain,$type) = @_;
11998: my %possible_hosts = ($type eq 'library') ? %libserv
11999: : %hostname;
12000: my %result;
1.842 albertel 12001: if (ref($domain) eq 'ARRAY') {
12002: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12003: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12004: $result{$host} = $hostname;
12005: }
12006: }
12007: } else {
12008: while ( my ($host,$hostname) = each(%possible_hosts)) {
12009: if ($hostdom{$host} eq $domain) {
12010: $result{$host} = $hostname;
12011: }
1.841 albertel 12012: }
12013: }
12014: return %result;
12015: }
1.845 albertel 12016:
1.1062 droeschl 12017: sub get_unique_servers {
12018: my %unique = reverse &get_servers(@_);
12019: return reverse %unique;
12020: }
12021:
1.844 albertel 12022: sub host_domain {
1.852 albertel 12023: &load_hosts_tab() if (!$loaded);
12024:
1.844 albertel 12025: my ($lonid) = @_;
12026: return $hostdom{$lonid};
12027: }
12028:
1.841 albertel 12029: sub all_domains {
1.852 albertel 12030: &load_hosts_tab() if (!$loaded);
12031:
1.841 albertel 12032: my %seen;
12033: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12034: return @uniq;
12035: }
1.1074 raeburn 12036:
12037: sub internet_dom {
12038: &load_hosts_tab() if (!$loaded);
12039:
12040: my ($lonid) = @_;
12041: return $internetdom{$lonid};
12042: }
1.1107 raeburn 12043:
12044: sub is_LC_dns {
12045: &load_hosts_tab() if (!$loaded);
12046:
12047: my ($hostname) = @_;
12048: return exists($LC_dns_serv{$hostname});
12049: }
12050:
1.1 albertel 12051: }
12052:
1.847 albertel 12053: {
12054: my %iphost;
1.856 albertel 12055: my %name_to_ip;
12056: my %lonid_to_ip;
1.869 albertel 12057:
1.847 albertel 12058: sub get_hosts_from_ip {
12059: my ($ip) = @_;
12060: my %iphosts = &get_iphost();
12061: if (ref($iphosts{$ip})) {
12062: return @{$iphosts{$ip}};
12063: }
12064: return;
1.839 albertel 12065: }
1.864 albertel 12066:
12067: sub reset_hosts_ip_info {
12068: undef(%iphost);
12069: undef(%name_to_ip);
12070: undef(%lonid_to_ip);
12071: }
1.856 albertel 12072:
12073: sub get_host_ip {
12074: my ($lonid) = @_;
12075: if (exists($lonid_to_ip{$lonid})) {
12076: return $lonid_to_ip{$lonid};
12077: }
12078: my $name=&hostname($lonid);
12079: my $ip = gethostbyname($name);
12080: return if (!$ip || length($ip) ne 4);
12081: $ip=inet_ntoa($ip);
12082: $name_to_ip{$name} = $ip;
12083: $lonid_to_ip{$lonid} = $ip;
12084: return $ip;
12085: }
1.847 albertel 12086:
12087: sub get_iphost {
1.869 albertel 12088: my ($ignore_cache) = @_;
1.894 albertel 12089:
1.869 albertel 12090: if (!$ignore_cache) {
12091: if (%iphost) {
12092: return %iphost;
12093: }
12094: my ($ip_info,$cached)=
12095: &Apache::lonnet::is_cached_new('iphost','iphost');
12096: if ($cached) {
12097: %iphost = %{$ip_info->[0]};
12098: %name_to_ip = %{$ip_info->[1]};
12099: %lonid_to_ip = %{$ip_info->[2]};
12100: return %iphost;
12101: }
12102: }
1.894 albertel 12103:
12104: # get yesterday's info for fallback
12105: my %old_name_to_ip;
12106: my ($ip_info,$cached)=
12107: &Apache::lonnet::is_cached_new('iphost','iphost');
12108: if ($cached) {
12109: %old_name_to_ip = %{$ip_info->[1]};
12110: }
12111:
1.888 albertel 12112: my %name_to_host = &all_names();
12113: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12114: my $ip;
12115: if (!exists($name_to_ip{$name})) {
12116: $ip = gethostbyname($name);
12117: if (!$ip || length($ip) ne 4) {
1.894 albertel 12118: if (defined($old_name_to_ip{$name})) {
12119: $ip = $old_name_to_ip{$name};
12120: &logthis("Can't find $name defaulting to old $ip");
12121: } else {
12122: &logthis("Name $name no IP found");
12123: next;
12124: }
12125: } else {
12126: $ip=inet_ntoa($ip);
1.847 albertel 12127: }
12128: $name_to_ip{$name} = $ip;
12129: } else {
12130: $ip = $name_to_ip{$name};
1.653 albertel 12131: }
1.888 albertel 12132: foreach my $id (@{ $name_to_host{$name} }) {
12133: $lonid_to_ip{$id} = $ip;
12134: }
12135: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12136: }
1.1172.2.23 raeburn 12137: &do_cache_new('iphost','iphost',
12138: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12139: 48*60*60);
1.869 albertel 12140:
1.847 albertel 12141: return %iphost;
1.598 albertel 12142: }
12143:
1.992 raeburn 12144: #
12145: # Given a DNS returns the loncapa host name for that DNS
12146: #
12147: sub host_from_dns {
12148: my ($dns) = @_;
12149: my @hosts;
12150: my $ip;
12151:
1.993 raeburn 12152: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12153: $ip = $name_to_ip{$dns};
12154: }
12155: if (!$ip) {
12156: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12157: if (length($ip) == 4) {
12158: $ip = &IO::Socket::inet_ntoa($ip);
12159: }
12160: }
12161: if ($ip) {
12162: @hosts = get_hosts_from_ip($ip);
12163: return $hosts[0];
12164: }
12165: return undef;
1.986 foxr 12166: }
1.992 raeburn 12167:
1.1074 raeburn 12168: sub get_internet_names {
12169: my ($lonid) = @_;
12170: return if ($lonid eq '');
12171: my ($idnref,$cached)=
12172: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12173: if ($cached) {
12174: return $idnref;
12175: }
12176: my $ip = &get_host_ip($lonid);
12177: my @hosts = &get_hosts_from_ip($ip);
12178: my %iphost = &get_iphost();
12179: my (@idns,%seen);
12180: foreach my $id (@hosts) {
12181: my $dom = &host_domain($id);
12182: my $prim_id = &domain($dom,'primary');
12183: my $prim_ip = &get_host_ip($prim_id);
12184: next if ($seen{$prim_ip});
12185: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12186: foreach my $id (@{$iphost{$prim_ip}}) {
12187: my $intdom = &internet_dom($id);
12188: unless (grep(/^\Q$intdom\E$/,@idns)) {
12189: push(@idns,$intdom);
12190: }
12191: }
12192: }
12193: $seen{$prim_ip} = 1;
12194: }
1.1172.2.23 raeburn 12195: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12196: }
12197:
1.986 foxr 12198: }
12199:
1.1079 raeburn 12200: sub all_loncaparevs {
12201: 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);
12202: }
12203:
1.1172.2.27 raeburn 12204: # ------------------------------------------------------- Read loncaparev table
12205: {
12206: sub load_loncaparevs {
12207: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12208: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12209: while (my $configline=<$config>) {
12210: chomp($configline);
12211: my ($hostid,$loncaparev)=split(/:/,$configline);
12212: $loncaparevs{$hostid}=$loncaparev;
12213: }
12214: close($config);
12215: }
12216: }
12217: }
12218: }
12219:
12220: # ----------------------------------------------------- Read serverhostID table
12221: {
12222: sub load_serverhomeIDs {
12223: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12224: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12225: while (my $configline=<$config>) {
12226: chomp($configline);
12227: my ($name,$id)=split(/:/,$configline);
12228: $serverhomeIDs{$name}=$id;
12229: }
12230: close($config);
12231: }
12232: }
12233: }
12234: }
12235:
12236:
1.862 albertel 12237: BEGIN {
12238:
12239: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12240: unless ($readit) {
12241: {
12242: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12243: %perlvar = (%perlvar,%{$configvars});
12244: }
12245:
12246:
1.1 albertel 12247: # ------------------------------------------------------ Read spare server file
12248: {
1.448 albertel 12249: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12250:
12251: while (my $configline=<$config>) {
12252: chomp($configline);
1.284 matthew 12253: if ($configline) {
1.784 albertel 12254: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12255: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12256: push(@{ $spareid{$type} }, $host);
1.1 albertel 12257: }
12258: }
1.448 albertel 12259: close($config);
1.1 albertel 12260: }
1.11 www 12261: # ------------------------------------------------------------ Read permissions
12262: {
1.448 albertel 12263: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12264:
12265: while (my $configline=<$config>) {
1.448 albertel 12266: chomp($configline);
12267: if ($configline) {
12268: my ($role,$perm)=split(/ /,$configline);
12269: if ($perm ne '') { $pr{$role}=$perm; }
12270: }
1.11 www 12271: }
1.448 albertel 12272: close($config);
1.11 www 12273: }
12274:
12275: # -------------------------------------------- Read plain texts for permissions
12276: {
1.448 albertel 12277: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12278:
12279: while (my $configline=<$config>) {
1.448 albertel 12280: chomp($configline);
12281: if ($configline) {
1.742 raeburn 12282: my ($short,@plain)=split(/:/,$configline);
12283: %{$prp{$short}} = ();
12284: if (@plain > 0) {
12285: $prp{$short}{'std'} = $plain[0];
12286: for (my $i=1; $i<@plain; $i++) {
12287: $prp{$short}{'alt'.$i} = $plain[$i];
12288: }
12289: }
1.448 albertel 12290: }
1.135 www 12291: }
1.448 albertel 12292: close($config);
1.135 www 12293: }
12294:
12295: # ---------------------------------------------------------- Read package table
12296: {
1.448 albertel 12297: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12298:
12299: while (my $configline=<$config>) {
1.483 albertel 12300: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12301: chomp($configline);
12302: my ($short,$plain)=split(/:/,$configline);
12303: my ($pack,$name)=split(/\&/,$short);
12304: if ($plain ne '') {
12305: $packagetab{$pack.'&'.$name.'&name'}=$name;
12306: $packagetab{$short}=$plain;
12307: }
1.11 www 12308: }
1.448 albertel 12309: close($config);
1.329 matthew 12310: }
12311:
1.1172.2.27 raeburn 12312: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12313:
1.1172.2.27 raeburn 12314: &load_loncaparevs();
12315:
12316: # ------------------------------------------------------- Read serverhostID table
12317:
12318: &load_serverhomeIDs();
1.1074 raeburn 12319:
1.1172.2.27 raeburn 12320: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12321: {
12322: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12323: if (-e $file) {
12324: my $parser = HTML::LCParser->new($file);
12325: while (my $token = $parser->get_token()) {
12326: if ($token->[0] eq 'S') {
12327: my $item = $token->[1];
12328: my $name = $token->[2]{'name'};
12329: my $value = $token->[2]{'value'};
12330: if ($item ne '' && $name ne '' && $value ne '') {
12331: my $release = $parser->get_text();
12332: $release =~ s/(^\s*|\s*$ )//gx;
12333: $needsrelease{$item.':'.$name.':'.$value} = $release;
12334: }
12335: }
12336: }
12337: }
1.1073 raeburn 12338: }
12339:
1.1138 raeburn 12340: # ---------------------------------------------------------- Read managers table
12341: {
12342: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12343: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12344: while (my $configline=<$config>) {
12345: chomp($configline);
12346: next if ($configline =~ /^\#/);
12347: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12348: $managerstab{$configline} = 1;
12349: }
12350: }
12351: close($config);
12352: }
12353: }
12354: }
12355:
1.329 matthew 12356: # ------------- set up temporary directory
12357: {
1.1117 foxr 12358: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12359:
1.11 www 12360: }
12361:
1.794 albertel 12362: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12363: 'compress_threshold'=> 20_000,
12364: });
1.185 www 12365:
1.281 www 12366: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12367: $dumpcount=0;
1.958 www 12368: $locknum=0;
1.22 www 12369:
1.163 harris41 12370: &logtouch();
1.672 albertel 12371: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12372: $readit=1;
1.564 albertel 12373: {
12374: use integer;
12375: my $test=(2**32)+1;
1.568 albertel 12376: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12377: &logthis(" Detected 64bit platform ($_64bit)");
12378: }
1.195 www 12379: }
1.1 albertel 12380: }
1.179 www 12381:
1.1 albertel 12382: 1;
1.191 harris41 12383: __END__
12384:
1.243 albertel 12385: =pod
12386:
1.191 harris41 12387: =head1 NAME
12388:
1.243 albertel 12389: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12390:
12391: =head1 SYNOPSIS
12392:
1.243 albertel 12393: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12394:
12395: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12396:
1.243 albertel 12397: Common parameters:
12398:
12399: =over 4
12400:
12401: =item *
12402:
12403: $uname : an internal username (if $cname expecting a course Id specifically)
12404:
12405: =item *
12406:
12407: $udom : a domain (if $cdom expecting a course's domain specifically)
12408:
12409: =item *
12410:
12411: $symb : a resource instance identifier
12412:
12413: =item *
12414:
12415: $namespace : the name of a .db file that contains the data needed or
12416: being set.
12417:
12418: =back
12419:
1.394 bowersj2 12420: =head1 OVERVIEW
1.191 harris41 12421:
1.394 bowersj2 12422: lonnet provides subroutines which interact with the
12423: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12424: about classes, users, and resources.
1.243 albertel 12425:
12426: For many of these objects you can also use this to store data about
12427: them or modify them in various ways.
1.191 harris41 12428:
1.394 bowersj2 12429: =head2 Symbs
1.191 harris41 12430:
1.394 bowersj2 12431: To identify a specific instance of a resource, LON-CAPA uses symbols
12432: or "symbs"X<symb>. These identifiers are built from the URL of the
12433: map, the resource number of the resource in the map, and the URL of
12434: the resource itself. The latter is somewhat redundant, but might help
12435: if maps change.
12436:
12437: An example is
12438:
12439: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12440:
12441: The respective map entry is
12442:
12443: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12444: title="Problem 2">
12445: </resource>
12446:
12447: Symbs are used by the random number generator, as well as to store and
12448: restore data specific to a certain instance of for example a problem.
12449:
12450: =head2 Storing And Retrieving Data
12451:
12452: X<store()>X<cstore()>X<restore()>Three of the most important functions
12453: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12454: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12455: is is the non-critical message twin of cstore. These functions are for
12456: handlers to store a perl hash to a user's permanent data space in an
12457: easy manner, and to retrieve it again on another call. It is expected
12458: that a handler would use this once at the beginning to retrieve data,
12459: and then again once at the end to send only the new data back.
12460:
12461: The data is stored in the user's data directory on the user's
12462: homeserver under the ID of the course.
12463:
12464: The hash that is returned by restore will have all of the previous
12465: value for all of the elements of the hash.
12466:
12467: Example:
12468:
12469: #creating a hash
12470: my %hash;
12471: $hash{'foo'}='bar';
12472:
12473: #storing it
12474: &Apache::lonnet::cstore(\%hash);
12475:
12476: #changing a value
12477: $hash{'foo'}='notbar';
12478:
12479: #adding a new value
12480: $hash{'bar'}='foo';
12481: &Apache::lonnet::cstore(\%hash);
12482:
12483: #retrieving the hash
12484: my %history=&Apache::lonnet::restore();
12485:
12486: #print the hash
12487: foreach my $key (sort(keys(%history))) {
12488: print("\%history{$key} = $history{$key}");
12489: }
12490:
12491: Will print out:
1.191 harris41 12492:
1.394 bowersj2 12493: %history{1:foo} = bar
12494: %history{1:keys} = foo:timestamp
12495: %history{1:timestamp} = 990455579
12496: %history{2:bar} = foo
12497: %history{2:foo} = notbar
12498: %history{2:keys} = foo:bar:timestamp
12499: %history{2:timestamp} = 990455580
12500: %history{bar} = foo
12501: %history{foo} = notbar
12502: %history{timestamp} = 990455580
12503: %history{version} = 2
12504:
12505: Note that the special hash entries C<keys>, C<version> and
12506: C<timestamp> were added to the hash. C<version> will be equal to the
12507: total number of versions of the data that have been stored. The
12508: C<timestamp> attribute will be the UNIX time the hash was
12509: stored. C<keys> is available in every historical section to list which
12510: keys were added or changed at a specific historical revision of a
12511: hash.
12512:
12513: B<Warning>: do not store the hash that restore returns directly. This
12514: will cause a mess since it will restore the historical keys as if the
12515: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12516:
1.394 bowersj2 12517: Calling convention:
1.191 harris41 12518:
1.1172.2.27 raeburn 12519: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12520: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12521:
1.394 bowersj2 12522: For more detailed information, see lonnet specific documentation.
1.191 harris41 12523:
1.394 bowersj2 12524: =head1 RETURN MESSAGES
1.191 harris41 12525:
1.394 bowersj2 12526: =over 4
1.191 harris41 12527:
1.394 bowersj2 12528: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12529:
1.394 bowersj2 12530: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12531: when the connection is brought back up
1.191 harris41 12532:
1.394 bowersj2 12533: =item * B<con_failed>: unable to contact remote host and unable to save message
12534: for later delivery
1.191 harris41 12535:
1.967 bisitz 12536: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12537:
1.394 bowersj2 12538: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12539: that was requested
1.191 harris41 12540:
1.243 albertel 12541: =back
1.191 harris41 12542:
1.243 albertel 12543: =head1 PUBLIC SUBROUTINES
1.191 harris41 12544:
1.243 albertel 12545: =head2 Session Environment Functions
1.191 harris41 12546:
1.243 albertel 12547: =over 4
1.191 harris41 12548:
1.394 bowersj2 12549: =item *
12550: X<appenv()>
1.949 raeburn 12551: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12552: the user envirnoment file, and will be restored for each access this
1.620 albertel 12553: user makes during this session, also modifies the %env for the current
1.949 raeburn 12554: process. Optional rolesarrayref - if defined contains a reference to an array
12555: of roles which are exempt from the restriction on modifying user.role entries
12556: in the user's environment.db and in %env.
1.191 harris41 12557:
12558: =item *
1.394 bowersj2 12559: X<delenv()>
1.987 raeburn 12560: B<delenv($delthis,$regexp)>: removes all items from the session
12561: environment file that begin with $delthis. If the
12562: optional second arg - $regexp - is true, $delthis is treated as a
12563: regular expression, otherwise \Q$delthis\E is used.
12564: The values are also deleted from the current processes %env.
1.191 harris41 12565:
1.795 albertel 12566: =item * get_env_multiple($name)
12567:
12568: gets $name from the %env hash, it seemlessly handles the cases where multiple
12569: values may be defined and end up as an array ref.
12570:
12571: returns an array of values
12572:
1.243 albertel 12573: =back
12574:
12575: =head2 User Information
1.191 harris41 12576:
1.243 albertel 12577: =over 4
1.191 harris41 12578:
12579: =item *
1.394 bowersj2 12580: X<queryauthenticate()>
12581: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12582: authentication scheme
12583:
12584: =item *
1.394 bowersj2 12585: X<authenticate()>
1.1073 raeburn 12586: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12587: authenticate user from domain's lib servers (first use the current
12588: one). C<$upass> should be the users password.
1.1073 raeburn 12589: $checkdefauth is optional (value is 1 if a check should be made to
12590: authenticate user using default authentication method, and allow
12591: account creation if username does not have account in the domain).
12592: $clientcancheckhost is optional (value is 1 if checking whether the
12593: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12594:
12595: =item *
1.394 bowersj2 12596: X<homeserver()>
12597: B<homeserver($uname,$udom)>: find the server which has
12598: the user's directory and files (there must be only one), this caches
12599: the answer, and also caches if there is a borken connection.
1.191 harris41 12600:
12601: =item *
1.394 bowersj2 12602: X<idget()>
12603: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12604: (IDs are a unique resource in a domain, there must be only 1 ID per
12605: username, and only 1 username per ID in a specific domain) (returns
12606: hash: id=>name,id=>name)
1.191 harris41 12607:
12608: =item *
1.394 bowersj2 12609: X<idrget()>
12610: B<idrget($udom,@unames)>: find the IDs behind a list of
12611: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12612:
12613: =item *
1.394 bowersj2 12614: X<idput()>
12615: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12616:
12617: =item *
1.394 bowersj2 12618: X<rolesinit()>
1.1169 droeschl 12619: B<rolesinit($udom,$username)>: get user privileges.
12620: returns user role, first access and timer interval hashes
1.243 albertel 12621:
12622: =item *
1.1171 droeschl 12623: X<privileged()>
12624: B<privileged($username,$domain)>: returns a true if user has a
12625: privileged and active role (i.e. su or dc), false otherwise.
12626:
12627: =item *
1.551 albertel 12628: X<getsection()>
12629: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12630: course $cname, return section name/number or '' for "not in course"
12631: and '-1' for "no section"
12632:
12633: =item *
1.394 bowersj2 12634: X<userenvironment()>
12635: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12636: passed in @what from the requested user's environment, returns a hash
12637:
1.858 raeburn 12638: =item *
12639: X<userlog_query()>
1.859 albertel 12640: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12641: activity.log file. %filters defines filters applied when parsing the
12642: log file. These can be start or end timestamps, or the type of action
12643: - log to look for Login or Logout events, check for Checkin or
12644: Checkout, role for role selection. The response is in the form
12645: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12646: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12647:
1.243 albertel 12648: =back
12649:
12650: =head2 User Roles
12651:
12652: =over 4
12653:
12654: =item *
12655:
1.810 raeburn 12656: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12657: F: full access
12658: U,I,K: authentication modes (cxx only)
12659: '': forbidden
12660: 1: user needs to choose course
12661: 2: browse allowed
1.766 albertel 12662: A: passphrase authentication needed
1.243 albertel 12663:
12664: =item *
12665:
1.1172.2.13 raeburn 12666: constructaccess($url,$setpriv) : check for access to construction space URL
12667:
12668: See if the owner domain and name in the URL match those in the
12669: expected environment. If so, return three element list
12670: ($ownername,$ownerdomain,$ownerhome).
12671:
12672: Otherwise return the null string.
12673:
12674: If second argument 'setpriv' is true, it assigns the privileges,
12675: and returns the same three element list, unless the owner has
12676: blocked "ad hoc" Domain Coordinator access to the Author Space,
12677: in which case the null string is returned.
12678:
12679: =item *
12680:
1.243 albertel 12681: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12682: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12683: and course level
12684:
12685: =item *
12686:
1.988 raeburn 12687: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12688: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12689: $type is Course (default) or Community.
1.988 raeburn 12690: If $forcedefault evaluates to true, text returned will be default
12691: text for $type. Otherwise, if this is a course, the text returned
12692: will be a custom name for the role (if defined in the course's
12693: environment). If no custom name is defined the default is returned.
12694:
1.832 raeburn 12695: =item *
12696:
1.1172.2.23 raeburn 12697: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12698: All arguments are optional. Returns a hash of a roles, either for
12699: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12700: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12701: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12702: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12703: For each key, value is set to colon-separated start and end times for
12704: the role. If no username and domain are specified, will default to
1.934 raeburn 12705: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12706: of role statuses (active, future or previous), roles
12707: (e.g., cc,in, st etc.) and domains of the roles which can be used
12708: to restrict the list of roles reported. If no array ref is
12709: provided for types, will default to return only active roles.
1.834 albertel 12710:
1.1172.2.13 raeburn 12711: =item *
12712:
12713: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12714: user: $uname:$udom has a role in the course: $cdom_$cnum.
12715:
12716: Additional optional arguments are: $type (if role checking is to be restricted
12717: to certain user status types -- previous (expired roles), active (currently
12718: available roles) or future (roles available in the future), and
12719: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12720: have active Domain Coordinator role in course's domain or in additional
12721: domains (specified in 'Domains to check for privileged users' in course
12722: environment -- set via: Course Settings -> Classlists and staff listing).
12723:
12724: =item *
12725:
12726: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12727: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12728: $possdomains and $possroles are optional array refs -- to domains to check and
12729: roles to check. If $possdomains is not specified, a dump will be done of the
12730: users' roles.db to check for a dc or su role in any domain. This can be
12731: time consuming if &privileged is called repeatedly (e.g., when displaying a
12732: classlist), so in such cases, supplying a $possdomains array is preferred, as
12733: this then allows &privileged_by_domain() to be used, which caches the identity
12734: of privileged users, eliminating the need for repeated calls to &dump().
12735:
12736: =item *
12737:
12738: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12739: where the outer hash keys are domains specified in the $possdomains array ref,
12740: next inner hash keys are privileged roles specified in the $roles array ref,
12741: and the innermost hash contains key = value pairs for username:domain = end:start
12742: for active or future "privileged" users with that role in that domain. To avoid
12743: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12744: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12745:
1.243 albertel 12746: =back
12747:
12748: =head2 User Modification
12749:
12750: =over 4
12751:
12752: =item *
12753:
1.957 raeburn 12754: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12755: user for the level given by URL. Optional start and end dates (leave empty
12756: string or zero for "no date")
1.191 harris41 12757:
12758: =item *
12759:
1.243 albertel 12760: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12761: change a users, password, possible return values are: ok,
12762: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12763: refused
1.191 harris41 12764:
12765: =item *
12766:
1.243 albertel 12767: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12768:
12769: =item *
12770:
1.1058 raeburn 12771: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12772: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12773:
12774: will update user information (firstname,middlename,lastname,generation,
12775: permanentemail), and if forceid is true, student/employee ID also.
12776: A user's institutional affiliation(s) can also be updated.
12777: User information fields will not be overwritten with empty entries
12778: unless the field is included in the $candelete array reference.
12779: This array is included when a single user is modified via "Manage Users",
12780: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12781:
12782: =item *
12783:
1.286 matthew 12784: modifystudent
12785:
1.957 raeburn 12786: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12787: The course id is resolved based on the current user's environment.
12788: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12789: associated with a course.
12790:
1.297 matthew 12791: This call is essentially a wrapper for lonnet::modifyuser and
12792: lonnet::modify_student_enrollment
1.286 matthew 12793:
12794: Inputs:
12795:
12796: =over 4
12797:
1.957 raeburn 12798: =item B<$udom> Student's loncapa domain
1.286 matthew 12799:
1.957 raeburn 12800: =item B<$uname> Student's loncapa login name
1.286 matthew 12801:
1.964 bisitz 12802: =item B<$uid> Student/Employee ID
1.286 matthew 12803:
1.957 raeburn 12804: =item B<$umode> Student's authentication mode
1.286 matthew 12805:
1.957 raeburn 12806: =item B<$upass> Student's password
1.286 matthew 12807:
1.957 raeburn 12808: =item B<$first> Student's first name
1.286 matthew 12809:
1.957 raeburn 12810: =item B<$middle> Student's middle name
1.286 matthew 12811:
1.957 raeburn 12812: =item B<$last> Student's last name
1.286 matthew 12813:
1.957 raeburn 12814: =item B<$gene> Student's generation
1.286 matthew 12815:
1.957 raeburn 12816: =item B<$usec> Student's section in course
1.286 matthew 12817:
12818: =item B<$end> Unix time of the roles expiration
12819:
12820: =item B<$start> Unix time of the roles start date
12821:
12822: =item B<$forceid> If defined, allow $uid to be changed
12823:
12824: =item B<$desiredhome> server to use as home server for student
12825:
1.957 raeburn 12826: =item B<$email> Student's permanent e-mail address
12827:
12828: =item B<$type> Type of enrollment (auto or manual)
12829:
1.963 raeburn 12830: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12831:
12832: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12833:
1.963 raeburn 12834: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12835:
1.963 raeburn 12836: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12837:
1.1172.2.19 raeburn 12838: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12839:
12840: =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 12841:
1.286 matthew 12842: =back
1.297 matthew 12843:
12844: =item *
12845:
12846: modify_student_enrollment
12847:
1.1172.2.31 raeburn 12848: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12849: 'role.request.course' must be defined for this function to proceed.
12850:
12851: Inputs:
12852:
12853: =over 4
12854:
1.1172.2.31 raeburn 12855: =item $udom, student's domain
1.297 matthew 12856:
1.1172.2.31 raeburn 12857: =item $uname, student's name
1.297 matthew 12858:
1.1172.2.31 raeburn 12859: =item $uid, student's user id
1.297 matthew 12860:
1.1172.2.31 raeburn 12861: =item $first, student's first name
1.297 matthew 12862:
12863: =item $middle
12864:
12865: =item $last
12866:
12867: =item $gene
12868:
12869: =item $usec
12870:
12871: =item $end
12872:
12873: =item $start
12874:
1.957 raeburn 12875: =item $type
12876:
12877: =item $locktype
12878:
12879: =item $cid
12880:
12881: =item $selfenroll
12882:
12883: =item $context
12884:
1.1172.2.19 raeburn 12885: =item $credits, number of credits student will earn from this class
12886:
1.297 matthew 12887: =back
12888:
1.191 harris41 12889:
12890: =item *
12891:
1.243 albertel 12892: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12893: custom role; give a custom role to a user for the level given by URL. Specify
12894: name and domain of role author, and role name
1.191 harris41 12895:
12896: =item *
12897:
1.243 albertel 12898: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12899:
12900: =item *
12901:
1.243 albertel 12902: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12903:
12904: =back
12905:
12906: =head2 Course Infomation
12907:
12908: =over 4
1.191 harris41 12909:
12910: =item *
12911:
1.1118 foxr 12912: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12913: specified course id, including all environment settings for the
12914: course, the description of the course will be in the hash under the
12915: key 'description'
1.191 harris41 12916:
1.1118 foxr 12917: $options is an optional parameter that if supplied is a hash reference that controls
12918: what how this function works. It has the following key/values:
12919:
12920: =over 4
12921:
12922: =item freshen_cache
12923:
12924: If defined, and the environment cache for the course is valid, it is
12925: returned in the returned hash.
12926:
12927: =item one_time
12928:
12929: If defined, the last cache time is set to _now_
12930:
12931: =item user
12932:
12933: If defined, the supplied username is used instead of the current user.
12934:
12935:
12936: =back
12937:
1.191 harris41 12938: =item *
12939:
1.624 albertel 12940: resdata($name,$domain,$type,@which) : request for current parameter
12941: setting for a specific $type, where $type is either 'course' or 'user',
12942: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 12943: answers for 10 minutes.
1.243 albertel 12944:
1.877 foxr 12945: =item *
12946:
12947: get_courseresdata($courseid, $domain) : dump the entire course resource
12948: data base, returning a hash that is keyed by the resource name and has
12949: values that are the resource value. I believe that the timestamps and
12950: versions are also returned.
12951:
1.1172.2.31 raeburn 12952: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12953: supplemental content area. This routine caches the number of files for
12954: 10 minutes.
12955:
1.243 albertel 12956: =back
12957:
12958: =head2 Course Modification
12959:
12960: =over 4
1.191 harris41 12961:
12962: =item *
12963:
1.243 albertel 12964: writecoursepref($courseid,%prefs) : write preferences (environment
12965: database) for a course
1.191 harris41 12966:
12967: =item *
12968:
1.1011 raeburn 12969: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12970:
12971: =item *
12972:
1.1038 raeburn 12973: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12974:
1.1167 droeschl 12975: =item *
12976:
12977: is_course($courseid), is_course($cdom, $cnum)
12978:
12979: Accepts either a combined $courseid (in the form of domain_courseid) or the
12980: two component version $cdom, $cnum. It checks if the specified course exists.
12981:
12982: Returns:
12983: undef if the course doesn't exist, otherwise
12984: in scalar context the combined courseid.
12985: in list context the two components of the course identifier, domain and
12986: courseid.
12987:
1.243 albertel 12988: =back
12989:
12990: =head2 Resource Subroutines
12991:
12992: =over 4
1.191 harris41 12993:
12994: =item *
12995:
1.243 albertel 12996: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12997:
12998: =item *
12999:
1.243 albertel 13000: repcopy($filename) : subscribes to the requested file, and attempts to
13001: replicate from the owning library server, Might return
1.607 raeburn 13002: 'unavailable', 'not_found', 'forbidden', 'ok', or
13003: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13004: resource. Expects the local filesystem pathname
13005: (/home/httpd/html/res/....)
13006:
13007: =back
13008:
13009: =head2 Resource Information
13010:
13011: =over 4
1.191 harris41 13012:
13013: =item *
13014:
1.1172.2.28 raeburn 13015: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13016: and returns the value of a variety of different possible values,
13017: $varname should be a request string, and the other parameters can be
13018: used to specify who and what one is asking about. Ordinarily, $cid
13019: does not need to be specified, as it is retrived from
13020: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13021: within lonuserstate::loadmap() when initializing a course, before
13022: $env{'request.course.id'} has been set, so it needs to be provided
13023: in that one case.
1.243 albertel 13024:
13025: Possible values for $varname are environment.lastname (or other item
13026: from the envirnment hash), user.name (or someother aspect about the
13027: user), resource.0.maxtries (or some other part and parameter of a
13028: resource)
1.204 albertel 13029:
13030: =item *
13031:
1.243 albertel 13032: directcondval($number) : get current value of a condition; reads from a state
13033: string
1.204 albertel 13034:
13035: =item *
13036:
1.243 albertel 13037: condval($condidx) : value of condition index based on state
1.204 albertel 13038:
13039: =item *
13040:
1.243 albertel 13041: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13042: resource's metadata, $what should be either a specific key, or either
13043: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13044: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13045:
13046: this function automatically caches all requests
1.191 harris41 13047:
13048: =item *
13049:
1.243 albertel 13050: metadata_query($query,$custom,$customshow) : make a metadata query against the
13051: network of library servers; returns file handle of where SQL and regex results
13052: will be stored for query
1.191 harris41 13053:
13054: =item *
13055:
1.243 albertel 13056: symbread($filename) : return symbolic list entry (filename argument optional);
13057: returns the data handle
1.191 harris41 13058:
13059: =item *
13060:
1.1172.2.17 raeburn 13061: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13062: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13063: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13064: on failure, user must be in a course, as it assumes the existence of
13065: the course initial hash, and uses $env('request.course.id'}. The third
13066: arg is an optional reference to a scalar. If this arg is passed in the
13067: call to symbverify, it will be set to 1 if the symb has been set to be
13068: encrypted; otherwise it will be null.
1.243 albertel 13069:
1.191 harris41 13070: =item *
13071:
1.243 albertel 13072: symbclean($symb) : removes versions numbers from a symb, returns the
13073: cleaned symb
1.191 harris41 13074:
13075: =item *
13076:
1.243 albertel 13077: is_on_map($uri) : checks if the $uri is somewhere on the current
13078: course map, user must be in a course for it to work.
1.191 harris41 13079:
13080: =item *
13081:
1.243 albertel 13082: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13083:
13084: =item *
13085:
1.243 albertel 13086: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13087: a random seed, all arguments are optional, if they aren't sent it uses the
13088: environment to derive them. Note: if symb isn't sent and it can't get one
13089: from &symbread it will use the current time as its return value
1.191 harris41 13090:
13091: =item *
13092:
1.243 albertel 13093: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13094: unfakeable, receipt
1.191 harris41 13095:
13096: =item *
13097:
1.620 albertel 13098: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13099:
13100: =item *
13101:
1.243 albertel 13102: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13103:
13104: =item *
13105:
1.243 albertel 13106: 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 13107:
13108: =item *
13109:
1.243 albertel 13110: 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 13111:
13112: =item *
13113:
1.243 albertel 13114: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13115:
13116: =item *
13117:
1.243 albertel 13118: devalidate($symb) : devalidate temporary spreadsheet calculations,
13119: forcing spreadsheet to reevaluate the resource scores next time.
13120:
1.1172.2.13 raeburn 13121: =item *
13122:
13123: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13124: when viewing in course context.
13125:
13126: input: six args -- filename (decluttered), course number, course domain,
13127: url, symb (if registered) and group (if this is a
13128: group item -- e.g., bulletin board, group page etc.).
13129:
13130: output: array of five scalars --
13131: $cfile -- url for file editing if editable on current server
13132: $home -- homeserver of resource (i.e., for author if published,
13133: or course if uploaded.).
13134: $switchserver -- 1 if server switch will be needed.
13135: $forceedit -- 1 if icon/link should be to go to edit mode
13136: $forceview -- 1 if icon/link should be to go to view mode
13137:
13138: =item *
13139:
13140: is_course_upload($file,$cnum,$cdom)
13141:
13142: Used in course context to determine if current file was uploaded to
13143: the course (i.e., would be found in /userfiles/docs on the course's
13144: homeserver.
13145:
13146: input: 3 args -- filename (decluttered), course number and course domain.
13147: output: boolean -- 1 if file was uploaded.
13148:
1.243 albertel 13149: =back
13150:
13151: =head2 Storing/Retreiving Data
13152:
13153: =over 4
1.191 harris41 13154:
13155: =item *
13156:
1.243 albertel 13157: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13158: for this url; hashref needs to be given and should be a \%hashname; the
13159: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13160: be derived from the env
1.191 harris41 13161:
13162: =item *
13163:
1.243 albertel 13164: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13165: uses critical subroutine
1.191 harris41 13166:
13167: =item *
13168:
1.243 albertel 13169: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13170: all args are optional
1.191 harris41 13171:
13172: =item *
13173:
1.717 albertel 13174: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13175: dumps the complete (or key matching regexp) namespace into a hash
13176: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13177: normally &store()ed into
13178:
13179: $range should be either an integer '100' (give me the first 100
13180: matching records)
13181: or be two integers sperated by a - with no spaces
13182: '30-50' (give me the 30th through the 50th matching
13183: records)
13184:
13185:
13186: =item *
13187:
13188: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13189: replaces a &store() version of data with a replacement set of data
13190: for a particular resource in a namespace passed in the $storehash hash
13191: reference
13192:
13193: =item *
13194:
1.243 albertel 13195: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13196: works very similar to store/cstore, but all data is stored in a
13197: temporary location and can be reset using tmpreset, $storehash should
13198: be a hash reference, returns nothing on success
1.191 harris41 13199:
13200: =item *
13201:
1.243 albertel 13202: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13203: similar to restore, but all data is stored in a temporary location and
13204: can be reset using tmpreset. Returns a hash of values on success,
13205: error string otherwise.
1.191 harris41 13206:
13207: =item *
13208:
1.243 albertel 13209: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13210: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13211:
13212: =item *
13213:
1.243 albertel 13214: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13215: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13216:
13217: =item *
13218:
1.243 albertel 13219: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13220: namesp ($udom and $uname are optional)
1.191 harris41 13221:
13222: =item *
13223:
1.702 albertel 13224: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13225: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13226: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13227:
1.702 albertel 13228: $range should be either an integer '100' (give me the first 100
13229: matching records)
13230: or be two integers sperated by a - with no spaces
13231: '30-50' (give me the 30th through the 50th matching
13232: records)
1.449 matthew 13233: =item *
13234:
13235: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13236: $store can be a scalar, an array reference, or if the amount to be
13237: incremented is > 1, a hash reference.
13238:
13239: ($udom and $uname are optional)
1.191 harris41 13240:
13241: =item *
13242:
1.243 albertel 13243: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13244: ($udom and $uname are optional)
1.191 harris41 13245:
13246: =item *
13247:
1.243 albertel 13248: cput($namespace,$storehash,$udom,$uname) : critical put
13249: ($udom and $uname are optional)
1.191 harris41 13250:
13251: =item *
13252:
1.748 albertel 13253: newput($namespace,$storehash,$udom,$uname) :
13254:
13255: Attempts to store the items in the $storehash, but only if they don't
13256: currently exist, if this succeeds you can be certain that you have
13257: successfully created a new key value pair in the $namespace db.
13258:
13259:
13260: Args:
13261: $namespace: name of database to store values to
13262: $storehash: hashref to store to the db
13263: $udom: (optional) domain of user containing the db
13264: $uname: (optional) name of user caontaining the db
13265:
13266: Returns:
13267: 'ok' -> succeeded in storing all keys of $storehash
13268: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13269: least <key> already existed in the db (other
13270: requested keys may also already exist)
1.967 bisitz 13271: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13272: 'con_lost' -> unable to contact request server
13273: 'refused' -> action was not allowed by remote machine
13274:
13275:
13276: =item *
13277:
1.243 albertel 13278: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13279: reference filled in from namesp (encrypts the return communication)
13280: ($udom and $uname are optional)
1.191 harris41 13281:
13282: =item *
13283:
1.243 albertel 13284: log($udom,$name,$home,$message) : write to permanent log for user; use
13285: critical subroutine
13286:
1.806 raeburn 13287: =item *
13288:
1.860 raeburn 13289: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13290: array reference filled in from namespace found in domain level on either
13291: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13292:
13293: =item *
13294:
1.860 raeburn 13295: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13296: domain level either on specified domain server ($uhome) or primary domain
13297: server ($udom and $uhome are optional)
1.806 raeburn 13298:
1.943 raeburn 13299: =item *
13300:
1.1172.2.35 raeburn 13301: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13302: for: authentication, language, quotas, timezone, date locale, and portal URL in
13303: the target domain.
13304:
13305: May also include additional key => value pairs for the following groups:
13306:
13307: =over
13308:
13309: =item
13310: disk quotas (MB allocated by default to portfolios and authoring spaces).
13311:
13312: =over
13313:
13314: =item defaultquota, authorquota
13315:
13316: =back
13317:
13318: =item
13319: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13320: portfolio for users).
13321:
13322: =over
13323:
13324: =item
13325: aboutme, blog, webdav, portfolio
13326:
13327: =back
13328:
13329: =item
13330: requestcourses: ability to request courses, and how requests are processed.
13331:
13332: =over
13333:
13334: =item
13335: official, unofficial, community
13336:
13337: =back
13338:
13339: =item
13340: inststatus: types of institutional affiliation, and order in which they are displayed.
13341:
13342: =over
13343:
13344: =item
13345: inststatustypes, inststatusorder
13346:
13347: =back
13348:
13349: =item
13350: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13351: for course's uploaded content.
13352:
13353: =over
13354:
13355: =item
13356: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13357:
13358: =back
13359:
13360: =item
13361: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13362: on your servers.
13363:
13364: =over
13365:
13366: =item
13367: remotesessions, hostedsessions
13368:
13369: =back
13370:
13371: =back
13372:
13373: In cases where a domain coordinator has never used the "Set Domain Configuration"
13374: utility to create a configuration.db file on a domain's primary library server
13375: only the following domain defaults: auth_def, auth_arg_def, lang_def
13376: -- corresponding values are authentication type (internal, krb4, krb5,
13377: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13378: will be available. Values are retrieved from cache (if current), unless the
13379: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13380: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13381:
13382: Typical usage:
1.943 raeburn 13383:
1.1172.2.35 raeburn 13384: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13385:
1.243 albertel 13386: =back
13387:
13388: =head2 Network Status Functions
13389:
13390: =over 4
1.191 harris41 13391:
13392: =item *
13393:
1.1137 raeburn 13394: dirlist() : return directory list based on URI (first arg).
13395:
13396: Inputs: 1 required, 5 optional.
13397:
13398: =over
13399:
13400: =item
13401: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13402:
13403: =item
13404: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13405:
13406: =item
13407: $username - username of user/course to be listed. Extracted from $uri if absent.
13408:
13409: =item
13410: $getpropath - boolean: 1 if prepend path using &propath().
13411:
13412: =item
13413: $getuserdir - boolean: 1 if prepend path for "userfiles".
13414:
13415: =item
13416: $alternateRoot - path to prepend in place of path from $uri.
13417:
13418: =back
13419:
13420: Returns: Array of up to two items.
13421:
13422: =over
13423:
13424: a reference to an array of files/subdirectories
13425:
13426: =over
13427:
13428: Each element in the array of files/subdirectories is a & separated list of
13429: item name and the result of running stat on the item. If dirlist was requested
13430: for a file instead of a directory, the item name will be ''. For a directory
13431: listing, if the item is a metadata file, the element will end &N&M
13432: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13433: default copyright set (1).
13434:
13435: =back
13436:
13437: a scalar containing error condition (if encountered).
13438:
13439: =over
13440:
13441: =item
13442: no_host (no homeserver identified for $username:$domain).
13443:
13444: =item
13445: no_such_host (server contacted for listing not identified as valid host).
13446:
13447: =item
13448: con_lost (connection to remote server failed).
13449:
13450: =item
13451: refused (invalid $username:$domain received on lond side).
13452:
13453: =item
13454: no_such_dir (directory at specified path on lond side does not exist).
13455:
13456: =item
13457: empty (directory at specified path on lond side is empty).
13458:
13459: =over
13460:
13461: This is currently not encountered because the &ls3, &ls2,
13462: &ls (_handler) routines on the lond side do not filter out
13463: . and .. from a directory listing.
13464:
13465: =back
13466:
13467: =back
13468:
13469: =back
1.191 harris41 13470:
13471: =item *
13472:
1.243 albertel 13473: spareserver() : find server with least workload from spare.tab
13474:
1.986 foxr 13475:
13476: =item *
13477:
13478: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13479: if there is no corresponding loncapa host.
13480:
1.243 albertel 13481: =back
13482:
1.986 foxr 13483:
1.243 albertel 13484: =head2 Apache Request
13485:
13486: =over 4
1.191 harris41 13487:
13488: =item *
13489:
1.243 albertel 13490: ssi($url,%hash) : server side include, does a complete request cycle on url to
13491: localhost, posts hash
13492:
13493: =back
13494:
13495: =head2 Data to String to Data
13496:
13497: =over 4
1.191 harris41 13498:
13499: =item *
13500:
1.243 albertel 13501: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13502: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13503:
13504: =item *
13505:
1.243 albertel 13506: hashref2str($hashref) : convert a hashref into a string complete with
13507: escaping and '=' and '&' separators, supports elements that are
13508: arrayrefs and hashrefs
1.191 harris41 13509:
13510: =item *
13511:
1.243 albertel 13512: arrayref2str($arrayref) : convert an arrayref into a string complete
13513: with escaping and '&' separators, supports elements that are arrayrefs
13514: and hashrefs
1.191 harris41 13515:
13516: =item *
13517:
1.243 albertel 13518: str2hash($string) : convert string to hash using unescaping and
13519: splitting on '=' and '&', supports elements that are arrayrefs and
13520: hashrefs
1.191 harris41 13521:
13522: =item *
13523:
1.243 albertel 13524: str2array($string) : convert string to hash using unescaping and
13525: splitting on '&', supports elements that are arrayrefs and hashrefs
13526:
13527: =back
13528:
13529: =head2 Logging Routines
13530:
13531:
13532: These routines allow one to make log messages in the lonnet.log and
13533: lonnet.perm logfiles.
1.191 harris41 13534:
1.1119 foxr 13535: =over 4
13536:
1.191 harris41 13537: =item *
13538:
1.243 albertel 13539: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13540:
13541: =item *
13542:
1.243 albertel 13543: logthis() : append message to the normal lonnet.log file, it gets
13544: preiodically rolled over and deleted.
1.191 harris41 13545:
13546: =item *
13547:
1.243 albertel 13548: logperm() : append a permanent message to lonnet.perm.log, this log
13549: file never gets deleted by any automated portion of the system, only
13550: messages of critical importance should go in here.
13551:
1.1119 foxr 13552:
1.243 albertel 13553: =back
13554:
13555: =head2 General File Helper Routines
13556:
13557: =over 4
1.191 harris41 13558:
13559: =item *
13560:
1.481 raeburn 13561: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13562: (a) files in /uploaded
13563: (i) If a local copy of the file exists -
13564: compares modification date of local copy with last-modified date for
13565: definitive version stored on home server for course. If local copy is
13566: stale, requests a new version from the home server and stores it.
13567: If the original has been removed from the home server, then local copy
13568: is unlinked.
13569: (ii) If local copy does not exist -
13570: requests the file from the home server and stores it.
13571:
13572: If $caller is 'uploadrep':
13573: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13574: for request for files originally uploaded via DOCS.
13575: - returns 'ok' if fresh local copy now available, -1 otherwise.
13576:
13577: Otherwise:
13578: This indicates a call from the content generation phase of the request.
13579: - returns the entire contents of the file or -1.
13580:
13581: (b) files in /res
13582: - returns the entire contents of a file or -1;
13583: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13584:
1.712 albertel 13585:
13586: =item *
13587:
13588: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13589: reference
13590:
13591: returns either a stat() list of data about the file or an empty list
13592: if the file doesn't exist or couldn't find out about it (connection
13593: problems or user unknown)
13594:
1.191 harris41 13595: =item *
13596:
1.243 albertel 13597: filelocation($dir,$file) : returns file system location of a file
13598: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13599: directory that relative $file lookups are to looked in ($dir of /a/dir
13600: and a file of ../bob will become /a/bob)
1.191 harris41 13601:
13602: =item *
13603:
13604: hreflocation($dir,$file) : returns file system location or a URL; same as
13605: filelocation except for hrefs
13606:
13607: =item *
13608:
13609: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13610:
1.243 albertel 13611: =back
13612:
1.608 albertel 13613: =head2 Usererfile file routines (/uploaded*)
13614:
13615: =over 4
13616:
13617: =item *
13618:
13619: userfileupload(): main rotine for putting a file in a user or course's
13620: filespace, arguments are,
13621:
1.620 albertel 13622: formname - required - this is the name of the element in $env where the
1.608 albertel 13623: filename, and the contents of the file to create/modifed exist
1.620 albertel 13624: the filename is in $env{'form.'.$formname.'.filename'} and the
13625: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13626: context - if coursedoc, store the file in the course of the active role
13627: of the current user;
13628: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13629: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13630: subdir - required - subdirectory to put the file in under ../userfiles/
13631: if undefined, it will be placed in "unknown"
13632:
13633: (This routine calls clean_filename() to remove any dangerous
13634: characters from the filename, and then calls finuserfileupload() to
13635: complete the transaction)
13636:
13637: returns either the url of the uploaded file (/uploaded/....) if successful
13638: and /adm/notfound.html if unsuccessful
13639:
13640: =item *
13641:
13642: clean_filename(): routine for cleaing a filename up for storage in
13643: userfile space, argument is:
13644:
13645: filename - proposed filename
13646:
13647: returns: the new clean filename
13648:
13649: =item *
13650:
1.1090 raeburn 13651: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13652: userspace, probably shouldn't be called directly
13653:
13654: docuname: username or courseid of destination for the file
13655: docudom: domain of user/course of destination for the file
13656: formname: same as for userfileupload()
1.1090 raeburn 13657: fname: filename (including subdirectories) for the file
13658: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13659: allfiles: reference to hash used to store objects found by parser
13660: codebase: reference to hash used for codebases of java objects found by parser
13661: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13662: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13663: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13664: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13665: context: if 'overwrite', will move the uploaded file from its temporary location to
13666: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13667: mimetype: reference to scalar to accommodate mime type determined
13668: from File::MMagic if $parser = parse.
1.608 albertel 13669:
13670: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13671: and /adm/notfound.html if unsuccessful (or an error message if context
13672: was 'overwrite').
13673:
1.608 albertel 13674:
13675: =item *
13676:
13677: renameuserfile(): renames an existing userfile to a new name
13678:
13679: Args:
13680: docuname: username or courseid of destination for the file
13681: docudom: domain of user/course of destination for the file
13682: old: current file name (including any subdirs under userfiles)
13683: new: desired file name (including any subdirs under userfiles)
13684:
13685: =item *
13686:
13687: mkdiruserfile(): creates a directory is a userfiles dir
13688:
13689: Args:
13690: docuname: username or courseid of destination for the file
13691: docudom: domain of user/course of destination for the file
13692: dir: dir to create (including any subdirs under userfiles)
13693:
13694: =item *
13695:
13696: removeuserfile(): removes a file that exists in userfiles
13697:
13698: Args:
13699: docuname: username or courseid of destination for the file
13700: docudom: domain of user/course of destination for the file
13701: fname: filname to delete (including any subdirs under userfiles)
13702:
13703: =item *
13704:
13705: removeuploadedurl(): convience function for removeuserfile()
13706:
13707: Args:
13708: url: a full /uploaded/... url to delete
13709:
1.747 albertel 13710: =item *
13711:
13712: get_portfile_permissions():
13713: Args:
13714: domain: domain of user or course contain the portfolio files
13715: user: name of user or num of course contain the portfolio files
13716: Returns:
13717: hashref of a dump of the proper file_permissions.db
13718:
13719:
13720: =item *
13721:
13722: get_access_controls():
13723:
13724: Args:
13725: current_permissions: the hash ref returned from get_portfile_permissions()
13726: group: (optional) the group you want the files associated with
13727: file: (optional) the file you want access info on
13728:
13729: Returns:
1.749 raeburn 13730: a hash (keys are file names) of hashes containing
13731: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13732: values are XML containing access control settings (see below)
1.747 albertel 13733:
13734: Internal notes:
13735:
1.749 raeburn 13736: access controls are stored in file_permissions.db as key=value pairs.
13737: key -> path to file/file_name\0uniqueID:scope_end_start
13738: where scope -> public,guest,course,group,domains or users.
13739: end -> UNIX time for end of access (0 -> no end date)
13740: start -> UNIX time for start of access
13741:
13742: value -> XML description of access control
13743: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13744: <start></start>
13745: <end></end>
13746:
13747: <password></password> for scope type = guest
13748:
13749: <domain></domain> for scope type = course or group
13750: <number></number>
13751: <roles id="">
13752: <role></role>
13753: <access></access>
13754: <section></section>
13755: <group></group>
13756: </roles>
13757:
13758: <dom></dom> for scope type = domains
13759:
13760: <users> for scope type = users
13761: <user>
13762: <uname></uname>
13763: <udom></udom>
13764: </user>
13765: </users>
13766: </scope>
13767:
13768: Access data is also aggregated for each file in an additional key=value pair:
13769: key -> path to file/file_name\0accesscontrol
13770: value -> reference to hash
13771: hash contains key = value pairs
13772: where key = uniqueID:scope_end_start
13773: value = UNIX time record was last updated
13774:
13775: Used to improve speed of look-ups of access controls for each file.
13776:
13777: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13778:
1.1172.2.13 raeburn 13779: =item *
13780:
1.749 raeburn 13781: modify_access_controls():
13782:
13783: Modifies access controls for a portfolio file
13784: Args
13785: 1. file name
13786: 2. reference to hash of required changes,
13787: 3. domain
13788: 4. username
13789: where domain,username are the domain of the portfolio owner
13790: (either a user or a course)
13791:
13792: Returns:
13793: 1. result of additions or updates ('ok' or 'error', with error message).
13794: 2. result of deletions ('ok' or 'error', with error message).
13795: 3. reference to hash of any new or updated access controls.
13796: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13797: key = integer (inbound ID)
1.1172.2.13 raeburn 13798: value = uniqueID
13799:
13800: =item *
13801:
13802: get_timebased_id():
13803:
13804: Attempts to get a unique timestamp-based suffix for use with items added to a
13805: course via the Course Editor (e.g., folders, composite pages,
13806: group bulletin boards).
13807:
13808: Args: (first three required; six others optional)
13809:
13810: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13811: docssequence, or name of group
13812:
13813: 2. keyid (alphanumeric): name of temporary locking key in hash,
13814: e.g., num, boardids
13815:
13816: 3. namespace: name of gdbm file used to store suffixes already assigned;
13817: file will be named nohist_namespace.db
13818:
13819: 4. cdom: domain of course; default is current course domain from %env
13820:
13821: 5. cnum: course number; default is current course number from %env
13822:
13823: 6. idtype: set to concat if an additional digit is to be appended to the
13824: unix timestamp to form the suffix, if the plain timestamp is already
13825: in use. Default is to not do this, but simply increment the unix
13826: timestamp by 1 until a unique key is obtained.
13827:
13828: 7. who: holder of locking key; defaults to user:domain for user.
13829:
13830: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13831: retrying); default is 3.
13832:
13833: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13834:
13835: Returns:
13836:
13837: 1. suffix obtained (numeric)
13838:
13839: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13840:
13841: 3. error: contains (localized) error message if an error occurred.
13842:
1.747 albertel 13843:
1.608 albertel 13844: =back
13845:
1.243 albertel 13846: =head2 HTTP Helper Routines
13847:
13848: =over 4
13849:
1.191 harris41 13850: =item *
13851:
13852: escape() : unpack non-word characters into CGI-compatible hex codes
13853:
13854: =item *
13855:
13856: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13857:
1.243 albertel 13858: =back
13859:
13860: =head1 PRIVATE SUBROUTINES
13861:
13862: =head2 Underlying communication routines (Shouldn't call)
13863:
13864: =over 4
13865:
13866: =item *
13867:
13868: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13869:
13870: =item *
13871:
13872: reply() : uses subreply to send a message to remote machine, logs all failures
13873:
13874: =item *
13875:
13876: critical() : passes a critical message to another server; if cannot
13877: get through then place message in connection buffer directory and
13878: returns con_delayed, if incapable of saving message, returns
13879: con_failed
13880:
13881: =item *
13882:
13883: reconlonc() : tries to reconnect lonc client processes.
13884:
13885: =back
13886:
13887: =head2 Resource Access Logging
13888:
13889: =over 4
13890:
13891: =item *
13892:
13893: flushcourselogs() : flush (save) buffer logs and access logs
13894:
13895: =item *
13896:
13897: courselog($what) : save message for course in hash
13898:
13899: =item *
13900:
13901: courseacclog($what) : save message for course using &courselog(). Perform
13902: special processing for specific resource types (problems, exams, quizzes, etc).
13903:
1.191 harris41 13904: =item *
13905:
13906: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13907: as a PerlChildExitHandler
1.243 albertel 13908:
13909: =back
13910:
13911: =head2 Other
13912:
13913: =over 4
13914:
13915: =item *
13916:
13917: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13918:
13919: =back
13920:
13921: =cut
1.877 foxr 13922:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>