Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.76
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.76! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.75 2016/08/06 01:25:03 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: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
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') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 847: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
848: $try_server));
1.1123 raeburn 849: ($spare_server, $lowest_load) =
850: &compare_server_load($try_server, $spare_server, $lowest_load);
851: }
1.1083 raeburn 852: }
1.784 albertel 853:
1.1123 raeburn 854: my $found_server = ($spare_server ne '' && $lowest_load < 100);
855:
856: if (!$found_server) {
857: if (ref($spareshash->{'default'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,
860: $remotesessions,$try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
1.1172.2.41 raeburn 884: my ($try_server, $spare_server, $lowest_load, $required) = @_;
885:
886: if ($required) {
887: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
888: my $remoterev = &get_server_loncaparev(undef,$try_server);
889: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
890: if (($major eq '' && $minor eq '') ||
891: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
892: return ($spare_server,$lowest_load);
893: }
894: }
1.784 albertel 895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1172.2.47 raeburn 955: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1172.2.47 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
960: if ($skiploadbal) {
961: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
962: unless (defined($cached)) {
963: my $cachetime = 60*60*24;
964: my %domconfig =
965: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
966: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
967: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
968: $cachetime);
969: }
970: }
971: }
1.1076 raeburn 972: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 973: my $loginvia;
1.1172.2.47 raeburn 974: if ($skiploadbal) {
975: if (ref($balancers) eq 'HASH') {
976: next if (exists($balancers->{$lonhost}));
977: }
978: }
1.1115 raeburn 979: if ($checkloginvia) {
980: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 981: if ($loginvia) {
982: my ($server,$path) = split(/:/,$loginvia);
983: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 984: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 985: if ($login_host eq $server) {
986: $portal_path = $path;
1.1151 raeburn 987: $isredirect = 1;
1.1116 raeburn 988: }
989: } else {
990: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 992: if ($login_host eq $lonhost) {
993: $portal_path = '';
1.1151 raeburn 994: $isredirect = '';
1.1116 raeburn 995: }
996: }
997: } else {
1.1076 raeburn 998: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 999: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1000: }
1001: }
1002: if ($login_host ne '') {
1.1116 raeburn 1003: $hostname = &hostname($login_host);
1.1076 raeburn 1004: }
1.1151 raeburn 1005: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1006: }
1007:
1.202 matthew 1008: # --------------------------------------------- Try to change a user's password
1009:
1010: sub changepass {
1.799 raeburn 1011: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1012: $currentpass = &escape($currentpass);
1013: $newpass = &escape($newpass);
1.1030 raeburn 1014: my $lonhost = $perlvar{'lonHostID'};
1015: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1016: $server);
1017: if (! $answer) {
1018: &logthis("No reply on password change request to $server ".
1019: "by $uname in domain $udom.");
1020: } elsif ($answer =~ "^ok") {
1021: &logthis("$uname in $udom successfully changed their password ".
1022: "on $server.");
1023: } elsif ($answer =~ "^pwchange_failure") {
1024: &logthis("$uname in $udom was unable to change their password ".
1025: "on $server. The action was blocked by either lcpasswd ".
1026: "or pwchange");
1027: } elsif ($answer =~ "^non_authorized") {
1028: &logthis("$uname in $udom did not get their password correct when ".
1029: "attempting to change it on $server.");
1030: } elsif ($answer =~ "^auth_mode_error") {
1031: &logthis("$uname in $udom attempted to change their password despite ".
1032: "not being locally or internally authenticated on $server.");
1033: } elsif ($answer =~ "^unknown_user") {
1034: &logthis("$uname in $udom attempted to change their password ".
1035: "on $server but were unable to because $server is not ".
1036: "their home server.");
1037: } elsif ($answer =~ "^refused") {
1038: &logthis("$server refused to change $uname in $udom password because ".
1039: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1040: } elsif ($answer =~ "invalid_client") {
1041: &logthis("$server refused to change $uname in $udom password because ".
1042: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1043: }
1044: return $answer;
1.1 albertel 1045: }
1046:
1.169 harris41 1047: # ----------------------- Try to determine user's current authentication scheme
1048:
1049: sub queryauthenticate {
1050: my ($uname,$udom)=@_;
1.456 albertel 1051: my $uhome=&homeserver($uname,$udom);
1052: if (!$uhome) {
1053: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1054: return 'no_host';
1055: }
1056: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1057: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1059: }
1.456 albertel 1060: return $answer;
1.169 harris41 1061: }
1062:
1.1 albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1064:
1.1 albertel 1065: sub authenticate {
1.1073 raeburn 1066: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1067: $upass=&escape($upass);
1068: $uname= &LONCAPA::clean_username($uname);
1.836 www 1069: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1070: my $newhome;
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: # Maybe the machine was offline and only re-appeared again recently?
1073: &reconlonc();
1074: # One more
1.952 raeburn 1075: $uhome=&homeserver($uname,$udom,1);
1076: if (($uhome eq 'no_host') && $checkdefauth) {
1077: if (defined(&domain($udom,'primary'))) {
1078: $newhome=&domain($udom,'primary');
1079: }
1080: if ($newhome ne '') {
1081: $uhome = $newhome;
1082: }
1083: }
1.836 www 1084: if ((!$uhome) || ($uhome eq 'no_host')) {
1085: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1086: return 'no_host';
1087: }
1.1 albertel 1088: }
1.1073 raeburn 1089: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1090: if ($answer eq 'authorized') {
1.952 raeburn 1091: if ($newhome) {
1092: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1093: return 'no_account_on_host';
1094: } else {
1095: &logthis("User $uname at $udom authorized by $uhome");
1096: return $uhome;
1097: }
1.471 albertel 1098: }
1099: if ($answer eq 'non_authorized') {
1100: &logthis("User $uname at $udom rejected by $uhome");
1101: return 'no_host';
1.9 www 1102: }
1.471 albertel 1103: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1104: return 'no_host';
1105: }
1106:
1.1073 raeburn 1107: sub can_host_session {
1.1074 raeburn 1108: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1109: my $canhost = 1;
1.1074 raeburn 1110: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1111: if (ref($remotesessions) eq 'HASH') {
1112: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1113: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1114: $canhost = 0;
1115: } else {
1116: $canhost = 1;
1117: }
1118: }
1119: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1120: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1121: $canhost = 1;
1122: } else {
1123: $canhost = 0;
1124: }
1125: }
1126: if ($canhost) {
1127: if ($remotesessions->{'version'} ne '') {
1128: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1129: if ($reqmajor ne '' && $reqminor ne '') {
1130: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1131: my $major = $1;
1132: my $minor = $2;
1133: if (($major < $reqmajor ) ||
1134: (($major == $reqmajor) && ($minor < $reqminor))) {
1135: $canhost = 0;
1136: }
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: }
1144: if ($canhost) {
1145: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1146: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1147: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1148: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1151: $canhost = 0;
1152: } else {
1153: $canhost = 1;
1154: }
1155: }
1156: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1157: if (($uint_dom ne '') &&
1158: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1159: $canhost = 1;
1160: } else {
1161: $canhost = 0;
1162: }
1163: }
1164: }
1165: }
1166: return $canhost;
1167: }
1168:
1.1083 raeburn 1169: sub spare_can_host {
1170: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1171: my $canhost=1;
1.1172.2.62 raeburn 1172: my $try_server_hostname = &hostname($try_server);
1173: my $serverhomeID = &get_server_homeID($try_server_hostname);
1174: my $serverhomedom = &host_domain($serverhomeID);
1175: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1176: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1177: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1178: $canhost = 0;
1179: }
1180: }
1181: if (($canhost) && ($uint_dom)) {
1182: my @intdoms;
1183: my $internet_names = &get_internet_names($try_server);
1184: if (ref($internet_names) eq 'ARRAY') {
1185: @intdoms = @{$internet_names};
1186: }
1187: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1188: my $remoterev = &get_server_loncaparev(undef,$try_server);
1189: $canhost = &can_host_session($udom,$try_server,$remoterev,
1190: $remotesessions,
1191: $defdomdefaults{'hostedsessions'});
1192: }
1.1083 raeburn 1193: }
1194: return $canhost;
1195: }
1196:
1.1123 raeburn 1197: sub this_host_spares {
1198: my ($dom) = @_;
1.1126 raeburn 1199: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1200: my @hosts = ¤t_machine_ids();
1201: foreach my $lonhost (@hosts) {
1202: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1203: $dom_in_use = $dom;
1204: $lonhost_in_use = $lonhost;
1.1123 raeburn 1205: last;
1206: }
1207: }
1.1126 raeburn 1208: if ($dom_in_use ne '') {
1209: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1210: }
1211: if (ref($result) ne 'HASH') {
1212: $lonhost_in_use = $perlvar{'lonHostID'};
1213: $dom_in_use = &host_domain($lonhost_in_use);
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: if (ref($result) ne 'HASH') {
1216: $result = \%spareid;
1217: }
1218: }
1219: return $result;
1220: }
1221:
1222: sub spares_for_offload {
1223: my ($dom_in_use,$lonhost_in_use) = @_;
1224: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1225: if (defined($cached)) {
1226: return $result;
1227: } else {
1.1126 raeburn 1228: my $cachetime = 60*60*24;
1229: my %domconfig =
1230: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1231: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1232: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1234: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1235: }
1236: }
1237: }
1238: }
1.1126 raeburn 1239: return;
1.1123 raeburn 1240: }
1241:
1.1129 raeburn 1242: sub get_lonbalancer_config {
1243: my ($servers) = @_;
1244: my ($currbalancer,$currtargets);
1245: if (ref($servers) eq 'HASH') {
1246: foreach my $server (keys(%{$servers})) {
1247: my %what = (
1248: spareid => 1,
1249: perlvar => 1,
1250: );
1251: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1252: if ($result eq 'ok') {
1253: if (ref($returnhash) eq 'HASH') {
1254: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1255: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1256: $currbalancer = $server;
1257: $currtargets = {};
1258: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1259: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1260: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1261: }
1262: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1263: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1264: }
1265: }
1266: last;
1267: }
1268: }
1269: }
1270: }
1271: }
1272: }
1273: return ($currbalancer,$currtargets);
1274: }
1275:
1276: sub check_loadbalancing {
1277: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1278: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1279: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1280: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1281: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1282: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1283: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1284: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1285: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1286: my $domneedscache;
1.1129 raeburn 1287: my $cachetime = 60*60*24;
1288:
1289: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1290: $dom_in_use = $udom;
1291: $homeintdom = 1;
1292: } else {
1293: $dom_in_use = $serverhomedom;
1294: }
1295: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1296: unless (defined($cached)) {
1297: my %domconfig =
1298: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1299: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1300: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1301: } else {
1302: $domneedscache = $dom_in_use;
1.1129 raeburn 1303: }
1304: }
1305: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1306: ($is_balancer,$currtargets,$currrules) =
1307: &check_balancer_result($result,@hosts);
1.1129 raeburn 1308: if ($is_balancer) {
1309: if (ref($currrules) eq 'HASH') {
1310: if ($homeintdom) {
1311: if ($uname ne '') {
1312: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1313: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1314: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1315: $rule_in_effect = $currrules->{'_LC_author'};
1316: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1317: $rule_in_effect = $currrules->{'_LC_adv'}
1318: }
1319: }
1320: if ($rule_in_effect eq '') {
1321: my %userenv = &userenvironment($udom,$uname,'inststatus');
1322: if ($userenv{'inststatus'} ne '') {
1323: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1324: my ($othertitle,$usertypes,$types) =
1325: &Apache::loncommon::sorted_inst_types($udom);
1326: if (ref($types) eq 'ARRAY') {
1327: foreach my $type (@{$types}) {
1328: if (grep(/^\Q$type\E$/,@statuses)) {
1329: if (exists($currrules->{$type})) {
1330: $rule_in_effect = $currrules->{$type};
1331: }
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: }
1341: } else {
1342: if (exists($currrules->{'default'})) {
1343: $rule_in_effect = $currrules->{'default'};
1344: }
1345: }
1346: } else {
1347: if ($currrules->{'_LC_external'} ne '') {
1348: $rule_in_effect = $currrules->{'_LC_external'};
1349: }
1350: }
1351: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1352: $uname,$udom);
1353: }
1354: }
1355: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1356: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1357: unless (defined($cached)) {
1358: my %domconfig =
1359: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1360: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1361: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1362: } else {
1363: $domneedscache = $serverhomedom;
1.1129 raeburn 1364: }
1365: }
1366: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1367: ($is_balancer,$currtargets,$currrules) =
1368: &check_balancer_result($result,@hosts);
1369: if ($is_balancer) {
1.1129 raeburn 1370: if (ref($currrules) eq 'HASH') {
1371: if ($currrules->{'_LC_internetdom'} ne '') {
1372: $rule_in_effect = $currrules->{'_LC_internetdom'};
1373: }
1374: }
1375: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1376: $uname,$udom);
1377: }
1378: } else {
1379: if ($perlvar{'lonBalancer'} eq 'yes') {
1380: $is_balancer = 1;
1381: $offloadto = &this_host_spares($dom_in_use);
1382: }
1.1172.2.75 raeburn 1383: unless (defined($cached)) {
1384: $domneedscache = $serverhomedom;
1385: }
1.1129 raeburn 1386: }
1387: } else {
1388: if ($perlvar{'lonBalancer'} eq 'yes') {
1389: $is_balancer = 1;
1390: $offloadto = &this_host_spares($dom_in_use);
1391: }
1.1172.2.75 raeburn 1392: unless (defined($cached)) {
1393: $domneedscache = $serverhomedom;
1394: }
1395: }
1396: if ($domneedscache) {
1397: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1398: }
1.1172.2.5 raeburn 1399: if ($is_balancer) {
1400: my $lowest_load = 30000;
1401: if (ref($offloadto) eq 'HASH') {
1402: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1403: foreach my $try_server (@{$offloadto->{'primary'}}) {
1404: ($otherserver,$lowest_load) =
1405: &compare_server_load($try_server,$otherserver,$lowest_load);
1406: }
1.1129 raeburn 1407: }
1.1172.2.5 raeburn 1408: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1409:
1.1172.2.5 raeburn 1410: if (!$found_server) {
1411: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1412: foreach my $try_server (@{$offloadto->{'default'}}) {
1413: ($otherserver,$lowest_load) =
1414: &compare_server_load($try_server,$otherserver,$lowest_load);
1415: }
1416: }
1417: }
1418: } elsif (ref($offloadto) eq 'ARRAY') {
1419: if (@{$offloadto} == 1) {
1420: $otherserver = $offloadto->[0];
1421: } elsif (@{$offloadto} > 1) {
1422: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1423: ($otherserver,$lowest_load) =
1424: &compare_server_load($try_server,$otherserver,$lowest_load);
1425: }
1426: }
1427: }
1.1172.2.5 raeburn 1428: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1429: $is_balancer = 0;
1430: if ($uname ne '' && $udom ne '') {
1431: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1432:
1433: &appenv({'user.loadbalexempt' => $lonhost,
1434: 'user.loadbalcheck.time' => time});
1435: }
1.1129 raeburn 1436: }
1437: }
1438: }
1439: return ($is_balancer,$otherserver);
1440: }
1441:
1.1172.2.12 raeburn 1442: sub check_balancer_result {
1443: my ($result,@hosts) = @_;
1444: my ($is_balancer,$currtargets,$currrules);
1445: if (ref($result) eq 'HASH') {
1446: if ($result->{'lonhost'} ne '') {
1447: my $currbalancer = $result->{'lonhost'};
1448: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1449: $is_balancer = 1;
1450: $currtargets = $result->{'targets'};
1451: $currrules = $result->{'rules'};
1452: }
1453: } else {
1454: foreach my $key (keys(%{$result})) {
1455: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1456: (ref($result->{$key}) eq 'HASH')) {
1457: $is_balancer = 1;
1458: $currrules = $result->{$key}{'rules'};
1459: $currtargets = $result->{$key}{'targets'};
1460: last;
1461: }
1462: }
1463: }
1464: }
1465: return ($is_balancer,$currtargets,$currrules);
1466: }
1467:
1.1129 raeburn 1468: sub get_loadbalancer_targets {
1469: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1470: my $offloadto;
1.1172.2.4 raeburn 1471: if ($rule_in_effect eq 'none') {
1472: return [$perlvar{'lonHostID'}];
1473: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1474: $offloadto = $currtargets;
1475: } else {
1476: if ($rule_in_effect eq 'homeserver') {
1477: my $homeserver = &homeserver($uname,$udom);
1478: if ($homeserver ne 'no_host') {
1479: $offloadto = [$homeserver];
1480: }
1481: } elsif ($rule_in_effect eq 'externalbalancer') {
1482: my %domconfig =
1483: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1484: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1485: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1486: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1487: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1488: }
1489: }
1490: } else {
1.1172.2.7 raeburn 1491: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1492: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1493: if (&hostname($remotebalancer) ne '') {
1494: $offloadto = [$remotebalancer];
1495: }
1496: }
1497: } elsif (&hostname($rule_in_effect) ne '') {
1498: $offloadto = [$rule_in_effect];
1499: }
1500: }
1501: return $offloadto;
1502: }
1503:
1.1127 raeburn 1504: sub internet_dom_servers {
1505: my ($dom) = @_;
1506: my (%uniqservers,%servers);
1507: my $primaryserver = &hostname(&domain($dom,'primary'));
1508: my @machinedoms = &machine_domains($primaryserver);
1509: foreach my $mdom (@machinedoms) {
1510: my %currservers = %servers;
1511: my %server = &get_servers($mdom);
1512: %servers = (%currservers,%server);
1513: }
1514: my %by_hostname;
1515: foreach my $id (keys(%servers)) {
1516: push(@{$by_hostname{$servers{$id}}},$id);
1517: }
1518: foreach my $hostname (sort(keys(%by_hostname))) {
1519: if (@{$by_hostname{$hostname}} > 1) {
1520: my $match = 0;
1521: foreach my $id (@{$by_hostname{$hostname}}) {
1522: if (&host_domain($id) eq $dom) {
1523: $uniqservers{$id} = $hostname;
1524: $match = 1;
1525: }
1526: }
1527: unless ($match) {
1528: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1529: }
1530: } else {
1531: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1532: }
1533: }
1534: return %uniqservers;
1535: }
1536:
1.1 albertel 1537: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1538:
1.599 albertel 1539: my %homecache;
1.1 albertel 1540: sub homeserver {
1.230 stredwic 1541: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1542: my $index="$uname:$udom";
1.426 albertel 1543:
1.599 albertel 1544: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1545:
1546: my %servers = &get_servers($udom,'library');
1547: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1548: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1549: exists($badServerCache{$tryserver}));
1.841 albertel 1550:
1551: my $answer=reply("home:$udom:$uname",$tryserver);
1552: if ($answer eq 'found') {
1553: delete($badServerCache{$tryserver});
1554: return $homecache{$index}=$tryserver;
1555: } elsif ($answer eq 'no_host') {
1556: $badServerCache{$tryserver}=1;
1557: }
1.1 albertel 1558: }
1559: return 'no_host';
1.70 www 1560: }
1561:
1562: # ------------------------------------- Find the usernames behind a list of IDs
1563:
1564: sub idget {
1565: my ($udom,@ids)=@_;
1566: my %returnhash=();
1567:
1.841 albertel 1568: my %servers = &get_servers($udom,'library');
1569: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1570: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1571: $idlist=~tr/A-Z/a-z/;
1572: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1573: my @answer=();
1574: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1575: @answer=split(/\&/,$reply);
1576: } ;
1577: my $i;
1578: for ($i=0;$i<=$#ids;$i++) {
1579: if ($answer[$i]) {
1.1172.2.73 raeburn 1580: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1581: }
1582: }
1583: }
1.70 www 1584: return %returnhash;
1585: }
1586:
1587: # ------------------------------------- Find the IDs behind a list of usernames
1588:
1589: sub idrget {
1590: my ($udom,@unames)=@_;
1591: my %returnhash=();
1.800 albertel 1592: foreach my $uname (@unames) {
1593: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1594: }
1.70 www 1595: return %returnhash;
1596: }
1597:
1598: # ------------------------------- Store away a list of names and associated IDs
1599:
1600: sub idput {
1601: my ($udom,%ids)=@_;
1602: my %servers=();
1.800 albertel 1603: foreach my $uname (keys(%ids)) {
1604: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1605: my $uhom=&homeserver($uname,$udom);
1.70 www 1606: if ($uhom ne 'no_host') {
1.800 albertel 1607: my $id=&escape($ids{$uname});
1.70 www 1608: $id=~tr/A-Z/a-z/;
1.800 albertel 1609: my $esc_unam=&escape($uname);
1.70 www 1610: if ($servers{$uhom}) {
1.800 albertel 1611: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1612: } else {
1.800 albertel 1613: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1614: }
1615: }
1.191 harris41 1616: }
1.800 albertel 1617: foreach my $server (keys(%servers)) {
1618: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1619: }
1.344 www 1620: }
1621:
1.1172.2.30 raeburn 1622: # ---------------------------------------- Delete unwanted IDs from ids.db file
1623:
1624: sub iddel {
1625: my ($udom,$idshashref,$uhome)=@_;
1626: my %result=();
1627: unless (ref($idshashref) eq 'HASH') {
1628: return %result;
1629: }
1630: my %servers=();
1631: while (my ($id,$uname) = each(%{$idshashref})) {
1632: my $uhom;
1633: if ($uhome) {
1634: $uhom = $uhome;
1635: } else {
1636: $uhom=&homeserver($uname,$udom);
1637: }
1638: if ($uhom ne 'no_host') {
1639: if ($servers{$uhom}) {
1640: $servers{$uhom}.='&'.&escape($id);
1641: } else {
1642: $servers{$uhom}=&escape($id);
1643: }
1644: }
1645: }
1646: foreach my $server (keys(%servers)) {
1647: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1648: }
1649: return %result;
1650: }
1651:
1.1023 raeburn 1652: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1653: sub dump_dom {
1.1165 droeschl 1654: my ($namespace, $udom, $regexp) = @_;
1655:
1656: $udom ||= $env{'user.domain'};
1657:
1658: return () unless $udom;
1659:
1660: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1661: }
1662:
1.1023 raeburn 1663: # ------------------------------------------ get items from domain db files
1.806 raeburn 1664:
1665: sub get_dom {
1.860 raeburn 1666: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1667: return if ($udom eq 'public');
1.806 raeburn 1668: my $items='';
1669: foreach my $item (@$storearr) {
1670: $items.=&escape($item).'&';
1671: }
1672: $items=~s/\&$//;
1.860 raeburn 1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1675: return if ($udom eq 'public');
1.860 raeburn 1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: } else {
1.874 albertel 1679: undef($uhome);
1.860 raeburn 1680: }
1681: } else {
1682: if (!$uhome) {
1683: if (defined(&domain($udom,'primary'))) {
1684: $uhome=&domain($udom,'primary');
1685: }
1686: }
1687: }
1688: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1689: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1690: my %returnhash;
1.875 albertel 1691: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1692: return %returnhash;
1693: }
1.806 raeburn 1694: my @pairs=split(/\&/,$rep);
1695: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1696: return @pairs;
1697: }
1698: my $i=0;
1699: foreach my $item (@$storearr) {
1700: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1701: $i++;
1702: }
1703: return %returnhash;
1704: } else {
1.880 banghart 1705: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1706: }
1707: }
1708:
1709: # -------------------------------------------- put items in domain db files
1710:
1711: sub put_dom {
1.860 raeburn 1712: my ($namespace,$storehash,$udom,$uhome)=@_;
1713: if (!$udom) {
1714: $udom=$env{'user.domain'};
1715: if (defined(&domain($udom,'primary'))) {
1716: $uhome=&domain($udom,'primary');
1717: } else {
1.874 albertel 1718: undef($uhome);
1.860 raeburn 1719: }
1720: } else {
1721: if (!$uhome) {
1722: if (defined(&domain($udom,'primary'))) {
1723: $uhome=&domain($udom,'primary');
1724: }
1725: }
1726: }
1727: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1728: my $items='';
1729: foreach my $item (keys(%$storehash)) {
1730: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1731: }
1732: $items=~s/\&$//;
1733: return &reply("putdom:$udom:$namespace:$items",$uhome);
1734: } else {
1.860 raeburn 1735: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1736: }
1737: }
1738:
1.1023 raeburn 1739: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1740: sub newput_dom {
1.1023 raeburn 1741: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1742: my $result;
1743: if (!$udom) {
1744: $udom=$env{'user.domain'};
1745: }
1.1023 raeburn 1746: if ($udom) {
1747: my $uname = &get_domainconfiguser($udom);
1748: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1749: }
1750: return $result;
1751: }
1752:
1.1023 raeburn 1753: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1754: sub del_dom {
1.1023 raeburn 1755: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1756: if (ref($storearr) eq 'ARRAY') {
1757: if (!$udom) {
1758: $udom=$env{'user.domain'};
1759: }
1.1023 raeburn 1760: if ($udom) {
1761: my $uname = &get_domainconfiguser($udom);
1762: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1763: }
1764: }
1765: }
1766:
1.1023 raeburn 1767: # ----------------------------------construct domainconfig user for a domain
1768: sub get_domainconfiguser {
1769: my ($udom) = @_;
1770: return $udom.'-domainconfig';
1771: }
1772:
1.837 raeburn 1773: sub retrieve_inst_usertypes {
1774: my ($udom) = @_;
1775: my (%returnhash,@order);
1.989 raeburn 1776: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1777: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1778: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1779: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1780: } else {
1781: if (defined(&domain($udom,'primary'))) {
1782: my $uhome=&domain($udom,'primary');
1783: my $rep=&reply("inst_usertypes:$udom",$uhome);
1784: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1785: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1786: return (\%returnhash,\@order);
1787: }
1788: my ($hashitems,$orderitems) = split(/:/,$rep);
1789: my @pairs=split(/\&/,$hashitems);
1790: foreach my $item (@pairs) {
1791: my ($key,$value)=split(/=/,$item,2);
1792: $key = &unescape($key);
1793: next if ($key =~ /^error: 2 /);
1794: $returnhash{$key}=&thaw_unescape($value);
1795: }
1796: my @esc_order = split(/\&/,$orderitems);
1797: foreach my $item (@esc_order) {
1798: push(@order,&unescape($item));
1799: }
1800: } else {
1.1172.2.44 raeburn 1801: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1802: }
1.1172.2.44 raeburn 1803: return (\%returnhash,\@order);
1.837 raeburn 1804: }
1805: }
1806:
1.868 raeburn 1807: sub is_domainimage {
1808: my ($url) = @_;
1.1172.2.74 raeburn 1809: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1810: if (&domain($1) ne '') {
1811: return '1';
1812: }
1813: }
1814: return;
1815: }
1816:
1.899 raeburn 1817: sub inst_directory_query {
1818: my ($srch) = @_;
1819: my $udom = $srch->{'srchdomain'};
1820: my %results;
1821: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1822: my $outcome;
1.899 raeburn 1823: if ($homeserver ne '') {
1.904 albertel 1824: my $queryid=&reply("querysend:instdirsearch:".
1825: &escape($srch->{'srchby'}).':'.
1826: &escape($srch->{'srchterm'}).':'.
1827: &escape($srch->{'srchtype'}),$homeserver);
1828: my $host=&hostname($homeserver);
1829: if ($queryid !~/^\Q$host\E\_/) {
1830: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1831: return;
1832: }
1833: my $response = &get_query_reply($queryid);
1834: my $maxtries = 5;
1835: my $tries = 1;
1836: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1837: $response = &get_query_reply($queryid);
1838: $tries ++;
1839: }
1840:
1841: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1842: if ($response eq 'unavailable') {
1843: $outcome = $response;
1844: } else {
1845: $outcome = 'ok';
1846: my @matches = split(/\n/,$response);
1847: foreach my $match (@matches) {
1848: my ($key,$value) = split(/=/,$match);
1849: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1850: }
1.899 raeburn 1851: }
1852: }
1853: }
1.909 raeburn 1854: return ($outcome,%results);
1.899 raeburn 1855: }
1856:
1857: sub usersearch {
1858: my ($srch) = @_;
1859: my $dom = $srch->{'srchdomain'};
1860: my %results;
1861: my %libserv = &all_library();
1862: my $query = 'usersearch';
1863: foreach my $tryserver (keys(%libserv)) {
1864: if (&host_domain($tryserver) eq $dom) {
1865: my $host=&hostname($tryserver);
1866: my $queryid=
1.911 raeburn 1867: &reply("querysend:".&escape($query).':'.
1868: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1869: &escape($srch->{'srchtype'}).':'.
1870: &escape($srch->{'srchterm'}),$tryserver);
1871: if ($queryid !~/^\Q$host\E\_/) {
1872: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1873: next;
1.899 raeburn 1874: }
1875: my $reply = &get_query_reply($queryid);
1876: my $maxtries = 1;
1877: my $tries = 1;
1878: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1879: $reply = &get_query_reply($queryid);
1880: $tries ++;
1881: }
1882: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1883: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1884: } else {
1.911 raeburn 1885: my @matches;
1886: if ($reply =~ /\n/) {
1887: @matches = split(/\n/,$reply);
1888: } else {
1889: @matches = split(/\&/,$reply);
1890: }
1.899 raeburn 1891: foreach my $match (@matches) {
1892: my ($uname,$udom,%userhash);
1.911 raeburn 1893: foreach my $entry (split(/:/,$match)) {
1894: my ($key,$value) =
1895: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1896: $userhash{$key} = $value;
1897: if ($key eq 'username') {
1898: $uname = $value;
1899: } elsif ($key eq 'domain') {
1900: $udom = $value;
1.911 raeburn 1901: }
1.899 raeburn 1902: }
1903: $results{$uname.':'.$udom} = \%userhash;
1904: }
1905: }
1906: }
1907: }
1908: return %results;
1909: }
1910:
1.912 raeburn 1911: sub get_instuser {
1912: my ($udom,$uname,$id) = @_;
1913: my $homeserver = &domain($udom,'primary');
1914: my ($outcome,%results);
1915: if ($homeserver ne '') {
1916: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1917: &escape($id).':'.&escape($udom),$homeserver);
1918: my $host=&hostname($homeserver);
1919: if ($queryid !~/^\Q$host\E\_/) {
1920: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1921: return;
1922: }
1923: my $response = &get_query_reply($queryid);
1924: my $maxtries = 5;
1925: my $tries = 1;
1926: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1927: $response = &get_query_reply($queryid);
1928: $tries ++;
1929: }
1930: if (!&error($response) && $response ne 'refused') {
1931: if ($response eq 'unavailable') {
1932: $outcome = $response;
1933: } else {
1934: $outcome = 'ok';
1935: my @matches = split(/\n/,$response);
1936: foreach my $match (@matches) {
1937: my ($key,$value) = split(/=/,$match);
1938: $results{&unescape($key)} = &thaw_unescape($value);
1939: }
1940: }
1941: }
1942: }
1943: my %userinfo;
1944: if (ref($results{$uname}) eq 'HASH') {
1945: %userinfo = %{$results{$uname}};
1946: }
1947: return ($outcome,%userinfo);
1948: }
1949:
1.1172.2.69 raeburn 1950: sub get_multiple_instusers {
1951: my ($udom,$users,$caller) = @_;
1952: my ($outcome,$results);
1953: if (ref($users) eq 'HASH') {
1954: my $count = keys(%{$users});
1955: my $requested = &freeze_escape($users);
1956: my $homeserver = &domain($udom,'primary');
1957: if ($homeserver ne '') {
1958: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1959: my $host=&hostname($homeserver);
1960: if ($queryid !~/^\Q$host\E\_/) {
1961: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1962: ' for host: '.$homeserver.'in domain '.$udom);
1963: return ($outcome,$results);
1964: }
1965: my $response = &get_query_reply($queryid);
1966: my $maxtries = 5;
1967: if ($count > 100) {
1968: $maxtries = 1+int($count/20);
1969: }
1970: my $tries = 1;
1971: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1972: $response = &get_query_reply($queryid);
1973: $tries ++;
1974: }
1975: if ($response eq '') {
1976: $results = {};
1977: foreach my $key (keys(%{$users})) {
1978: my ($uname,$id);
1979: if ($caller eq 'id') {
1980: $id = $key;
1981: } else {
1982: $uname = $key;
1983: }
1984: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1985: $outcome = $resp;
1986: if ($resp eq 'ok') {
1987: %{$results} = (%{$results}, %info);
1988: } else {
1989: last;
1990: }
1991: }
1992: } elsif(!&error($response) && ($response ne 'refused')) {
1993: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
1994: $outcome = $response;
1995: } else {
1996: ($outcome,my $userdata) = split(/=/,$response,2);
1997: if ($outcome eq 'ok') {
1998: $results = &thaw_unescape($userdata);
1999: }
2000: }
2001: }
2002: }
2003: }
2004: return ($outcome,$results);
2005: }
2006:
1.912 raeburn 2007: sub inst_rulecheck {
1.923 raeburn 2008: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2009: my %returnhash;
2010: if ($udom ne '') {
2011: if (ref($rules) eq 'ARRAY') {
2012: @{$rules} = map {&escape($_);} (@{$rules});
2013: my $rulestr = join(':',@{$rules});
2014: my $homeserver=&domain($udom,'primary');
2015: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2016: my $response;
2017: if ($item eq 'username') {
2018: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2019: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2020: $homeserver));
1.923 raeburn 2021: } elsif ($item eq 'id') {
2022: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2023: ':'.&escape($id).':'.$rulestr,
2024: $homeserver));
1.945 raeburn 2025: } elsif ($item eq 'selfcreate') {
2026: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2027: &escape($udom).':'.&escape($uname).
2028: ':'.$rulestr,$homeserver));
1.923 raeburn 2029: }
1.912 raeburn 2030: if ($response ne 'refused') {
2031: my @pairs=split(/\&/,$response);
2032: foreach my $item (@pairs) {
2033: my ($key,$value)=split(/=/,$item,2);
2034: $key = &unescape($key);
2035: next if ($key =~ /^error: 2 /);
2036: $returnhash{$key}=&thaw_unescape($value);
2037: }
2038: }
2039: }
2040: }
2041: }
2042: return %returnhash;
2043: }
2044:
2045: sub inst_userrules {
1.923 raeburn 2046: my ($udom,$check) = @_;
1.912 raeburn 2047: my (%ruleshash,@ruleorder);
2048: if ($udom ne '') {
2049: my $homeserver=&domain($udom,'primary');
2050: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2051: my $response;
2052: if ($check eq 'id') {
2053: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2054: $homeserver);
1.943 raeburn 2055: } elsif ($check eq 'email') {
2056: $response=&reply('instemailrules:'.&escape($udom),
2057: $homeserver);
1.923 raeburn 2058: } else {
2059: $response=&reply('instuserrules:'.&escape($udom),
2060: $homeserver);
2061: }
1.912 raeburn 2062: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2063: ($response ne 'unknown_cmd') &&
1.912 raeburn 2064: ($response ne 'no_such_host')) {
2065: my ($hashitems,$orderitems) = split(/:/,$response);
2066: my @pairs=split(/\&/,$hashitems);
2067: foreach my $item (@pairs) {
2068: my ($key,$value)=split(/=/,$item,2);
2069: $key = &unescape($key);
2070: next if ($key =~ /^error: 2 /);
2071: $ruleshash{$key}=&thaw_unescape($value);
2072: }
2073: my @esc_order = split(/\&/,$orderitems);
2074: foreach my $item (@esc_order) {
2075: push(@ruleorder,&unescape($item));
2076: }
2077: }
2078: }
2079: }
2080: return (\%ruleshash,\@ruleorder);
2081: }
2082:
1.976 raeburn 2083: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2084:
2085: sub get_domain_defaults {
1.1172.2.35 raeburn 2086: my ($domain,$ignore_cache) = @_;
2087: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2088: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2089: unless ($ignore_cache) {
2090: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2091: if (defined($cached)) {
2092: if (ref($result) eq 'HASH') {
2093: return %{$result};
2094: }
1.943 raeburn 2095: }
2096: }
2097: my %domdefaults;
2098: my %domconfig =
1.989 raeburn 2099: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2100: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2101: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2102: 'requestauthor','selfenrollment',
1.1172.2.76! raeburn 2103: 'coursecategories','autoenroll'],$domain);
1.1172.2.41 raeburn 2104: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2105: if (ref($domconfig{'defaults'}) eq 'HASH') {
2106: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2107: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2108: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2109: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2110: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2111: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2112: } else {
2113: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2114: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2115: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2116: }
1.976 raeburn 2117: if (ref($domconfig{'quotas'}) eq 'HASH') {
2118: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2119: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2120: } else {
2121: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2122: }
1.1172.2.6 raeburn 2123: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2124: foreach my $item (@usertools) {
2125: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2126: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2127: }
2128: }
1.1172.2.29 raeburn 2129: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2130: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2131: }
1.976 raeburn 2132: }
1.985 raeburn 2133: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2134: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2135: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2136: }
2137: }
1.1172.2.9 raeburn 2138: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2139: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2140: }
1.989 raeburn 2141: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2142: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2143: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2144: }
2145: }
1.1047 raeburn 2146: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2147: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2148: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2149: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2150: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2151: }
1.1172.2.41 raeburn 2152: foreach my $type (@coursetypes) {
2153: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2154: unless ($type eq 'community') {
2155: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2156: }
2157: }
2158: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2159: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2160: }
1.1172.2.60 raeburn 2161: if ($domdefaults{'postsubmit'} eq 'on') {
2162: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2163: $domdefaults{$type.'postsubtimeout'} =
2164: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2165: }
2166: }
1.1172.2.30 raeburn 2167: }
1.1172.2.67 raeburn 2168: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2169: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2170: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2171: if (@clonecodes) {
2172: $domdefaults{'canclone'} = join('+',@clonecodes);
2173: }
2174: }
2175: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2176: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2177: }
1.1047 raeburn 2178: }
1.1073 raeburn 2179: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2180: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2181: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2182: }
2183: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2184: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2185: }
1.1172.2.62 raeburn 2186: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2187: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2188: }
1.1073 raeburn 2189: }
1.1172.2.41 raeburn 2190: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2191: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2192: my @settings = ('types','registered','enroll_dates','access_dates','section',
2193: 'approval','limit');
2194: foreach my $type (@coursetypes) {
2195: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2196: my @mgrdc = ();
2197: foreach my $item (@settings) {
2198: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2199: push(@mgrdc,$item);
2200: }
2201: }
2202: if (@mgrdc) {
2203: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2204: }
2205: }
2206: }
2207: }
2208: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2209: foreach my $type (@coursetypes) {
2210: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2211: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2212: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2213: }
2214: }
2215: }
2216: }
2217: }
1.1172.2.46 raeburn 2218: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2219: $domdefaults{'catauth'} = 'std';
2220: $domdefaults{'catunauth'} = 'std';
2221: if ($domconfig{'coursecategories'}{'auth'}) {
2222: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2223: }
2224: if ($domconfig{'coursecategories'}{'unauth'}) {
2225: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2226: }
2227: }
1.1172.2.76! raeburn 2228: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
! 2229: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
! 2230: }
1.1172.2.23 raeburn 2231: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2232: return %domdefaults;
2233: }
2234:
1.344 www 2235: # --------------------------------------------------- Assign a key to a student
2236:
2237: sub assign_access_key {
1.364 www 2238: #
2239: # a valid key looks like uname:udom#comments
2240: # comments are being appended
2241: #
1.498 www 2242: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2243: $kdom=
1.620 albertel 2244: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2245: $knum=
1.620 albertel 2246: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2247: $cdom=
1.620 albertel 2248: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2249: $cnum=
1.620 albertel 2250: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2251: $udom=$env{'user.name'} unless (defined($udom));
2252: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2253: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2254: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2255: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2256: # assigned to this person
2257: # - this should not happen,
1.345 www 2258: # unless something went wrong
2259: # the first time around
2260: # ready to assign
1.364 www 2261: $logentry=$1.'; '.$logentry;
1.496 www 2262: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2263: $kdom,$knum) eq 'ok') {
1.345 www 2264: # key now belongs to user
1.346 www 2265: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2266: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2267: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2268: return 'ok';
2269: } else {
2270: return
2271: 'error: Count not permanently assign key, will need to be re-entered later.';
2272: }
2273: } else {
2274: return 'error: Could not assign key, try again later.';
2275: }
1.364 www 2276: } elsif (!$existing{$ckey}) {
1.345 www 2277: # the key does not exist
2278: return 'error: The key does not exist';
2279: } else {
2280: # the key is somebody else's
2281: return 'error: The key is already in use';
2282: }
1.344 www 2283: }
2284:
1.364 www 2285: # ------------------------------------------ put an additional comment on a key
2286:
2287: sub comment_access_key {
2288: #
2289: # a valid key looks like uname:udom#comments
2290: # comments are being appended
2291: #
2292: my ($ckey,$cdom,$cnum,$logentry)=@_;
2293: $cdom=
1.620 albertel 2294: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2295: $cnum=
1.620 albertel 2296: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2297: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2298: if ($existing{$ckey}) {
2299: $existing{$ckey}.='; '.$logentry;
2300: # ready to assign
1.367 www 2301: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2302: $cdom,$cnum) eq 'ok') {
2303: return 'ok';
2304: } else {
2305: return 'error: Count not store comment.';
2306: }
2307: } else {
2308: # the key does not exist
2309: return 'error: The key does not exist';
2310: }
2311: }
2312:
1.344 www 2313: # ------------------------------------------------------ Generate a set of keys
2314:
2315: sub generate_access_keys {
1.364 www 2316: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2317: $cdom=
1.620 albertel 2318: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2319: $cnum=
1.620 albertel 2320: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2321: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2322: unless (($cdom) && ($cnum)) { return 0; }
2323: if ($number>10000) { return 0; }
2324: sleep(2); # make sure don't get same seed twice
2325: srand(time()^($$+($$<<15))); # from "Programming Perl"
2326: my $total=0;
2327: for (my $i=1;$i<=$number;$i++) {
2328: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2329: sprintf("%lx",int(100000*rand)).'-'.
2330: sprintf("%lx",int(100000*rand));
2331: $newkey=~s/1/g/g; # folks mix up 1 and l
2332: $newkey=~s/0/h/g; # and also 0 and O
2333: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2334: if ($existing{$newkey}) {
2335: $i--;
2336: } else {
1.364 www 2337: if (&put('accesskeys',
2338: { $newkey => '# generated '.localtime().
1.620 albertel 2339: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2340: '; '.$logentry },
2341: $cdom,$cnum) eq 'ok') {
1.344 www 2342: $total++;
2343: }
2344: }
2345: }
1.620 albertel 2346: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2347: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2348: return $total;
2349: }
2350:
2351: # ------------------------------------------------------- Validate an accesskey
2352:
2353: sub validate_access_key {
2354: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2355: $cdom=
1.620 albertel 2356: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2357: $cnum=
1.620 albertel 2358: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2359: $udom=$env{'user.domain'} unless (defined($udom));
2360: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2361: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2362: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2363: }
2364:
2365: # ------------------------------------- Find the section of student in a course
1.652 albertel 2366: sub devalidate_getsection_cache {
2367: my ($udom,$unam,$courseid)=@_;
2368: my $hashid="$udom:$unam:$courseid";
2369: &devalidate_cache_new('getsection',$hashid);
2370: }
1.298 matthew 2371:
1.815 albertel 2372: sub courseid_to_courseurl {
2373: my ($courseid) = @_;
2374: #already url style courseid
2375: return $courseid if ($courseid =~ m{^/});
2376:
2377: if (exists($env{'course.'.$courseid.'.num'})) {
2378: my $cnum = $env{'course.'.$courseid.'.num'};
2379: my $cdom = $env{'course.'.$courseid.'.domain'};
2380: return "/$cdom/$cnum";
2381: }
2382:
2383: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2384: if (exists($courseinfo{'num'})) {
2385: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2386: }
2387:
2388: return undef;
2389: }
2390:
1.298 matthew 2391: sub getsection {
2392: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2393: my $cachetime=1800;
1.551 albertel 2394:
2395: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2396: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2397: if (defined($cached)) { return $result; }
2398:
1.298 matthew 2399: my %Pending;
2400: my %Expired;
2401: #
2402: # Each role can either have not started yet (pending), be active,
2403: # or have expired.
2404: #
2405: # If there is an active role, we are done.
2406: #
2407: # If there is more than one role which has not started yet,
2408: # choose the one which will start sooner
2409: # If there is one role which has not started yet, return it.
2410: #
2411: # If there is more than one expired role, choose the one which ended last.
2412: # If there is a role which has expired, return it.
2413: #
1.815 albertel 2414: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2415: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2416: foreach my $key (keys(%roleshash)) {
1.479 albertel 2417: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2418: my $section=$1;
2419: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2420: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2421: my $now=time;
1.548 albertel 2422: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2423: $Expired{$end}=$section;
2424: next;
2425: }
1.548 albertel 2426: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2427: $Pending{$start}=$section;
2428: next;
2429: }
1.599 albertel 2430: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2431: }
2432: #
2433: # Presumedly there will be few matching roles from the above
2434: # loop and the sorting time will be negligible.
2435: if (scalar(keys(%Pending))) {
2436: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2437: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2438: }
2439: if (scalar(keys(%Expired))) {
2440: my @sorted = sort {$a <=> $b} keys(%Expired);
2441: my $time = pop(@sorted);
1.599 albertel 2442: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2443: }
1.599 albertel 2444: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2445: }
1.70 www 2446:
1.599 albertel 2447: sub save_cache {
2448: &purge_remembered();
1.722 albertel 2449: #&Apache::loncommon::validate_page();
1.620 albertel 2450: undef(%env);
1.780 albertel 2451: undef($env_loaded);
1.599 albertel 2452: }
1.452 albertel 2453:
1.599 albertel 2454: my $to_remember=-1;
2455: my %remembered;
2456: my %accessed;
2457: my $kicks=0;
2458: my $hits=0;
1.849 albertel 2459: sub make_key {
2460: my ($name,$id) = @_;
1.872 albertel 2461: if (length($id) > 65
2462: && length(&escape($id)) > 200) {
2463: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2464: }
1.849 albertel 2465: return &escape($name.':'.$id);
2466: }
2467:
1.599 albertel 2468: sub devalidate_cache_new {
2469: my ($name,$id,$debug) = @_;
2470: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2471: $id=&make_key($name,$id);
1.599 albertel 2472: $memcache->delete($id);
2473: delete($remembered{$id});
2474: delete($accessed{$id});
2475: }
2476:
2477: sub is_cached_new {
2478: my ($name,$id,$debug) = @_;
1.849 albertel 2479: $id=&make_key($name,$id);
1.599 albertel 2480: if (exists($remembered{$id})) {
1.1133 foxr 2481: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2482: $accessed{$id}=[&gettimeofday()];
2483: $hits++;
2484: return ($remembered{$id},1);
2485: }
2486: my $value = $memcache->get($id);
2487: if (!(defined($value))) {
2488: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2489: return (undef,undef);
1.416 albertel 2490: }
1.599 albertel 2491: if ($value eq '__undef__') {
2492: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2493: $value=undef;
2494: }
2495: &make_room($id,$value,$debug);
2496: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2497: return ($value,1);
2498: }
2499:
2500: sub do_cache_new {
2501: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2502: $id=&make_key($name,$id);
1.599 albertel 2503: my $setvalue=$value;
2504: if (!defined($setvalue)) {
2505: $setvalue='__undef__';
2506: }
1.623 albertel 2507: if (!defined($time) ) {
2508: $time=600;
2509: }
1.599 albertel 2510: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2511: my $result = $memcache->set($id,$setvalue,$time);
2512: if (! $result) {
1.872 albertel 2513: &logthis("caching of id -> $id failed");
1.910 albertel 2514: $memcache->disconnect_all();
1.872 albertel 2515: }
1.600 albertel 2516: # need to make a copy of $value
1.919 albertel 2517: &make_room($id,$value,$debug);
1.599 albertel 2518: return $value;
2519: }
2520:
2521: sub make_room {
2522: my ($id,$value,$debug)=@_;
1.919 albertel 2523:
2524: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2525: : $value;
1.599 albertel 2526: if ($to_remember<0) { return; }
2527: $accessed{$id}=[&gettimeofday()];
2528: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2529: my $to_kick;
2530: my $max_time=0;
2531: foreach my $other (keys(%accessed)) {
2532: if (&tv_interval($accessed{$other}) > $max_time) {
2533: $to_kick=$other;
2534: $max_time=&tv_interval($accessed{$other});
2535: }
2536: }
2537: delete($remembered{$to_kick});
2538: delete($accessed{$to_kick});
2539: $kicks++;
2540: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2541: return;
2542: }
2543:
1.599 albertel 2544: sub purge_remembered {
1.604 albertel 2545: #&logthis("Tossing ".scalar(keys(%remembered)));
2546: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2547: undef(%remembered);
2548: undef(%accessed);
1.428 albertel 2549: }
1.70 www 2550: # ------------------------------------- Read an entry from a user's environment
2551:
2552: sub userenvironment {
2553: my ($udom,$unam,@what)=@_;
1.976 raeburn 2554: my $items;
2555: foreach my $item (@what) {
2556: $items.=&escape($item).'&';
2557: }
2558: $items=~s/\&$//;
1.70 www 2559: my %returnhash=();
1.1009 raeburn 2560: my $uhome = &homeserver($unam,$udom);
2561: unless ($uhome eq 'no_host') {
2562: my @answer=split(/\&/,
2563: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2564: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2565: return %returnhash;
2566: }
1.1009 raeburn 2567: my $i;
2568: for ($i=0;$i<=$#what;$i++) {
2569: $returnhash{$what[$i]}=&unescape($answer[$i]);
2570: }
1.70 www 2571: }
2572: return %returnhash;
1.1 albertel 2573: }
2574:
1.617 albertel 2575: # ---------------------------------------------------------- Get a studentphoto
2576: sub studentphoto {
2577: my ($udom,$unam,$ext) = @_;
2578: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2579: if (defined($env{'request.course.id'})) {
1.708 raeburn 2580: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2581: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2582: return(&retrievestudentphoto($udom,$unam,$ext));
2583: } else {
2584: my ($result,$perm_reqd)=
1.707 albertel 2585: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2586: if ($result eq 'ok') {
2587: if (!($perm_reqd eq 'yes')) {
2588: return(&retrievestudentphoto($udom,$unam,$ext));
2589: }
2590: }
2591: }
2592: }
2593: } else {
2594: my ($result,$perm_reqd) =
1.707 albertel 2595: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2596: if ($result eq 'ok') {
2597: if (!($perm_reqd eq 'yes')) {
2598: return(&retrievestudentphoto($udom,$unam,$ext));
2599: }
2600: }
2601: }
2602: return '/adm/lonKaputt/lonlogo_broken.gif';
2603: }
2604:
2605: sub retrievestudentphoto {
2606: my ($udom,$unam,$ext,$type) = @_;
2607: my $home=&Apache::lonnet::homeserver($unam,$udom);
2608: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2609: if ($ret eq 'ok') {
2610: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2611: if ($type eq 'thumbnail') {
2612: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2613: }
2614: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2615: return $tokenurl;
2616: } else {
2617: if ($type eq 'thumbnail') {
2618: return '/adm/lonKaputt/genericstudent_tn.gif';
2619: } else {
2620: return '/adm/lonKaputt/lonlogo_broken.gif';
2621: }
1.617 albertel 2622: }
2623: }
2624:
1.263 www 2625: # -------------------------------------------------------------------- New chat
2626:
2627: sub chatsend {
1.724 raeburn 2628: my ($newentry,$anon,$group)=@_;
1.620 albertel 2629: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2630: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2631: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2632: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2633: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2634: &escape($newentry)).':'.$group,$chome);
1.292 www 2635: }
2636:
2637: # ------------------------------------------ Find current version of a resource
2638:
2639: sub getversion {
2640: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2641: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2642: return ¤tversion(&filelocation('',$fname));
2643: }
2644:
2645: sub currentversion {
2646: my $fname=shift;
2647: my $author=$fname;
2648: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2649: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2650: my $home=&homeserver($uname,$udom);
1.292 www 2651: if ($home eq 'no_host') {
2652: return -1;
2653: }
1.1112 www 2654: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2655: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2656: return -1;
2657: }
1.1112 www 2658: return $answer;
1.263 www 2659: }
2660:
1.1111 www 2661: #
2662: # Return special version number of resource if set by override, empty otherwise
2663: #
2664: sub usedversion {
2665: my $fname=shift;
2666: unless ($fname) { $fname=$env{'request.uri'}; }
2667: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2668: if ($urlversion) { return $urlversion; }
2669: return '';
2670: }
2671:
1.1 albertel 2672: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2673:
1.1 albertel 2674: sub subscribe {
2675: my $fname=shift;
1.761 raeburn 2676: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2677: $fname=~s/[\n\r]//g;
1.1 albertel 2678: my $author=$fname;
2679: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2680: my ($udom,$uname)=split(/\//,$author);
2681: my $home=homeserver($uname,$udom);
1.335 albertel 2682: if ($home eq 'no_host') {
2683: return 'not_found';
1.1 albertel 2684: }
2685: my $answer=reply("sub:$fname",$home);
1.64 www 2686: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2687: $answer.=' by '.$home;
2688: }
1.1 albertel 2689: return $answer;
2690: }
2691:
1.8 www 2692: # -------------------------------------------------------------- Replicate file
2693:
2694: sub repcopy {
2695: my $filename=shift;
1.23 www 2696: $filename=~s/\/+/\//g;
1.1142 raeburn 2697: my $londocroot = $perlvar{'lonDocRoot'};
2698: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2699: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2700: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2701: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2702: return &repcopy_userfile($filename);
2703: }
1.532 albertel 2704: $filename=~s/[\n\r]//g;
1.8 www 2705: my $transname="$filename.in.transfer";
1.828 www 2706: # FIXME: this should flock
1.607 raeburn 2707: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2708: my $remoteurl=subscribe($filename);
1.64 www 2709: if ($remoteurl =~ /^con_lost by/) {
2710: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2711: return 'unavailable';
1.8 www 2712: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2713: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2714: return 'not_found';
1.64 www 2715: } elsif ($remoteurl =~ /^rejected by/) {
2716: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2717: return 'forbidden';
1.20 www 2718: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2719: return 'ok';
1.8 www 2720: } else {
1.290 www 2721: my $author=$filename;
2722: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2723: my ($udom,$uname)=split(/\//,$author);
2724: my $home=homeserver($uname,$udom);
2725: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2726: my @parts=split(/\//,$filename);
2727: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2728: if ($path ne "$londocroot/res") {
1.8 www 2729: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2730: return 'bad_request';
1.8 www 2731: }
2732: my $count;
2733: for ($count=5;$count<$#parts;$count++) {
2734: $path.="/$parts[$count]";
2735: if ((-e $path)!=1) {
2736: mkdir($path,0777);
2737: }
2738: }
2739: my $ua=new LWP::UserAgent;
2740: my $request=new HTTP::Request('GET',"$remoteurl");
2741: my $response=$ua->request($request,$transname);
2742: if ($response->is_error()) {
2743: unlink($transname);
2744: my $message=$response->status_line;
1.672 albertel 2745: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2746: ." LWP get: $message: $filename</font>");
1.607 raeburn 2747: return 'unavailable';
1.8 www 2748: } else {
1.16 www 2749: if ($remoteurl!~/\.meta$/) {
2750: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2751: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2752: if ($mresponse->is_error()) {
2753: unlink($filename.'.meta');
2754: &logthis(
1.672 albertel 2755: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2756: }
2757: }
1.8 www 2758: rename($transname,$filename);
1.607 raeburn 2759: return 'ok';
1.8 www 2760: }
1.290 www 2761: }
1.8 www 2762: }
1.330 www 2763: }
2764:
2765: # ------------------------------------------------ Get server side include body
2766: sub ssi_body {
1.381 albertel 2767: my ($filelink,%form)=@_;
1.606 matthew 2768: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2769: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2770: }
1.953 www 2771: my $output='';
2772: my $response;
1.980 raeburn 2773: if ($filelink=~/^https?\:/) {
1.954 raeburn 2774: ($output,$response)=&externalssi($filelink);
1.953 www 2775: } else {
1.1004 droeschl 2776: $filelink .= $filelink=~/\?/ ? '&' : '?';
2777: $filelink .= 'inhibitmenu=yes';
1.953 www 2778: ($output,$response)=&ssi($filelink,%form);
2779: }
1.778 albertel 2780: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2781: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2782: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2783: if (wantarray) {
2784: return ($output, $response);
2785: } else {
2786: return $output;
2787: }
1.8 www 2788: }
2789:
1.15 www 2790: # --------------------------------------------------------- Server Side Include
2791:
1.782 albertel 2792: sub absolute_url {
2793: my ($host_name) = @_;
2794: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2795: if ($host_name eq '') {
2796: $host_name = $ENV{'SERVER_NAME'};
2797: }
2798: return $protocol.$host_name;
2799: }
2800:
1.942 foxr 2801: #
2802: # Server side include.
2803: # Parameters:
2804: # fn Possibly encrypted resource name/id.
2805: # form Hash that describes how the rendering should be done
2806: # and other things.
1.944 foxr 2807: # Returns:
1.950 raeburn 2808: # Scalar context: The content of the response.
2809: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2810: #
1.15 www 2811: sub ssi {
2812:
1.944 foxr 2813: my ($fn,%form)=@_;
1.15 www 2814: my $ua=new LWP::UserAgent;
1.23 www 2815: my $request;
1.711 albertel 2816:
2817: $form{'no_update_last_known'}=1;
1.895 albertel 2818: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2819: if (%form) {
1.782 albertel 2820: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2821: $request->content(join('&',map {
2822: my $name = escape($_);
2823: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2824: ? join("&$name=", map {escape($_) } @{$form{$_}})
2825: : &escape($form{$_}) );
2826: } keys(%form)));
1.23 www 2827: } else {
1.782 albertel 2828: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2829: }
2830:
1.15 www 2831: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2832: my $response= $ua->request($request);
1.944 foxr 2833: if (wantarray) {
1.1172.2.3 raeburn 2834: return ($response->content, $response);
1.944 foxr 2835: } else {
1.1172.2.3 raeburn 2836: return $response->content;
1.942 foxr 2837: }
1.324 www 2838: }
2839:
2840: sub externalssi {
2841: my ($url)=@_;
2842: my $ua=new LWP::UserAgent;
2843: my $request=new HTTP::Request('GET',$url);
2844: my $response=$ua->request($request);
1.954 raeburn 2845: if (wantarray) {
2846: return ($response->content, $response);
2847: } else {
2848: return $response->content;
2849: }
1.15 www 2850: }
1.254 www 2851:
1.492 albertel 2852: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2853:
2854: sub allowuploaded {
2855: my ($srcurl,$url)=@_;
2856: $url=&clutter(&declutter($url));
2857: my $dir=$url;
2858: $dir=~s/\/[^\/]+$//;
2859: my %httpref=();
2860: my $httpurl=&hreflocation('',$url);
2861: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2862: &Apache::lonnet::appenv(\%httpref);
1.254 www 2863: }
1.477 raeburn 2864:
1.1172.2.13 raeburn 2865: #
2866: # Determine if the current user should be able to edit a particular resource,
2867: # when viewing in course context.
2868: # (a) When viewing resource used to determine if "Edit" item is included in
2869: # Functions.
2870: # (b) When displaying folder contents in course editor, used to determine if
2871: # "Edit" link will be displayed alongside resource.
2872: #
2873: # input: six args -- filename (decluttered), course number, course domain,
2874: # url, symb (if registered) and group (if this is a group
2875: # item -- e.g., bulletin board, group page etc.).
2876: # output: array of five scalars --
2877: # $cfile -- url for file editing if editable on current server
2878: # $home -- homeserver of resource (i.e., for author if published,
2879: # or course if uploaded.).
2880: # $switchserver -- 1 if server switch will be needed.
2881: # $forceedit -- 1 if icon/link should be to go to edit mode
2882: # $forceview -- 1 if icon/link should be to go to view mode
2883: #
2884:
2885: sub can_edit_resource {
2886: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2887: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2888: #
2889: # For aboutme pages user can only edit his/her own.
2890: #
2891: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2892: my ($sdom,$sname) = ($1,$2);
2893: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2894: $home = $env{'user.home'};
2895: $cfile = $resurl;
2896: if ($env{'form.forceedit'}) {
2897: $forceview = 1;
2898: } else {
2899: $forceedit = 1;
2900: }
2901: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2902: } else {
2903: return;
2904: }
2905: }
2906:
2907: if ($env{'request.course.id'}) {
2908: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2909: if ($group ne '') {
2910: # if this is a group homepage or group bulletin board, check group privs
2911: my $allowed = 0;
2912: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2913: if ((&allowed('mdg',$env{'request.course.id'}.
2914: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2915: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2916: $allowed = 1;
2917: }
2918: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2919: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2920: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2921: $allowed = 1;
2922: }
2923: }
2924: if ($allowed) {
2925: $home=&homeserver($cnum,$cdom);
2926: if ($env{'form.forceedit'}) {
2927: $forceview = 1;
2928: } else {
2929: $forceedit = 1;
2930: }
2931: $cfile = $resurl;
2932: } else {
2933: return;
2934: }
2935: } else {
1.1172.2.15 raeburn 2936: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2937: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2938: return;
2939: }
2940: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2941: #
2942: # No edit allowed where CC has switched to student role.
2943: #
2944: return;
2945: }
2946: }
2947: }
2948:
2949: if ($file ne '') {
2950: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2951: if (&is_course_upload($file,$cnum,$cdom)) {
2952: $uploaded = 1;
2953: $incourse = 1;
2954: if ($file =~/\.(htm|html|css|js|txt)$/) {
2955: $cfile = &hreflocation('',$file);
2956: if ($env{'form.forceedit'}) {
2957: $forceview = 1;
2958: } else {
2959: $forceedit = 1;
2960: }
2961: }
2962: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2963: $incourse = 1;
2964: if ($env{'form.forceedit'}) {
2965: $forceview = 1;
2966: } else {
2967: $forceedit = 1;
2968: }
2969: $cfile = $resurl;
2970: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2971: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2972: $incourse = 1;
2973: if ($env{'form.forceedit'}) {
2974: $forceview = 1;
2975: } else {
2976: $forceedit = 1;
2977: }
2978: $cfile = $resurl;
2979: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2980: $incourse = 1;
2981: $cfile = $resurl.'/smpedit';
2982: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2983: $incourse = 1;
2984: if ($env{'form.forceedit'}) {
2985: $forceview = 1;
2986: } else {
2987: $forceedit = 1;
2988: }
2989: $cfile = $resurl;
1.1172.2.15 raeburn 2990: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2991: $incourse = 1;
2992: if ($env{'form.forceedit'}) {
2993: $forceview = 1;
2994: } else {
2995: $forceedit = 1;
2996: }
2997: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2998: }
2999: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3000: my $template = '/res/lib/templates/simpleproblem.problem';
3001: if (&is_on_map($template)) {
3002: $incourse = 1;
3003: $forceview = 1;
3004: $cfile = $template;
3005: }
3006: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3007: $incourse = 1;
3008: if ($env{'form.forceedit'}) {
3009: $forceview = 1;
3010: } else {
3011: $forceedit = 1;
3012: }
3013: $cfile = $resurl;
3014: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3015: $incourse = 1;
3016: $forceview = 1;
3017: if ($symb) {
3018: my ($map,$id,$res)=&decode_symb($symb);
3019: $env{'request.symb'} = $symb;
3020: $cfile = &clutter($res);
3021: } else {
3022: $cfile = $env{'form.suppurl'};
3023: $cfile =~ s{^http://}{};
3024: $cfile = '/adm/wrapper/ext/'.$cfile;
3025: }
1.1172.2.31 raeburn 3026: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3027: if ($env{'form.forceedit'}) {
3028: $forceview = 1;
3029: } else {
3030: $forceedit = 1;
3031: }
3032: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3033: }
3034: }
3035: if ($uploaded || $incourse) {
3036: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3037: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3038: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3039: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3040: # Check that the user has permission to edit this resource
3041: my $setpriv = 1;
3042: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3043: if (defined($cfudom)) {
3044: $home=&homeserver($cfuname,$cfudom);
3045: $cfile=$file;
3046: }
3047: }
3048: if (($cfile ne '') && (!$incourse || $uploaded) &&
3049: (($home ne '') && ($home ne 'no_host'))) {
3050: my @ids=¤t_machine_ids();
3051: unless (grep(/^\Q$home\E$/,@ids)) {
3052: $switchserver=1;
3053: }
3054: }
3055: }
3056: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3057: }
3058:
3059: sub is_course_upload {
3060: my ($file,$cnum,$cdom) = @_;
3061: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3062: $uploadpath =~ s{^\/}{};
3063: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3064: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3065: return 1;
3066: }
3067: return;
3068: }
3069:
3070: sub in_course {
3071: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3072: if ($hideprivileged) {
3073: my $skipuser;
1.1172.2.23 raeburn 3074: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3075: my @possdoms = ($cdom);
3076: if ($coursehash{'checkforpriv'}) {
3077: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3078: }
3079: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3080: $skipuser = 1;
3081: if ($coursehash{'nothideprivileged'}) {
3082: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3083: my $user;
3084: if ($item =~ /:/) {
3085: $user = $item;
3086: } else {
3087: $user = join(':',split(/[\@]/,$item));
3088: }
3089: if ($user eq $uname.':'.$udom) {
3090: undef($skipuser);
3091: last;
3092: }
3093: }
3094: }
3095: if ($skipuser) {
3096: return 0;
3097: }
3098: }
3099: }
3100: $type ||= 'any';
3101: if (!defined($cdom) || !defined($cnum)) {
3102: my $cid = $env{'request.course.id'};
3103: $cdom = $env{'course.'.$cid.'.domain'};
3104: $cnum = $env{'course.'.$cid.'.num'};
3105: }
3106: my $typesref;
3107: if (($type eq 'any') || ($type eq 'all')) {
3108: $typesref = ['active','previous','future'];
3109: } elsif ($type eq 'previous' || $type eq 'future') {
3110: $typesref = [$type];
3111: }
3112: my %roles = &get_my_roles($uname,$udom,'userroles',
3113: $typesref,undef,[$cdom]);
3114: my ($tmp) = keys(%roles);
3115: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3116: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3117: if (@course_roles > 0) {
3118: return 1;
3119: }
3120: return 0;
3121: }
3122:
1.478 albertel 3123: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3124: # input: action, courseID, current domain, intended
1.637 raeburn 3125: # path to file, source of file, instruction to parse file for objects,
3126: # ref to hash for embedded objects,
3127: # ref to hash for codebase of java objects.
1.1095 raeburn 3128: # reference to scalar to accommodate mime type determined
3129: # from File::MMagic if $parser = parse.
1.637 raeburn 3130: #
1.485 raeburn 3131: # output: url to file (if action was uploaddoc),
3132: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3133: #
1.478 albertel 3134: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3135: # course.
1.477 raeburn 3136: #
1.478 albertel 3137: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3138: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3139: # course's home server.
1.477 raeburn 3140: #
1.478 albertel 3141: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3142: # be copied from $source (current location) to
3143: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3144: # and will then be copied to
3145: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3146: # course's home server.
1.485 raeburn 3147: #
1.481 raeburn 3148: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3149: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3150: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3151: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3152: # in course's home server.
1.637 raeburn 3153: #
1.477 raeburn 3154:
3155: sub process_coursefile {
1.1095 raeburn 3156: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3157: $mimetype)=@_;
1.477 raeburn 3158: my $fetchresult;
1.638 albertel 3159: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3160: if ($action eq 'propagate') {
1.638 albertel 3161: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3162: $home);
1.481 raeburn 3163: } else {
1.477 raeburn 3164: my $fpath = '';
3165: my $fname = $file;
1.478 albertel 3166: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3167: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3168: my $filepath = &build_filepath($fpath);
1.481 raeburn 3169: if ($action eq 'copy') {
3170: if ($source eq '') {
3171: $fetchresult = 'no source file';
3172: return $fetchresult;
3173: } else {
3174: my $destination = $filepath.'/'.$fname;
3175: rename($source,$destination);
3176: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3177: $home);
1.481 raeburn 3178: }
3179: } elsif ($action eq 'uploaddoc') {
3180: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3181: print $fh $env{'form.'.$source};
1.481 raeburn 3182: close($fh);
1.637 raeburn 3183: if ($parser eq 'parse') {
1.1024 raeburn 3184: my $mm = new File::MMagic;
1.1095 raeburn 3185: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3186: if ($type eq 'text/html') {
1.1024 raeburn 3187: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3188: unless ($parse_result eq 'ok') {
3189: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3190: }
1.637 raeburn 3191: }
1.1095 raeburn 3192: if (ref($mimetype)) {
3193: $$mimetype = $type;
3194: }
1.637 raeburn 3195: }
1.477 raeburn 3196: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3197: $home);
1.481 raeburn 3198: if ($fetchresult eq 'ok') {
3199: return '/uploaded/'.$fpath.'/'.$fname;
3200: } else {
3201: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3202: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3203: return '/adm/notfound.html';
3204: }
1.477 raeburn 3205: }
3206: }
1.485 raeburn 3207: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3208: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3209: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3210: }
3211: return $fetchresult;
3212: }
3213:
1.637 raeburn 3214: sub build_filepath {
3215: my ($fpath) = @_;
3216: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3217: unless ($fpath eq '') {
3218: my @parts=split('/',$fpath);
3219: foreach my $part (@parts) {
3220: $filepath.= '/'.$part;
3221: if ((-e $filepath)!=1) {
3222: mkdir($filepath,0777);
3223: }
3224: }
3225: }
3226: return $filepath;
3227: }
3228:
3229: sub store_edited_file {
1.638 albertel 3230: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3231: my $file = $primary_url;
3232: $file =~ s#^/uploaded/$docudom/$docuname/##;
3233: my $fpath = '';
3234: my $fname = $file;
3235: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3236: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3237: my $filepath = &build_filepath($fpath);
3238: open(my $fh,'>'.$filepath.'/'.$fname);
3239: print $fh $content;
3240: close($fh);
1.638 albertel 3241: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3242: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3243: $home);
1.637 raeburn 3244: if ($$fetchresult eq 'ok') {
3245: return '/uploaded/'.$fpath.'/'.$fname;
3246: } else {
1.638 albertel 3247: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3248: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3249: return '/adm/notfound.html';
3250: }
3251: }
3252:
1.531 albertel 3253: sub clean_filename {
1.831 albertel 3254: my ($fname,$args)=@_;
1.315 www 3255: # Replace Windows backslashes by forward slashes
1.257 www 3256: $fname=~s/\\/\//g;
1.831 albertel 3257: if (!$args->{'keep_path'}) {
3258: # Get rid of everything but the actual filename
3259: $fname=~s/^.*\/([^\/]+)$/$1/;
3260: }
1.315 www 3261: # Replace spaces by underscores
3262: $fname=~s/\s+/\_/g;
3263: # Replace all other weird characters by nothing
1.831 albertel 3264: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3265: # Replace all .\d. sequences with _\d. so they no longer look like version
3266: # numbers
3267: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3268: return $fname;
3269: }
1.1051 raeburn 3270: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3271: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3272: # image with the same aspect ratio as the original, but with dimensions which do
3273: # not exceed $resizewidth and $resizeheight.
3274:
1.984 neumanie 3275: sub resizeImage {
1.1051 raeburn 3276: my ($img_path,$resizewidth,$resizeheight) = @_;
3277: my $ima = Image::Magick->new;
3278: my $resized;
3279: if (-e $img_path) {
3280: $ima->Read($img_path);
3281: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3282: my $width = $ima->Get('width');
3283: my $height = $ima->Get('height');
3284: if ($width > $resizewidth) {
3285: my $factor = $width/$resizewidth;
3286: my $newheight = $height/$factor;
3287: $ima->Scale(width=>$resizewidth,height=>$newheight);
3288: $resized = 1;
3289: }
3290: }
3291: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3292: my $width = $ima->Get('width');
3293: my $height = $ima->Get('height');
3294: if ($height > $resizeheight) {
3295: my $factor = $height/$resizeheight;
3296: my $newwidth = $width/$factor;
3297: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3298: $resized = 1;
3299: }
3300: }
3301: if ($resized) {
3302: $ima->Write($img_path);
3303: }
3304: }
3305: return;
1.977 amueller 3306: }
3307:
1.608 albertel 3308: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3309: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3310: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3311: # $context - possible values: coursedoc, existingfile, overwrite,
3312: # canceloverwrite, or ''.
3313: # if 'coursedoc': upload to the current course
3314: # if 'existingfile': write file to tmp/overwrites directory
3315: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3316: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3317: # $subdir - directory in userfile to store the file into
1.858 raeburn 3318: # $parser - instruction to parse file for objects ($parser = parse)
3319: # $allfiles - reference to hash for embedded objects
3320: # $codebase - reference to hash for codebase of java objects
3321: # $desuname - username for permanent storage of uploaded file
3322: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3323: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3324: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3325: # $resizewidth - width (pixels) to which to resize uploaded image
3326: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3327: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3328: # from File::MMagic.
1.858 raeburn 3329: #
1.686 albertel 3330: # output: url of file in userspace, or error: <message>
3331: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3332:
1.531 albertel 3333: sub userfileupload {
1.1090 raeburn 3334: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3335: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3336: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3337: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3338: $fname=&clean_filename($fname);
1.1090 raeburn 3339: # See if there is anything left
1.257 www 3340: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3341: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3342: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3343: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3344: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3345: my $now = time;
1.1090 raeburn 3346: my $filepath;
1.1095 raeburn 3347: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3348: $filepath = 'tmp/helprequests/'.$now;
3349: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3350: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3351: '_'.$env{'user.domain'}.'/pending';
3352: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3353: my ($docuname,$docudom);
3354: if ($destudom) {
3355: $docudom = $destudom;
3356: } else {
3357: $docudom = $env{'user.domain'};
3358: }
3359: if ($destuname) {
3360: $docuname = $destuname;
3361: } else {
3362: $docuname = $env{'user.name'};
3363: }
3364: if (exists($env{'form.group'})) {
3365: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3366: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3367: }
3368: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3369: if ($context eq 'canceloverwrite') {
3370: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3371: if (-e $tempfile) {
3372: my @info = stat($tempfile);
3373: if ($info[9] eq $env{'form.timestamp'}) {
3374: unlink($tempfile);
3375: }
3376: }
3377: return;
1.523 raeburn 3378: }
3379: }
1.1090 raeburn 3380: # Create the directory if not present
1.741 raeburn 3381: my @parts=split(/\//,$filepath);
3382: my $fullpath = $perlvar{'lonDaemons'};
3383: for (my $i=0;$i<@parts;$i++) {
3384: $fullpath .= '/'.$parts[$i];
3385: if ((-e $fullpath)!=1) {
3386: mkdir($fullpath,0777);
3387: }
3388: }
3389: open(my $fh,'>'.$fullpath.'/'.$fname);
3390: print $fh $env{'form.'.$formname};
3391: close($fh);
1.1090 raeburn 3392: if ($context eq 'existingfile') {
3393: my @info = stat($fullpath.'/'.$fname);
3394: return ($fullpath.'/'.$fname,$info[9]);
3395: } else {
3396: return $fullpath.'/'.$fname;
3397: }
1.523 raeburn 3398: }
1.995 raeburn 3399: if ($subdir eq 'scantron') {
3400: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3401: } else {
1.995 raeburn 3402: $fname="$subdir/$fname";
3403: }
1.1090 raeburn 3404: if ($context eq 'coursedoc') {
1.638 albertel 3405: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3406: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3407: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3408: return &finishuserfileupload($docuname,$docudom,
3409: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3410: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3411: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3412: } else {
1.1172.2.21 raeburn 3413: if ($env{'form.folder'}) {
3414: $fname=$env{'form.folder'}.'/'.$fname;
3415: }
1.638 albertel 3416: return &process_coursefile('uploaddoc',$docuname,$docudom,
3417: $fname,$formname,$parser,
1.1095 raeburn 3418: $allfiles,$codebase,$mimetype);
1.481 raeburn 3419: }
1.719 banghart 3420: } elsif (defined($destuname)) {
3421: my $docuname=$destuname;
3422: my $docudom=$destudom;
1.860 raeburn 3423: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3424: $parser,$allfiles,$codebase,
1.1051 raeburn 3425: $thumbwidth,$thumbheight,
1.1095 raeburn 3426: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3427: } else {
1.638 albertel 3428: my $docuname=$env{'user.name'};
3429: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3430: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3431: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3432: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3433: }
1.860 raeburn 3434: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3435: $parser,$allfiles,$codebase,
1.1051 raeburn 3436: $thumbwidth,$thumbheight,
1.1095 raeburn 3437: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3438: }
1.271 www 3439: }
3440:
3441: sub finishuserfileupload {
1.860 raeburn 3442: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3443: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3444: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3445: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3446:
1.860 raeburn 3447: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3448: $file=$fname;
3449: if ($fname=~m|/|) {
3450: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3451: $path.=$fnamepath.'/';
3452: }
1.259 www 3453: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3454: my $count;
3455: for ($count=4;$count<=$#parts;$count++) {
3456: $filepath.="/$parts[$count]";
3457: if ((-e $filepath)!=1) {
3458: mkdir($filepath,0777);
3459: }
3460: }
1.984 neumanie 3461:
1.258 www 3462: # Save the file
3463: {
1.701 albertel 3464: if (!open(FH,'>'.$filepath.'/'.$file)) {
3465: &logthis('Failed to create '.$filepath.'/'.$file);
3466: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3467: return '/adm/notfound.html';
3468: }
1.1090 raeburn 3469: if ($context eq 'overwrite') {
1.1117 foxr 3470: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3471: my $target = $filepath.'/'.$file;
3472: if (-e $source) {
3473: my @info = stat($source);
3474: if ($info[9] eq $env{'form.timestamp'}) {
3475: unless (&File::Copy::move($source,$target)) {
3476: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3477: return "Moving from $source failed";
3478: }
3479: } else {
3480: return "Temporary file: $source had unexpected date/time for last modification";
3481: }
3482: } else {
3483: return "Temporary file: $source missing";
3484: }
3485: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3486: &logthis('Failed to write to '.$filepath.'/'.$file);
3487: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3488: return '/adm/notfound.html';
3489: }
1.570 albertel 3490: close(FH);
1.1051 raeburn 3491: if ($resizewidth && $resizeheight) {
3492: my $mm = new File::MMagic;
3493: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3494: if ($mime_type =~ m{^image/}) {
3495: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3496: }
1.977 amueller 3497: }
1.258 www 3498: }
1.1152 raeburn 3499: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3500: if (ref($mimetype)) {
3501: if ($$mimetype eq '') {
3502: my $mm = new File::MMagic;
3503: my $type = $mm->checktype_filename($filepath.'/'.$file);
3504: $$mimetype = $type;
3505: }
3506: }
3507: }
1.637 raeburn 3508: if ($parser eq 'parse') {
1.1152 raeburn 3509: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3510: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3511: $allfiles,$codebase);
3512: unless ($parse_result eq 'ok') {
3513: &logthis('Failed to parse '.$filepath.$file.
3514: ' for embedded media: '.$parse_result);
3515: }
1.637 raeburn 3516: }
3517: }
1.860 raeburn 3518: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3519: my $input = $filepath.'/'.$file;
3520: my $output = $filepath.'/'.'tn-'.$file;
3521: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3522: system("convert -sample $thumbsize $input $output");
3523: if (-e $filepath.'/'.'tn-'.$file) {
3524: $fetchthumb = 1;
3525: }
3526: }
1.858 raeburn 3527:
1.259 www 3528: # Notify homeserver to grep it
3529: #
1.984 neumanie 3530: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3531: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3532: if ($fetchresult eq 'ok') {
1.860 raeburn 3533: if ($fetchthumb) {
3534: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3535: if ($thumbresult ne 'ok') {
3536: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3537: $docuhome.': '.$thumbresult);
3538: }
3539: }
1.259 www 3540: #
1.258 www 3541: # Return the URL to it
1.494 albertel 3542: return '/uploaded/'.$path.$file;
1.263 www 3543: } else {
1.494 albertel 3544: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3545: ': '.$fetchresult);
1.263 www 3546: return '/adm/notfound.html';
1.858 raeburn 3547: }
1.493 albertel 3548: }
3549:
1.637 raeburn 3550: sub extract_embedded_items {
1.961 raeburn 3551: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3552: my @state = ();
1.1164 raeburn 3553: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3554: my %javafiles = (
3555: codebase => '',
3556: code => '',
3557: archive => ''
3558: );
3559: my %mediafiles = (
3560: src => '',
3561: movie => '',
3562: );
1.648 raeburn 3563: my $p;
3564: if ($content) {
3565: $p = HTML::LCParser->new($content);
3566: } else {
1.961 raeburn 3567: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3568: }
1.641 albertel 3569: while (my $t=$p->get_token()) {
1.640 albertel 3570: if ($t->[0] eq 'S') {
3571: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3572: push(@state, $tagname);
1.648 raeburn 3573: if (lc($tagname) eq 'allow') {
3574: &add_filetype($allfiles,$attr->{'src'},'src');
3575: }
1.640 albertel 3576: if (lc($tagname) eq 'img') {
3577: &add_filetype($allfiles,$attr->{'src'},'src');
3578: }
1.886 albertel 3579: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3580: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3581: &add_filetype($allfiles,$attr->{'href'},'href');
3582: }
1.886 albertel 3583: }
1.645 raeburn 3584: if (lc($tagname) eq 'script') {
1.1164 raeburn 3585: my $src;
1.645 raeburn 3586: if ($attr->{'archive'} =~ /\.jar$/i) {
3587: &add_filetype($allfiles,$attr->{'archive'},'archive');
3588: } else {
1.1164 raeburn 3589: if ($attr->{'src'} ne '') {
3590: $src = $attr->{'src'};
3591: &add_filetype($allfiles,$src,'src');
3592: }
3593: }
3594: my $text = $p->get_trimmed_text();
3595: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3596: my @swfargs = split(/,/,$1);
3597: foreach my $item (@swfargs) {
3598: $item =~ s/["']//g;
3599: $item =~ s/^\s+//;
3600: $item =~ s/\s+$//;
3601: }
3602: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3603: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3604: push(@{$related{$swfargs[0]}},$swfargs[2]);
3605: } else {
3606: $related{$swfargs[0]} = [$swfargs[2]];
3607: }
3608: }
1.645 raeburn 3609: }
3610: }
3611: if (lc($tagname) eq 'link') {
3612: if (lc($attr->{'rel'}) eq 'stylesheet') {
3613: &add_filetype($allfiles,$attr->{'href'},'href');
3614: }
3615: }
1.640 albertel 3616: if (lc($tagname) eq 'object' ||
3617: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3618: foreach my $item (keys(%javafiles)) {
3619: $javafiles{$item} = '';
3620: }
1.1164 raeburn 3621: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3622: $lastids{lc($tagname)} = $attr->{'id'};
3623: }
1.640 albertel 3624: }
3625: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3626: my $name = lc($attr->{'name'});
3627: foreach my $item (keys(%javafiles)) {
3628: if ($name eq $item) {
3629: $javafiles{$item} = $attr->{'value'};
3630: last;
3631: }
3632: }
1.1164 raeburn 3633: my $pathfrom;
1.640 albertel 3634: foreach my $item (keys(%mediafiles)) {
3635: if ($name eq $item) {
1.1164 raeburn 3636: $pathfrom = $attr->{'value'};
3637: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3638: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3639: last;
3640: }
3641: }
1.1164 raeburn 3642: if ($name eq 'flashvars') {
3643: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3644: }
3645: if ($pathfrom ne '') {
3646: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3647: $pathfrom);
3648: }
1.640 albertel 3649: }
3650: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3651: foreach my $item (keys(%javafiles)) {
3652: if ($attr->{$item}) {
3653: $javafiles{$item} = $attr->{$item};
3654: last;
3655: }
3656: }
3657: foreach my $item (keys(%mediafiles)) {
3658: if ($attr->{$item}) {
3659: &add_filetype($allfiles,$attr->{$item},$item);
3660: last;
3661: }
3662: }
1.1164 raeburn 3663: if (lc($tagname) eq 'embed') {
3664: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3665: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3666: $attr->{'src'});
3667: }
3668: }
1.640 albertel 3669: }
1.1172.2.35 raeburn 3670: if (lc($tagname) eq 'iframe') {
3671: my $src = $attr->{'src'} ;
3672: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3673: &add_filetype($allfiles,$src,'src');
3674: } elsif ($src =~ m{^/}) {
3675: if ($env{'request.course.id'}) {
3676: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3677: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3678: my $url = &hreflocation('',$fullpath);
3679: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3680: my $relpath = $1;
3681: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3682: &add_filetype($allfiles,$1,'src');
3683: }
3684: }
3685: }
3686: }
3687: }
1.1164 raeburn 3688: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3689: pop(@state);
1.1164 raeburn 3690: }
1.640 albertel 3691: } elsif ($t->[0] eq 'E') {
3692: my ($tagname) = ($t->[1]);
3693: if ($javafiles{'codebase'} ne '') {
3694: $javafiles{'codebase'} .= '/';
3695: }
3696: if (lc($tagname) eq 'applet' ||
3697: lc($tagname) eq 'object' ||
3698: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3699: ) {
3700: foreach my $item (keys(%javafiles)) {
3701: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3702: my $file=$javafiles{'codebase'}.$javafiles{$item};
3703: &add_filetype($allfiles,$file,$item);
3704: }
3705: }
3706: }
3707: pop @state;
3708: }
3709: }
1.1164 raeburn 3710: foreach my $id (sort(keys(%flashvars))) {
3711: if ($shockwave{$id} ne '') {
3712: my @pairs = split(/\&/,$flashvars{$id});
3713: foreach my $pair (@pairs) {
3714: my ($key,$value) = split(/\=/,$pair);
3715: if ($key eq 'thumb') {
3716: &add_filetype($allfiles,$value,$key);
3717: } elsif ($key eq 'content') {
3718: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3719: my ($ext) = ($value =~ /\.([^.]+)$/);
3720: if ($ext ne '') {
3721: &add_filetype($allfiles,$path.$value,$ext);
3722: }
3723: }
3724: }
3725: }
3726: }
1.637 raeburn 3727: return 'ok';
3728: }
3729:
1.639 albertel 3730: sub add_filetype {
3731: my ($allfiles,$file,$type)=@_;
3732: if (exists($allfiles->{$file})) {
3733: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3734: push(@{$allfiles->{$file}}, &escape($type));
3735: }
3736: } else {
3737: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3738: }
3739: }
3740:
1.1164 raeburn 3741: sub embedded_dependency {
3742: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3743: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3744: if (($identifier ne '') &&
3745: (ref($related->{$identifier}) eq 'ARRAY') &&
3746: ($pathfrom ne '')) {
3747: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3748: foreach my $dep (@{$related->{$identifier}}) {
3749: &add_filetype($allfiles,$path.$dep,'object');
3750: }
3751: }
3752: }
3753: return;
3754: }
3755:
1.493 albertel 3756: sub removeuploadedurl {
1.984 neumanie 3757: my ($url)=@_;
3758: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3759: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3760: }
3761:
3762: sub removeuserfile {
3763: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3764: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3765: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3766: if ($result eq 'ok') {
1.798 raeburn 3767: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3768: my $metafile = $fname.'.meta';
3769: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3770: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3771: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3772: my $sqlresult =
1.823 albertel 3773: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3774: 'portfolio_metadata',$group,
3775: 'delete');
1.798 raeburn 3776: }
3777: }
3778: return $result;
1.257 www 3779: }
1.15 www 3780:
1.530 albertel 3781: sub mkdiruserfile {
3782: my ($docuname,$docudom,$dir)=@_;
3783: my $home=&homeserver($docuname,$docudom);
3784: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3785: }
3786:
1.531 albertel 3787: sub renameuserfile {
3788: my ($docuname,$docudom,$old,$new)=@_;
3789: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3790: my $result = &reply("renameuserfile:$docudom:$docuname:".
3791: &escape("$old").':'.&escape("$new"),$home);
3792: if ($result eq 'ok') {
3793: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3794: my $oldmeta = $old.'.meta';
3795: my $newmeta = $new.'.meta';
3796: my $metaresult =
3797: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3798: my $url = "/uploaded/$docudom/$docuname/$old";
3799: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3800: my $sqlresult =
1.823 albertel 3801: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3802: 'portfolio_metadata',$group,
3803: 'delete');
1.798 raeburn 3804: }
3805: }
3806: return $result;
1.531 albertel 3807: }
3808:
1.14 www 3809: # ------------------------------------------------------------------------- Log
3810:
3811: sub log {
3812: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3813: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3814: }
3815:
3816: # ------------------------------------------------------------------ Course Log
1.352 www 3817: #
3818: # This routine flushes several buffers of non-mission-critical nature
3819: #
1.157 www 3820:
3821: sub flushcourselogs {
1.352 www 3822: &logthis('Flushing log buffers');
3823: #
3824: # course logs
3825: # This is a log of all transactions in a course, which can be used
3826: # for data mining purposes
3827: #
3828: # It also collects the courseid database, which lists last transaction
3829: # times and course titles for all courseids
3830: #
3831: my %courseidbuffer=();
1.921 raeburn 3832: foreach my $crsid (keys(%courselogs)) {
1.352 www 3833: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3834: &escape($courselogs{$crsid}),
3835: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3836: delete $courselogs{$crsid};
3837: } else {
3838: &logthis('Failed to flush log buffer for '.$crsid);
3839: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3840: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3841: " exceeded maximum size, deleting.</font>");
3842: delete $courselogs{$crsid};
3843: }
1.352 www 3844: }
1.920 raeburn 3845: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3846: 'description' => $coursedescrbuf{$crsid},
3847: 'inst_code' => $courseinstcodebuf{$crsid},
3848: 'type' => $coursetypebuf{$crsid},
3849: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3850: };
1.191 harris41 3851: }
1.352 www 3852: #
3853: # Write course id database (reverse lookup) to homeserver of courses
3854: # Is used in pickcourse
3855: #
1.840 albertel 3856: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3857: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3858: $courseidbuffer{$crs_home},
3859: $crs_home,'timeonly');
1.352 www 3860: }
3861: #
3862: # File accesses
3863: # Writes to the dynamic metadata of resources to get hit counts, etc.
3864: #
1.449 matthew 3865: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3866: if ($entry =~ /___count$/) {
3867: my ($dom,$name);
1.807 albertel 3868: ($dom,$name,undef)=
1.811 albertel 3869: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3870: if (! defined($dom) || $dom eq '' ||
3871: ! defined($name) || $name eq '') {
1.620 albertel 3872: my $cid = $env{'request.course.id'};
3873: $dom = $env{'request.'.$cid.'.domain'};
3874: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3875: }
1.450 matthew 3876: my $value = $accesshash{$entry};
3877: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3878: my %temphash=($url => $value);
1.449 matthew 3879: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3880: if ($result eq 'ok') {
3881: delete $accesshash{$entry};
3882: }
3883: } else {
1.811 albertel 3884: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3885: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3886: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3887: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3888: delete $accesshash{$entry};
3889: }
1.185 www 3890: }
1.191 harris41 3891: }
1.352 www 3892: #
3893: # Roles
3894: # Reverse lookup of user roles for course faculty/staff and co-authorship
3895: #
1.800 albertel 3896: foreach my $entry (keys(%userrolehash)) {
1.351 www 3897: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3898: split(/\:/,$entry);
3899: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3900: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3901: $rudom,$runame) eq 'ok') {
3902: delete $userrolehash{$entry};
3903: }
3904: }
1.662 raeburn 3905: #
3906: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3907: #
3908: my %domrolebuffer = ();
1.1000 raeburn 3909: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3910: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3911: if ($domrolebuffer{$rudom}) {
3912: $domrolebuffer{$rudom}.='&'.&escape($entry).
3913: '='.&escape($domainrolehash{$entry});
3914: } else {
3915: $domrolebuffer{$rudom}.=&escape($entry).
3916: '='.&escape($domainrolehash{$entry});
3917: }
3918: delete $domainrolehash{$entry};
3919: }
3920: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3921: my %servers = &get_servers($dom,'library');
3922: foreach my $tryserver (keys(%servers)) {
3923: unless (&reply('domroleput:'.$dom.':'.
3924: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3925: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3926: }
1.662 raeburn 3927: }
3928: }
1.186 www 3929: $dumpcount++;
1.157 www 3930: }
3931:
3932: sub courselog {
3933: my $what=shift;
1.158 www 3934: $what=time.':'.$what;
1.620 albertel 3935: unless ($env{'request.course.id'}) { return ''; }
3936: $coursedombuf{$env{'request.course.id'}}=
3937: $env{'course.'.$env{'request.course.id'}.'.domain'};
3938: $coursenumbuf{$env{'request.course.id'}}=
3939: $env{'course.'.$env{'request.course.id'}.'.num'};
3940: $coursehombuf{$env{'request.course.id'}}=
3941: $env{'course.'.$env{'request.course.id'}.'.home'};
3942: $coursedescrbuf{$env{'request.course.id'}}=
3943: $env{'course.'.$env{'request.course.id'}.'.description'};
3944: $courseinstcodebuf{$env{'request.course.id'}}=
3945: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3946: $courseownerbuf{$env{'request.course.id'}}=
3947: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3948: $coursetypebuf{$env{'request.course.id'}}=
3949: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3950: if (defined $courselogs{$env{'request.course.id'}}) {
3951: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3952: } else {
1.620 albertel 3953: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3954: }
1.620 albertel 3955: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3956: &flushcourselogs();
3957: }
1.158 www 3958: }
3959:
3960: sub courseacclog {
3961: my $fnsymb=shift;
1.620 albertel 3962: unless ($env{'request.course.id'}) { return ''; }
3963: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3964: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3965: $what.=':POST';
1.583 matthew 3966: # FIXME: Probably ought to escape things....
1.800 albertel 3967: foreach my $key (keys(%env)) {
3968: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3969: my $formitem = $1;
3970: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3971: $what.=':'.$formitem.'='.$env{$key};
3972: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3973: $what.=':'.$formitem.'='.$env{$key};
3974: }
1.158 www 3975: }
1.191 harris41 3976: }
1.583 matthew 3977: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3978: # FIXME: We should not be depending on a form parameter that someone
3979: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3980: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3981: $what.= ':POST';
3982: # FIXME: Probably ought to escape things....
3983: foreach my $element ('courseexp','crsfulltext','crsrelated',
3984: 'crsdiscuss') {
1.620 albertel 3985: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3986: }
3987: }
1.158 www 3988: }
3989: &courselog($what);
1.149 www 3990: }
3991:
1.185 www 3992: sub countacc {
3993: my $url=&declutter(shift);
1.458 matthew 3994: return if (! defined($url) || $url eq '');
1.620 albertel 3995: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3996: #
3997: # Mark that this url was used in this course
3998: #
1.620 albertel 3999: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4000: #
4001: # Increase the access count for this resource in this child process
4002: #
1.281 www 4003: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4004: $accesshash{$key}++;
1.185 www 4005: }
1.349 www 4006:
1.361 www 4007: sub linklog {
4008: my ($from,$to)=@_;
4009: $from=&declutter($from);
4010: $to=&declutter($to);
4011: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4012: $accesshash{$to.'___'.$from.'___goto'}=1;
4013: }
1.1160 www 4014:
4015: sub statslog {
4016: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4017: if ($users<2) { return; }
4018: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4019: 'course' => $env{'request.course.id'},
4020: 'sections' => '"all"',
4021: 'num_students' => $users,
4022: 'part' => $part,
4023: 'symb' => $symb,
4024: 'mean_tries' => $av_attempts,
4025: 'deg_of_diff' => $degdiff});
4026: foreach my $key (keys(%dynstore)) {
4027: $accesshash{$key}=$dynstore{$key};
4028: }
4029: }
1.361 www 4030:
1.349 www 4031: sub userrolelog {
4032: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4033: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4034: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4035: $userrolehash
4036: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4037: =$tend.':'.$tstart;
1.662 raeburn 4038: }
1.1169 droeschl 4039: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4040: $userrolehash
4041: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4042: =$tend.':'.$tstart;
4043: }
1.1169 droeschl 4044: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4045: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4046: $domainrolehash
4047: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4048: = $tend.':'.$tstart;
4049: }
1.351 www 4050: }
4051:
1.957 raeburn 4052: sub courserolelog {
4053: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4054: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4055: my $cdom = $1;
4056: my $cnum = $2;
4057: my $sec = $3;
4058: my $namespace = 'rolelog';
4059: my %storehash = (
4060: role => $trole,
4061: start => $tstart,
4062: end => $tend,
4063: selfenroll => $selfenroll,
4064: context => $context,
4065: );
4066: if ($trole eq 'gr') {
4067: $namespace = 'groupslog';
4068: $storehash{'group'} = $sec;
4069: } else {
4070: $storehash{'section'} = $sec;
4071: }
4072: &write_log('course',$namespace,\%storehash,$delflag,$username,
4073: $domain,$cnum,$cdom);
4074: if (($trole ne 'st') || ($sec ne '')) {
4075: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4076: }
4077: }
4078: return;
4079: }
4080:
1.1172.2.9 raeburn 4081: sub domainrolelog {
4082: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4083: if ($area =~ m{^/($match_domain)/$}) {
4084: my $cdom = $1;
4085: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4086: my $namespace = 'rolelog';
4087: my %storehash = (
4088: role => $trole,
4089: start => $tstart,
4090: end => $tend,
4091: context => $context,
4092: );
4093: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4094: $domain,$domconfiguser,$cdom);
4095: }
4096: return;
4097:
4098: }
4099:
4100: sub coauthorrolelog {
4101: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4102: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4103: my $audom = $1;
4104: my $auname = $2;
4105: my $namespace = 'rolelog';
4106: my %storehash = (
4107: role => $trole,
4108: start => $tstart,
4109: end => $tend,
4110: context => $context,
4111: );
4112: &write_log('author',$namespace,\%storehash,$delflag,$username,
4113: $domain,$auname,$audom);
4114: }
4115: return;
4116: }
4117:
1.351 www 4118: sub get_course_adv_roles {
1.948 raeburn 4119: my ($cid,$codes) = @_;
1.620 albertel 4120: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4121: my %coursehash=&coursedescription($cid);
1.988 raeburn 4122: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4123: my %nothide=();
1.800 albertel 4124: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4125: if ($user !~ /:/) {
4126: $nothide{join(':',split(/[\@]/,$user))}=1;
4127: } else {
4128: $nothide{$user}=1;
4129: }
1.470 www 4130: }
1.1172.2.23 raeburn 4131: my @possdoms = ($coursehash{'domain'});
4132: if ($coursehash{'checkforpriv'}) {
4133: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4134: }
1.351 www 4135: my %returnhash=();
4136: my %dumphash=
4137: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4138: my $now=time;
1.997 raeburn 4139: my %privileged;
1.1000 raeburn 4140: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4141: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4142: if (($tstart) && ($tstart<0)) { next; }
4143: if (($tend) && ($tend<$now)) { next; }
4144: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4145: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4146: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4147: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4148: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4149: if ($role eq 'cr') { next; }
1.948 raeburn 4150: if ($codes) {
4151: if ($section) { $role .= ':'.$section; }
4152: if ($returnhash{$role}) {
4153: $returnhash{$role}.=','.$username.':'.$domain;
4154: } else {
4155: $returnhash{$role}=$username.':'.$domain;
4156: }
1.351 www 4157: } else {
1.988 raeburn 4158: my $key=&plaintext($role,$crstype);
1.973 bisitz 4159: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4160: if ($returnhash{$key}) {
4161: $returnhash{$key}.=','.$username.':'.$domain;
4162: } else {
4163: $returnhash{$key}=$username.':'.$domain;
4164: }
1.351 www 4165: }
1.948 raeburn 4166: }
1.400 www 4167: return %returnhash;
4168: }
4169:
4170: sub get_my_roles {
1.937 raeburn 4171: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4172: unless (defined($uname)) { $uname=$env{'user.name'}; }
4173: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4174: my (%dumphash,%nothide);
1.1086 raeburn 4175: if ($context eq 'userroles') {
1.1166 raeburn 4176: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4177: } else {
1.1172.2.23 raeburn 4178: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4179: if ($hidepriv) {
4180: my %coursehash=&coursedescription($udom.'_'.$uname);
4181: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4182: if ($user !~ /:/) {
4183: $nothide{join(':',split(/[\@]/,$user))} = 1;
4184: } else {
4185: $nothide{$user} = 1;
4186: }
4187: }
4188: }
1.858 raeburn 4189: }
1.400 www 4190: my %returnhash=();
4191: my $now=time;
1.999 raeburn 4192: my %privileged;
1.800 albertel 4193: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4194: my ($role,$tend,$tstart);
4195: if ($context eq 'userroles') {
1.1149 raeburn 4196: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4197: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4198: } else {
4199: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4200: }
1.400 www 4201: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4202: my $status = 'active';
1.939 raeburn 4203: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4204: $status = 'previous';
4205: }
4206: if (($tstart) && ($now<$tstart)) {
4207: $status = 'future';
4208: }
4209: if (ref($types) eq 'ARRAY') {
4210: if (!grep(/^\Q$status\E$/,@{$types})) {
4211: next;
4212: }
4213: } else {
4214: if ($status ne 'active') {
4215: next;
4216: }
4217: }
1.867 raeburn 4218: my ($rolecode,$username,$domain,$section,$area);
4219: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4220: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4221: (undef,$domain,$username,$section) = split(/\//,$area);
4222: } else {
4223: ($role,$username,$domain,$section) = split(/\:/,$entry);
4224: }
1.832 raeburn 4225: if (ref($roledoms) eq 'ARRAY') {
4226: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4227: next;
4228: }
4229: }
4230: if (ref($roles) eq 'ARRAY') {
4231: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4232: if ($role =~ /^cr\//) {
4233: if (!grep(/^cr$/,@{$roles})) {
4234: next;
4235: }
1.1104 raeburn 4236: } elsif ($role =~ /^gr\//) {
4237: if (!grep(/^gr$/,@{$roles})) {
4238: next;
4239: }
1.922 raeburn 4240: } else {
4241: next;
4242: }
1.832 raeburn 4243: }
1.867 raeburn 4244: }
1.937 raeburn 4245: if ($hidepriv) {
1.1172.2.23 raeburn 4246: my @privroles = ('dc','su');
1.999 raeburn 4247: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4248: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4249: } else {
1.1172.2.23 raeburn 4250: my $possdoms = [$domain];
4251: if (ref($roledoms) eq 'ARRAY') {
4252: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4253: }
1.1172.2.23 raeburn 4254: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4255: if (!$nothide{$username.':'.$domain}) {
4256: next;
4257: }
4258: }
1.937 raeburn 4259: }
4260: }
1.933 raeburn 4261: if ($withsec) {
4262: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4263: $tstart.':'.$tend;
4264: } else {
4265: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4266: }
1.832 raeburn 4267: }
1.373 www 4268: return %returnhash;
1.399 www 4269: }
4270:
4271: # ----------------------------------------------------- Frontpage Announcements
4272: #
4273: #
4274:
4275: sub postannounce {
4276: my ($server,$text)=@_;
1.844 albertel 4277: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4278: unless ($text=~/\w/) { $text=''; }
4279: return &reply('setannounce:'.&escape($text),$server);
4280: }
4281:
4282: sub getannounce {
1.448 albertel 4283:
4284: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4285: my $announcement='';
1.800 albertel 4286: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4287: close($fh);
1.399 www 4288: if ($announcement=~/\w/) {
4289: return
4290: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4291: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4292: } else {
4293: return '';
4294: }
4295: } else {
4296: return '';
4297: }
1.351 www 4298: }
1.353 www 4299:
4300: # ---------------------------------------------------------- Course ID routines
4301: # Deal with domain's nohist_courseid.db files
4302: #
4303:
4304: sub courseidput {
1.921 raeburn 4305: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4306: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4307: my $outcome;
4308: if ($caller eq 'timeonly') {
4309: my $cids = '';
4310: foreach my $item (keys(%$storehash)) {
4311: $cids.=&escape($item).'&';
4312: }
4313: $cids=~s/\&$//;
4314: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4315: $coursehome);
4316: } else {
4317: my $items = '';
4318: foreach my $item (keys(%$storehash)) {
4319: $items.= &escape($item).'='.
4320: &freeze_escape($$storehash{$item}).'&';
4321: }
4322: $items=~s/\&$//;
4323: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4324: $coursehome);
1.918 raeburn 4325: }
4326: if ($outcome eq 'unknown_cmd') {
4327: my $what;
4328: foreach my $cid (keys(%$storehash)) {
4329: $what .= &escape($cid).'=';
1.921 raeburn 4330: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4331: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4332: }
4333: $what =~ s/\:$/&/;
4334: }
4335: $what =~ s/\&$//;
4336: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4337: } else {
4338: return $outcome;
4339: }
1.353 www 4340: }
4341:
4342: sub courseiddump {
1.921 raeburn 4343: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4344: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4345: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4346: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4347: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4348: my $as_hash = 1;
4349: my %returnhash;
4350: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4351: my %libserv = &all_library();
4352: foreach my $tryserver (keys(%libserv)) {
4353: if ( ( $hostidflag == 1
4354: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4355: || (!defined($hostidflag)) ) {
4356:
1.918 raeburn 4357: if (($domfilter eq '') ||
4358: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4359: my $rep;
4360: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4361: $rep = &LONCAPA::Lond::dump_course_id_handler(
4362: join(":", (&host_domain($tryserver), $sincefilter,
4363: &escape($descfilter), &escape($instcodefilter),
4364: &escape($ownerfilter), &escape($coursefilter),
4365: &escape($typefilter), &escape($regexp_ok),
4366: $as_hash, &escape($selfenrollonly),
4367: &escape($catfilter), $showhidden, $caller,
4368: &escape($cloner), &escape($cc_clone), $cloneonly,
4369: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4370: &escape($creationcontext),$domcloner,$hasuniquecode,
4371: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4372: } else {
4373: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4374: $sincefilter.':'.&escape($descfilter).':'.
4375: &escape($instcodefilter).':'.&escape($ownerfilter).
4376: ':'.&escape($coursefilter).':'.&escape($typefilter).
4377: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4378: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4379: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4380: &escape($cc_clone).':'.$cloneonly.':'.
4381: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4382: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4383: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4384: }
4385:
1.918 raeburn 4386: my @pairs=split(/\&/,$rep);
4387: foreach my $item (@pairs) {
4388: my ($key,$value)=split(/\=/,$item,2);
4389: $key = &unescape($key);
4390: next if ($key =~ /^error: 2 /);
4391: my $result = &thaw_unescape($value);
4392: if (ref($result) eq 'HASH') {
4393: $returnhash{$key}=$result;
4394: } else {
1.921 raeburn 4395: my @responses = split(/:/,$value);
4396: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4397: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4398: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4399: }
1.1008 raeburn 4400: }
1.353 www 4401: }
4402: }
4403: }
4404: }
4405: return %returnhash;
4406: }
4407:
1.1055 raeburn 4408: sub courselastaccess {
4409: my ($cdom,$cnum,$hostidref) = @_;
4410: my %returnhash;
4411: if ($cdom && $cnum) {
4412: my $chome = &homeserver($cnum,$cdom);
4413: if ($chome ne 'no_host') {
4414: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4415: &extract_lastaccess(\%returnhash,$rep);
4416: }
4417: } else {
4418: if (!$cdom) { $cdom=''; }
4419: my %libserv = &all_library();
4420: foreach my $tryserver (keys(%libserv)) {
4421: if (ref($hostidref) eq 'ARRAY') {
4422: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4423: }
4424: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4425: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4426: &extract_lastaccess(\%returnhash,$rep);
4427: }
4428: }
4429: }
4430: return %returnhash;
4431: }
4432:
4433: sub extract_lastaccess {
4434: my ($returnhash,$rep) = @_;
4435: if (ref($returnhash) eq 'HASH') {
4436: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4437: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4438: $rep eq '') {
4439: my @pairs=split(/\&/,$rep);
4440: foreach my $item (@pairs) {
4441: my ($key,$value)=split(/\=/,$item,2);
4442: $key = &unescape($key);
4443: next if ($key =~ /^error: 2 /);
4444: $returnhash->{$key} = &thaw_unescape($value);
4445: }
4446: }
4447: }
4448: return;
4449: }
4450:
1.658 raeburn 4451: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4452:
4453: sub dcmailput {
1.685 raeburn 4454: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4455: my $status = &Apache::lonnet::critical(
1.740 www 4456: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4457: &escape($message),$server);
1.662 raeburn 4458: return $status;
4459: }
4460:
1.658 raeburn 4461: sub dcmaildump {
4462: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4463: my %returnhash=();
1.846 albertel 4464:
4465: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4466: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4467: &escape($enddate).':';
4468: my @esc_senders=map { &escape($_)} @$senders;
4469: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4470: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4471: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4472: if (($key) && ($value)) {
4473: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4474: }
4475: }
4476: }
4477: return %returnhash;
4478: }
1.662 raeburn 4479: # ---------------------------------------------------------- Domain roles
4480:
4481: sub get_domain_roles {
4482: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4483: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4484: $startdate = '.';
4485: }
1.1018 raeburn 4486: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4487: $enddate = '.';
4488: }
1.922 raeburn 4489: my $rolelist;
4490: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4491: $rolelist = join('&',@{$roles});
1.922 raeburn 4492: }
1.662 raeburn 4493: my %personnel = ();
1.841 albertel 4494:
4495: my %servers = &get_servers($dom,'library');
4496: foreach my $tryserver (keys(%servers)) {
4497: %{$personnel{$tryserver}}=();
4498: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4499: &escape($startdate).':'.
4500: &escape($enddate).':'.
4501: &escape($rolelist), $tryserver))) {
4502: my ($key,$value) = split(/\=/,$line,2);
4503: if (($key) && ($value)) {
4504: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4505: }
4506: }
1.662 raeburn 4507: }
4508: return %personnel;
4509: }
1.658 raeburn 4510:
1.1057 www 4511: # ----------------------------------------------------------- Interval timing
1.149 www 4512:
1.1153 www 4513: {
4514: # Caches needed for speedup of navmaps
4515: # We don't want to cache this for very long at all (5 seconds at most)
4516: #
4517: # The user for whom we cache
4518: my $cachedkey='';
4519: # The cached times for this user
4520: my %cachedtimes=();
4521: # When this was last done
1.1172.2.66 raeburn 4522: my $cachedtime='';
1.1153 www 4523:
4524: sub load_all_first_access {
1.1154 raeburn 4525: my ($uname,$udom)=@_;
1.1156 www 4526: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4527: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4528: return;
4529: }
4530: $cachedtime=time;
4531: $cachedkey=$uname.':'.$udom;
4532: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4533: }
4534:
1.504 albertel 4535: sub get_first_access {
1.1162 raeburn 4536: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4537: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4538: if ($argsymb) { $symb=$argsymb; }
4539: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4540: if ($argmap) { $map = $argmap; }
1.926 albertel 4541: if ($type eq 'course') {
4542: $res='course';
4543: } elsif ($type eq 'map') {
1.588 albertel 4544: $res=&symbread($map);
4545: } else {
4546: $res=$symb;
4547: }
1.1153 www 4548: &load_all_first_access($uname,$udom);
4549: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4550: }
4551:
4552: sub set_first_access {
1.1162 raeburn 4553: my ($type,$interval)=@_;
1.790 albertel 4554: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4555: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4556: if ($type eq 'course') {
4557: $res='course';
4558: } elsif ($type eq 'map') {
1.588 albertel 4559: $res=&symbread($map);
4560: } else {
4561: $res=$symb;
4562: }
1.1153 www 4563: $cachedkey='';
1.1162 raeburn 4564: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4565: if (!$firstaccess) {
1.1162 raeburn 4566: my $start = time;
4567: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4568: $udom,$uname);
4569: if ($putres eq 'ok') {
4570: &put('timerinterval',{"$courseid\0$res"=>$interval},
4571: $udom,$uname);
4572: &appenv(
4573: {
4574: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4575: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4576: }
4577: );
4578: }
4579: return $putres;
1.505 albertel 4580: }
4581: return 'already_set';
1.504 albertel 4582: }
1.1153 www 4583: }
1.1172.2.32 raeburn 4584:
4585: sub checkout {
4586: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4587: my $now=time;
4588: my $lonhost=$perlvar{'lonHostID'};
4589: my $infostr=&escape(
4590: 'CHECKOUTTOKEN&'.
4591: $tuname.'&'.
4592: $tudom.'&'.
4593: $tcrsid.'&'.
4594: $symb.'&'.
4595: $now.'&'.$ENV{'REMOTE_ADDR'});
4596: my $token=&reply('tmpput:'.$infostr,$lonhost);
4597: if ($token=~/^error\:/) {
4598: &logthis("<font color=\"blue\">WARNING: ".
4599: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4600: "</font>");
4601: return '';
4602: }
4603:
4604: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4605: $token=~tr/a-z/A-Z/;
4606:
4607: my %infohash=('resource.0.outtoken' => $token,
4608: 'resource.0.checkouttime' => $now,
4609: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4610:
4611: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4612: return '';
4613: } else {
4614: &logthis("<font color=\"blue\">WARNING: ".
4615: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4616: "</font>");
4617: }
4618:
4619: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4620: &escape('Checkout '.$infostr.' - '.
4621: $token)) ne 'ok') {
4622: return '';
4623: } else {
4624: &logthis("<font color=\"blue\">WARNING: ".
4625: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4626: "</font>");
4627: }
4628: return $token;
4629: }
4630:
4631: # ------------------------------------------------------------ Check in an item
4632:
4633: sub checkin {
4634: my $token=shift;
4635: my $now=time;
4636: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4637: $lonhost=~tr/A-Z/a-z/;
4638: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4639: $dtoken=~s/\W/\_/g;
4640: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4641: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4642:
4643: unless (($tuname) && ($tudom)) {
4644: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4645: return '';
4646: }
4647:
4648: unless (&allowed('mgr',$tcrsid)) {
4649: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4650: $env{'user.name'}.' - '.$env{'user.domain'});
4651: return '';
4652: }
4653:
4654: my %infohash=('resource.0.intoken' => $token,
4655: 'resource.0.checkintime' => $now,
4656: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4657:
4658: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4659: return '';
4660: }
4661:
4662: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4663: &escape('Checkin - '.$token)) ne 'ok') {
4664: return '';
4665: }
4666:
4667: return ($symb,$tuname,$tudom,$tcrsid);
4668: }
4669:
1.110 www 4670: # --------------------------------------------- Set Expire Date for Spreadsheet
4671:
4672: sub expirespread {
4673: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4674: my $cid=$env{'request.course.id'};
1.110 www 4675: if ($cid) {
4676: my $now=time;
4677: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4678: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4679: $env{'course.'.$cid.'.num'}.
1.110 www 4680: ':nohist_expirationdates:'.
4681: &escape($key).'='.$now,
1.620 albertel 4682: $env{'course.'.$cid.'.home'})
1.110 www 4683: }
4684: return 'ok';
1.14 www 4685: }
4686:
1.109 www 4687: # ----------------------------------------------------- Devalidate Spreadsheets
4688:
4689: sub devalidate {
1.325 www 4690: my ($symb,$uname,$udom)=@_;
1.620 albertel 4691: my $cid=$env{'request.course.id'};
1.109 www 4692: if ($cid) {
1.391 matthew 4693: # delete the stored spreadsheets for
4694: # - the student level sheet of this user in course's homespace
4695: # - the assessment level sheet for this resource
4696: # for this user in user's homespace
1.553 albertel 4697: # - current conditional state info
1.325 www 4698: my $key=$uname.':'.$udom.':';
1.109 www 4699: my $status=
1.299 matthew 4700: &del('nohist_calculatedsheets',
1.391 matthew 4701: [$key.'studentcalc:'],
1.620 albertel 4702: $env{'course.'.$cid.'.domain'},
4703: $env{'course.'.$cid.'.num'})
1.133 albertel 4704: .' '.
4705: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4706: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4707: unless ($status eq 'ok ok') {
4708: &logthis('Could not devalidate spreadsheet '.
1.325 www 4709: $uname.' at '.$udom.' for '.
1.109 www 4710: $symb.': '.$status);
1.133 albertel 4711: }
1.553 albertel 4712: &delenv('user.state.'.$cid);
1.109 www 4713: }
4714: }
4715:
1.265 albertel 4716: sub get_scalar {
4717: my ($string,$end) = @_;
4718: my $value;
4719: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4720: $value = $1;
4721: } elsif ($$string =~ s/^([^&]*?)&//) {
4722: $value = $1;
4723: }
4724: return &unescape($value);
4725: }
4726:
4727: sub array2str {
4728: my (@array) = @_;
4729: my $result=&arrayref2str(\@array);
4730: $result=~s/^__ARRAY_REF__//;
4731: $result=~s/__END_ARRAY_REF__$//;
4732: return $result;
4733: }
4734:
1.204 albertel 4735: sub arrayref2str {
4736: my ($arrayref) = @_;
1.265 albertel 4737: my $result='__ARRAY_REF__';
1.204 albertel 4738: foreach my $elem (@$arrayref) {
1.265 albertel 4739: if(ref($elem) eq 'ARRAY') {
4740: $result.=&arrayref2str($elem).'&';
4741: } elsif(ref($elem) eq 'HASH') {
4742: $result.=&hashref2str($elem).'&';
4743: } elsif(ref($elem)) {
4744: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4745: } else {
4746: $result.=&escape($elem).'&';
4747: }
4748: }
4749: $result=~s/\&$//;
1.265 albertel 4750: $result .= '__END_ARRAY_REF__';
1.204 albertel 4751: return $result;
4752: }
4753:
1.168 albertel 4754: sub hash2str {
1.204 albertel 4755: my (%hash) = @_;
4756: my $result=&hashref2str(\%hash);
1.265 albertel 4757: $result=~s/^__HASH_REF__//;
4758: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4759: return $result;
4760: }
4761:
4762: sub hashref2str {
4763: my ($hashref)=@_;
1.265 albertel 4764: my $result='__HASH_REF__';
1.800 albertel 4765: foreach my $key (sort(keys(%$hashref))) {
4766: if (ref($key) eq 'ARRAY') {
4767: $result.=&arrayref2str($key).'=';
4768: } elsif (ref($key) eq 'HASH') {
4769: $result.=&hashref2str($key).'=';
4770: } elsif (ref($key)) {
1.265 albertel 4771: $result.='=';
1.800 albertel 4772: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4773: } else {
1.1132 raeburn 4774: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4775: }
4776:
1.800 albertel 4777: if(ref($hashref->{$key}) eq 'ARRAY') {
4778: $result.=&arrayref2str($hashref->{$key}).'&';
4779: } elsif(ref($hashref->{$key}) eq 'HASH') {
4780: $result.=&hashref2str($hashref->{$key}).'&';
4781: } elsif(ref($hashref->{$key})) {
1.265 albertel 4782: $result.='&';
1.800 albertel 4783: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4784: } else {
1.800 albertel 4785: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4786: }
4787: }
1.168 albertel 4788: $result=~s/\&$//;
1.265 albertel 4789: $result .= '__END_HASH_REF__';
1.168 albertel 4790: return $result;
4791: }
4792:
4793: sub str2hash {
1.265 albertel 4794: my ($string)=@_;
4795: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4796: return %$hash;
4797: }
4798:
4799: sub str2hashref {
1.168 albertel 4800: my ($string) = @_;
1.265 albertel 4801:
4802: my %hash;
4803:
4804: if($string !~ /^__HASH_REF__/) {
4805: if (! ($string eq '' || !defined($string))) {
4806: $hash{'error'}='Not hash reference';
4807: }
4808: return (\%hash, $string);
4809: }
4810:
4811: $string =~ s/^__HASH_REF__//;
4812:
4813: while($string !~ /^__END_HASH_REF__/) {
4814: #key
4815: my $key='';
4816: if($string =~ /^__HASH_REF__/) {
4817: ($key, $string)=&str2hashref($string);
4818: if(defined($key->{'error'})) {
4819: $hash{'error'}='Bad data';
4820: return (\%hash, $string);
4821: }
4822: } elsif($string =~ /^__ARRAY_REF__/) {
4823: ($key, $string)=&str2arrayref($string);
4824: if($key->[0] eq 'Array reference error') {
4825: $hash{'error'}='Bad data';
4826: return (\%hash, $string);
4827: }
4828: } else {
4829: $string =~ s/^(.*?)=//;
1.267 albertel 4830: $key=&unescape($1);
1.265 albertel 4831: }
4832: $string =~ s/^=//;
4833:
4834: #value
4835: my $value='';
4836: if($string =~ /^__HASH_REF__/) {
4837: ($value, $string)=&str2hashref($string);
4838: if(defined($value->{'error'})) {
4839: $hash{'error'}='Bad data';
4840: return (\%hash, $string);
4841: }
4842: } elsif($string =~ /^__ARRAY_REF__/) {
4843: ($value, $string)=&str2arrayref($string);
4844: if($value->[0] eq 'Array reference error') {
4845: $hash{'error'}='Bad data';
4846: return (\%hash, $string);
4847: }
4848: } else {
4849: $value=&get_scalar(\$string,'__END_HASH_REF__');
4850: }
4851: $string =~ s/^&//;
4852:
4853: $hash{$key}=$value;
1.204 albertel 4854: }
1.265 albertel 4855:
4856: $string =~ s/^__END_HASH_REF__//;
4857:
4858: return (\%hash, $string);
1.204 albertel 4859: }
4860:
4861: sub str2array {
1.265 albertel 4862: my ($string)=@_;
4863: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4864: return @$array;
4865: }
4866:
4867: sub str2arrayref {
1.204 albertel 4868: my ($string) = @_;
1.265 albertel 4869: my @array;
4870:
4871: if($string !~ /^__ARRAY_REF__/) {
4872: if (! ($string eq '' || !defined($string))) {
4873: $array[0]='Array reference error';
4874: }
4875: return (\@array, $string);
4876: }
4877:
4878: $string =~ s/^__ARRAY_REF__//;
4879:
4880: while($string !~ /^__END_ARRAY_REF__/) {
4881: my $value='';
4882: if($string =~ /^__HASH_REF__/) {
4883: ($value, $string)=&str2hashref($string);
4884: if(defined($value->{'error'})) {
4885: $array[0] ='Array reference error';
4886: return (\@array, $string);
4887: }
4888: } elsif($string =~ /^__ARRAY_REF__/) {
4889: ($value, $string)=&str2arrayref($string);
4890: if($value->[0] eq 'Array reference error') {
4891: $array[0] ='Array reference error';
4892: return (\@array, $string);
4893: }
4894: } else {
4895: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4896: }
4897: $string =~ s/^&//;
4898:
4899: push(@array, $value);
1.191 harris41 4900: }
1.265 albertel 4901:
4902: $string =~ s/^__END_ARRAY_REF__//;
4903:
4904: return (\@array, $string);
1.168 albertel 4905: }
4906:
1.167 albertel 4907: # -------------------------------------------------------------------Temp Store
4908:
1.168 albertel 4909: sub tmpreset {
4910: my ($symb,$namespace,$domain,$stuname) = @_;
4911: if (!$symb) {
4912: $symb=&symbread();
1.620 albertel 4913: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4914: }
4915: $symb=escape($symb);
4916:
1.620 albertel 4917: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4918: $namespace=~s/\//\_/g;
4919: $namespace=~s/\W//g;
4920:
1.620 albertel 4921: if (!$domain) { $domain=$env{'user.domain'}; }
4922: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4923: if ($domain eq 'public' && $stuname eq 'public') {
4924: $stuname=$ENV{'REMOTE_ADDR'};
4925: }
1.1117 foxr 4926: my $path=LONCAPA::tempdir();
1.168 albertel 4927: my %hash;
4928: if (tie(%hash,'GDBM_File',
4929: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4930: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4931: foreach my $key (keys(%hash)) {
1.180 albertel 4932: if ($key=~ /:$symb/) {
1.168 albertel 4933: delete($hash{$key});
4934: }
4935: }
4936: }
4937: }
4938:
1.167 albertel 4939: sub tmpstore {
1.168 albertel 4940: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4941:
4942: if (!$symb) {
4943: $symb=&symbread();
1.620 albertel 4944: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4945: }
4946: $symb=escape($symb);
4947:
4948: if (!$namespace) {
4949: # I don't think we would ever want to store this for a course.
4950: # it seems this will only be used if we don't have a course.
1.620 albertel 4951: #$namespace=$env{'request.course.id'};
1.168 albertel 4952: #if (!$namespace) {
1.620 albertel 4953: $namespace=$env{'request.state'};
1.168 albertel 4954: #}
4955: }
4956: $namespace=~s/\//\_/g;
4957: $namespace=~s/\W//g;
1.620 albertel 4958: if (!$domain) { $domain=$env{'user.domain'}; }
4959: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4960: if ($domain eq 'public' && $stuname eq 'public') {
4961: $stuname=$ENV{'REMOTE_ADDR'};
4962: }
1.168 albertel 4963: my $now=time;
4964: my %hash;
1.1117 foxr 4965: my $path=LONCAPA::tempdir();
1.168 albertel 4966: if (tie(%hash,'GDBM_File',
4967: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4968: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4969: $hash{"version:$symb"}++;
4970: my $version=$hash{"version:$symb"};
4971: my $allkeys='';
4972: foreach my $key (keys(%$storehash)) {
4973: $allkeys.=$key.':';
1.591 albertel 4974: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4975: }
4976: $hash{"$version:$symb:timestamp"}=$now;
4977: $allkeys.='timestamp';
4978: $hash{"$version:keys:$symb"}=$allkeys;
4979: if (untie(%hash)) {
4980: return 'ok';
4981: } else {
4982: return "error:$!";
4983: }
4984: } else {
4985: return "error:$!";
4986: }
4987: }
1.167 albertel 4988:
1.168 albertel 4989: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4990:
1.168 albertel 4991: sub tmprestore {
4992: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4993:
1.168 albertel 4994: if (!$symb) {
4995: $symb=&symbread();
1.620 albertel 4996: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4997: }
4998: $symb=escape($symb);
4999:
1.620 albertel 5000: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5001:
1.620 albertel 5002: if (!$domain) { $domain=$env{'user.domain'}; }
5003: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5004: if ($domain eq 'public' && $stuname eq 'public') {
5005: $stuname=$ENV{'REMOTE_ADDR'};
5006: }
1.168 albertel 5007: my %returnhash;
5008: $namespace=~s/\//\_/g;
5009: $namespace=~s/\W//g;
5010: my %hash;
1.1117 foxr 5011: my $path=LONCAPA::tempdir();
1.168 albertel 5012: if (tie(%hash,'GDBM_File',
5013: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5014: &GDBM_READER(),0640)) {
1.168 albertel 5015: my $version=$hash{"version:$symb"};
5016: $returnhash{'version'}=$version;
5017: my $scope;
5018: for ($scope=1;$scope<=$version;$scope++) {
5019: my $vkeys=$hash{"$scope:keys:$symb"};
5020: my @keys=split(/:/,$vkeys);
5021: my $key;
5022: $returnhash{"$scope:keys"}=$vkeys;
5023: foreach $key (@keys) {
1.591 albertel 5024: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5025: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5026: }
5027: }
1.168 albertel 5028: if (!(untie(%hash))) {
5029: return "error:$!";
5030: }
5031: } else {
5032: return "error:$!";
5033: }
5034: return %returnhash;
1.167 albertel 5035: }
5036:
1.9 www 5037: # ----------------------------------------------------------------------- Store
5038:
5039: sub store {
1.1172.2.64 raeburn 5040: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5041: my $home='';
5042:
1.168 albertel 5043: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5044:
1.213 www 5045: $symb=&symbclean($symb);
1.122 albertel 5046: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5047:
1.620 albertel 5048: if (!$domain) { $domain=$env{'user.domain'}; }
5049: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5050:
5051: &devalidate($symb,$stuname,$domain);
1.109 www 5052:
5053: $symb=escape($symb);
1.187 www 5054: if (!$namespace) {
1.620 albertel 5055: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5056: return '';
5057: }
5058: }
1.620 albertel 5059: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5060:
5061: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5062: $$storehash{'host'}=$perlvar{'lonHostID'};
5063:
1.12 www 5064: my $namevalue='';
1.800 albertel 5065: foreach my $key (keys(%$storehash)) {
5066: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5067: }
1.12 www 5068: $namevalue=~s/\&$//;
1.187 www 5069: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5070: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5071: }
5072:
1.47 www 5073: # -------------------------------------------------------------- Critical Store
5074:
5075: sub cstore {
1.1172.2.64 raeburn 5076: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5077: my $home='';
5078:
1.168 albertel 5079: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5080:
1.213 www 5081: $symb=&symbclean($symb);
1.122 albertel 5082: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5083:
1.620 albertel 5084: if (!$domain) { $domain=$env{'user.domain'}; }
5085: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5086:
5087: &devalidate($symb,$stuname,$domain);
1.109 www 5088:
5089: $symb=escape($symb);
1.187 www 5090: if (!$namespace) {
1.620 albertel 5091: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5092: return '';
5093: }
5094: }
1.620 albertel 5095: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5096:
5097: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5098: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5099:
1.47 www 5100: my $namevalue='';
1.800 albertel 5101: foreach my $key (keys(%$storehash)) {
5102: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5103: }
1.47 www 5104: $namevalue=~s/\&$//;
1.187 www 5105: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5106: return critical
1.1172.2.64 raeburn 5107: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5108: }
5109:
1.9 www 5110: # --------------------------------------------------------------------- Restore
5111:
5112: sub restore {
1.124 www 5113: my ($symb,$namespace,$domain,$stuname) = @_;
5114: my $home='';
5115:
1.168 albertel 5116: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5117:
1.122 albertel 5118: if (!$symb) {
1.1172.2.26 raeburn 5119: return if ($namespace eq 'courserequests');
5120: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5121: } else {
1.1172.2.26 raeburn 5122: unless ($namespace eq 'courserequests') {
5123: $symb=&escape(&symbclean($symb));
5124: }
1.122 albertel 5125: }
1.188 www 5126: if (!$namespace) {
1.620 albertel 5127: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5128: return '';
5129: }
5130: }
1.620 albertel 5131: if (!$domain) { $domain=$env{'user.domain'}; }
5132: if (!$stuname) { $stuname=$env{'user.name'}; }
5133: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5134: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5135:
1.12 www 5136: my %returnhash=();
1.800 albertel 5137: foreach my $line (split(/\&/,$answer)) {
5138: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5139: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5140: }
1.75 www 5141: my $version;
5142: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5143: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5144: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5145: }
1.75 www 5146: }
1.13 www 5147: return %returnhash;
1.34 www 5148: }
5149:
5150: # ---------------------------------------------------------- Course Description
1.1118 foxr 5151: #
5152: #
1.34 www 5153:
5154: sub coursedescription {
1.731 albertel 5155: my ($courseid,$args)=@_;
1.34 www 5156: $courseid=~s/^\///;
1.49 www 5157: $courseid=~s/\_/\//g;
1.34 www 5158: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5159: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5160: my $normalid=$cdomain.'_'.$cnum;
5161: # need to always cache even if we get errors otherwise we keep
5162: # trying and trying and trying to get the course description.
5163: my %envhash=();
5164: my %returnhash=();
1.731 albertel 5165:
5166: my $expiretime=600;
5167: if ($env{'request.course.id'} eq $normalid) {
5168: $expiretime=120;
5169: }
5170:
5171: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5172: if (!$args->{'freshen_cache'}
5173: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5174: foreach my $key (keys(%env)) {
5175: next if ($key !~ /^\Q$prefix\E(.*)/);
5176: my ($setting) = $1;
5177: $returnhash{$setting} = $env{$key};
5178: }
5179: return %returnhash;
5180: }
5181:
1.1118 foxr 5182: # get the data again
5183:
1.731 albertel 5184: if (!$args->{'one_time'}) {
5185: $envhash{'course.'.$normalid.'.last_cache'}=time;
5186: }
1.811 albertel 5187:
1.34 www 5188: if ($chome ne 'no_host') {
1.302 albertel 5189: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5190: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5191: my $username = $env{'user.name'}; # Defult username
5192: if(defined $args->{'user'}) {
5193: $username = $args->{'user'};
5194: }
1.129 albertel 5195: $returnhash{'home'}= $chome;
5196: $returnhash{'domain'} = $cdomain;
5197: $returnhash{'num'} = $cnum;
1.741 raeburn 5198: if (!defined($returnhash{'type'})) {
5199: $returnhash{'type'} = 'Course';
5200: }
1.130 albertel 5201: while (my ($name,$value) = each %returnhash) {
1.53 www 5202: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5203: }
1.270 www 5204: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5205: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5206: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5207: $envhash{'course.'.$normalid.'.home'}=$chome;
5208: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5209: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5210: }
5211: }
1.731 albertel 5212: if (!$args->{'one_time'}) {
1.949 raeburn 5213: &appenv(\%envhash);
1.731 albertel 5214: }
1.302 albertel 5215: return %returnhash;
1.461 www 5216: }
5217:
1.1080 raeburn 5218: sub update_released_required {
5219: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5220: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5221: $cid = $env{'request.course.id'};
5222: $cdom = $env{'course.'.$cid.'.domain'};
5223: $cnum = $env{'course.'.$cid.'.num'};
5224: $chome = $env{'course.'.$cid.'.home'};
5225: }
5226: if ($needsrelease) {
5227: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5228: my $needsupdate;
5229: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5230: $needsupdate = 1;
5231: } else {
5232: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5233: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5234: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5235: $needsupdate = 1;
5236: }
5237: }
5238: if ($needsupdate) {
5239: my %needshash = (
5240: 'internal.releaserequired' => $needsrelease,
5241: );
5242: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5243: if ($putresult eq 'ok') {
5244: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5245: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5246: if (ref($crsinfo{$cid}) eq 'HASH') {
5247: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5248: &courseidput($cdom,\%crsinfo,$chome,'notime');
5249: }
5250: }
5251: }
5252: }
5253: return;
5254: }
5255:
1.461 www 5256: # -------------------------------------------------See if a user is privileged
5257:
5258: sub privileged {
1.1172.2.23 raeburn 5259: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5260: my $now = time;
1.1172.2.23 raeburn 5261: my $roles;
5262: if (ref($possroles) eq 'ARRAY') {
5263: $roles = $possroles;
5264: } else {
5265: $roles = ['dc','su'];
5266: }
5267: if (ref($possdomains) eq 'ARRAY') {
5268: my %privileged = &privileged_by_domain($possdomains,$roles);
5269: foreach my $dom (@{$possdomains}) {
5270: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5271: (ref($privileged{$dom}) eq 'HASH')) {
5272: foreach my $role (@{$roles}) {
5273: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5274: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5275: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5276: return 1 unless (($end && $end < $now) ||
5277: ($start && $start > $now));
5278: }
5279: }
5280: }
5281: }
5282: }
5283: } else {
5284: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5285: my $now = time;
1.1170 droeschl 5286:
1.1172.2.58 raeburn 5287: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5288: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5289: if (grep(/^\Q$trole\E$/,@{$roles})) {
5290: return 1 unless ($tend && $tend < $now)
5291: or ($tstart && $tstart > $now);
1.1170 droeschl 5292: }
1.1172.2.23 raeburn 5293: }
5294: }
1.461 www 5295: return 0;
1.9 www 5296: }
1.1 albertel 5297:
1.1172.2.23 raeburn 5298: sub privileged_by_domain {
5299: my ($domains,$roles) = @_;
5300: my %privileged = ();
5301: my $cachetime = 60*60*24;
5302: my $now = time;
5303: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5304: return %privileged;
5305: }
5306: foreach my $dom (@{$domains}) {
5307: next if (ref($privileged{$dom}) eq 'HASH');
5308: my $needroles;
5309: foreach my $role (@{$roles}) {
5310: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5311: if (defined($cached)) {
5312: if (ref($result) eq 'HASH') {
5313: $privileged{$dom}{$role} = $result;
5314: }
5315: } else {
5316: $needroles = 1;
5317: }
5318: }
5319: if ($needroles) {
5320: my %dompersonnel = &get_domain_roles($dom,$roles);
5321: $privileged{$dom} = {};
5322: foreach my $server (keys(%dompersonnel)) {
5323: if (ref($dompersonnel{$server}) eq 'HASH') {
5324: foreach my $item (keys(%{$dompersonnel{$server}})) {
5325: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5326: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5327: next if ($end && $end < $now);
5328: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5329: $dompersonnel{$server}{$item};
5330: }
5331: }
5332: }
5333: if (ref($privileged{$dom}) eq 'HASH') {
5334: foreach my $role (@{$roles}) {
5335: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5336: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5337: } else {
5338: my %hash = ();
5339: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5340: }
5341: }
5342: }
5343: }
5344: }
5345: return %privileged;
5346: }
5347:
1.103 harris41 5348: # -------------------------------------------------------- Get user privileges
1.11 www 5349:
5350: sub rolesinit {
1.1169 droeschl 5351: my ($domain, $username) = @_;
5352: my %userroles = ('user.login.time' => time);
5353: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5354:
5355: # firstaccess and timerinterval are related to timed maps/resources.
5356: # also, blocking can be triggered by an activating timer
5357: # it's saved in the user's %env.
5358: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5359: my %timerinterval = &dump('timerinterval', $domain, $username);
5360: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5361: %timerintchk, %timerintenv);
5362:
1.1162 raeburn 5363: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5364: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5365: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5366: }
1.1169 droeschl 5367:
1.1162 raeburn 5368: foreach my $key (keys(%timerinterval)) {
5369: my ($cid,$rest) = split(/\0/,$key);
5370: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5371: }
1.1169 droeschl 5372:
1.11 www 5373: my %allroles=();
1.1162 raeburn 5374: my %allgroups=();
1.11 www 5375:
1.1172.2.58 raeburn 5376: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5377: my $role = $rolesdump{$area};
5378: $area =~ s/\_\w\w$//;
5379:
5380: my ($trole, $tend, $tstart, $group_privs);
5381:
5382: if ($role =~ /^cr/) {
5383: # Custom role, defined by a user
5384: # e.g., user.role.cr/msu/smith/mynewrole
5385: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5386: $trole = $1;
5387: ($tend, $tstart) = split('_', $2);
5388: } else {
5389: $trole = $role;
5390: }
5391: } elsif ($role =~ m|^gr/|) {
5392: # Role of member in a group, defined within a course/community
5393: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5394: ($trole, $tend, $tstart) = split(/_/, $role);
5395: next if $tstart eq '-1';
5396: ($trole, $group_privs) = split(/\//, $trole);
5397: $group_privs = &unescape($group_privs);
5398: } else {
5399: # Just a normal role, defined in roles.tab
5400: ($trole, $tend, $tstart) = split(/_/,$role);
5401: }
5402:
5403: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5404: $username);
5405: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5406:
5407: # role expired or not available yet?
5408: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5409: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5410:
5411: next if $area eq '' or $trole eq '';
5412:
5413: my $spec = "$trole.$area";
5414: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5415:
5416: if ($trole =~ /^cr\//) {
5417: # Custom role, defined by a user
5418: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5419: } elsif ($trole eq 'gr') {
5420: # Role of a member in a group, defined within a course/community
5421: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5422: next;
5423: } else {
5424: # Normal role, defined in roles.tab
5425: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5426: }
5427:
5428: my $cid = $tdomain.'_'.$trest;
5429: unless ($firstaccchk{$cid}) {
5430: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5431: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5432: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5433: $coursetimerstarts{$cid}{$item};
5434: }
5435: }
5436: $firstaccchk{$cid} = 1;
5437: }
5438: unless ($timerintchk{$cid}) {
5439: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5440: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5441: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5442: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5443: }
1.12 www 5444: }
1.1169 droeschl 5445: $timerintchk{$cid} = 1;
1.191 harris41 5446: }
1.11 www 5447: }
1.1169 droeschl 5448:
5449: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5450: \%allroles, \%allgroups);
5451: $env{'user.adv'} = $userroles{'user.adv'};
5452:
1.1162 raeburn 5453: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5454: }
5455:
1.567 raeburn 5456: sub set_arearole {
1.1172.2.19 raeburn 5457: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5458: unless ($nolog) {
1.567 raeburn 5459: # log the associated role with the area
1.1172.2.19 raeburn 5460: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5461: }
1.743 albertel 5462: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5463: }
5464:
5465: sub custom_roleprivs {
5466: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5467: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5468: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5469: if (&hostname($homsvr) ne '') {
1.567 raeburn 5470: my ($rdummy,$roledef)=
5471: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5472: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5473: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5474: if (defined($syspriv)) {
1.1043 raeburn 5475: if ($trest =~ /^$match_community$/) {
5476: $syspriv =~ s/bre\&S//;
5477: }
1.567 raeburn 5478: $$allroles{'cm./'}.=':'.$syspriv;
5479: $$allroles{$spec.'./'}.=':'.$syspriv;
5480: }
5481: if ($tdomain ne '') {
5482: if (defined($dompriv)) {
5483: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5484: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5485: }
5486: if (($trest ne '') && (defined($coursepriv))) {
5487: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5488: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5489: }
5490: }
5491: }
5492: }
5493: }
5494:
1.678 raeburn 5495: sub group_roleprivs {
5496: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5497: my $access = 1;
5498: my $now = time;
5499: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5500: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5501: if ($access) {
1.811 albertel 5502: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5503: $$allgroups{$course}{$group} .=':'.$group_privs;
5504: }
5505: }
1.567 raeburn 5506:
5507: sub standard_roleprivs {
5508: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5509: if (defined($pr{$trole.':s'})) {
5510: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5511: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5512: }
5513: if ($tdomain ne '') {
5514: if (defined($pr{$trole.':d'})) {
5515: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5516: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5517: }
5518: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5519: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5520: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5521: }
5522: }
5523: }
5524:
5525: sub set_userprivs {
1.1064 raeburn 5526: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5527: my $author=0;
5528: my $adv=0;
1.678 raeburn 5529: my %grouproles = ();
5530: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5531: my @groupkeys;
1.1000 raeburn 5532: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5533: push(@groupkeys,$role);
5534: }
5535: if (ref($groups_roles) eq 'HASH') {
5536: foreach my $key (keys(%{$groups_roles})) {
5537: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5538: push(@groupkeys,$key);
5539: }
5540: }
5541: }
5542: if (@groupkeys > 0) {
5543: foreach my $role (@groupkeys) {
5544: my ($trole,$area,$sec,$extendedarea);
5545: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5546: $trole = $1;
5547: $area = $2;
5548: $sec = $3;
5549: $extendedarea = $area.$sec;
5550: if (exists($$allgroups{$area})) {
5551: foreach my $group (keys(%{$$allgroups{$area}})) {
5552: my $spec = $trole.'.'.$extendedarea;
5553: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5554: $$allgroups{$area}{$group};
1.1064 raeburn 5555: }
1.678 raeburn 5556: }
5557: }
5558: }
5559: }
5560: }
1.800 albertel 5561: foreach my $group (keys(%grouproles)) {
5562: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5563: }
1.800 albertel 5564: foreach my $role (keys(%{$allroles})) {
5565: my %thesepriv;
1.941 raeburn 5566: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5567: foreach my $item (split(/:/,$$allroles{$role})) {
5568: if ($item ne '') {
5569: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5570: if ($restrictions eq '') {
5571: $thesepriv{$privilege}='F';
5572: } elsif ($thesepriv{$privilege} ne 'F') {
5573: $thesepriv{$privilege}.=$restrictions;
5574: }
5575: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5576: }
5577: }
5578: my $thesestr='';
1.1104 raeburn 5579: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5580: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5581: }
5582: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5583: }
5584: return ($author,$adv);
5585: }
5586:
1.994 raeburn 5587: sub role_status {
1.1104 raeburn 5588: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5589: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5590: my ($one,$two) = split(m{\./},$rolekey,2);
5591: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5592: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5593: $$where = '/'.$two;
1.994 raeburn 5594: $$trolecode=$$role.'.'.$$where;
5595: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5596: $$tstatus='is';
1.1104 raeburn 5597: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5598: $$tstatus='future';
1.1034 raeburn 5599: if ($$tstart<$now) {
5600: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5601: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5602: my (%allroles,%allgroups,$group_privs,
5603: %groups_roles,@rolecodes);
1.1002 raeburn 5604: my %userroles = (
5605: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5606: );
1.1064 raeburn 5607: @rolecodes = ('cm');
1.1002 raeburn 5608: my $spec=$$role.'.'.$$where;
5609: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5610: if ($$role =~ /^cr\//) {
5611: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5612: push(@rolecodes,'cr');
1.1002 raeburn 5613: } elsif ($$role eq 'gr') {
1.1064 raeburn 5614: push(@rolecodes,$$role);
1.1002 raeburn 5615: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5616: $env{'user.name'});
1.1064 raeburn 5617: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5618: (undef,my $group_privs) = split(/\//,$trole);
5619: $group_privs = &unescape($group_privs);
5620: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5621: 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 5622: &get_groups_roles($tdomain,$trest,
5623: \%course_roles,\@rolecodes,
5624: \%groups_roles);
1.1002 raeburn 5625: } else {
1.1064 raeburn 5626: push(@rolecodes,$$role);
1.1002 raeburn 5627: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5628: }
1.1064 raeburn 5629: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5630: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5631: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5632: }
5633: }
1.1034 raeburn 5634: $$tstatus = 'is';
1.1002 raeburn 5635: }
1.994 raeburn 5636: }
5637: if ($$tend) {
1.1104 raeburn 5638: if ($$tend<$update) {
1.994 raeburn 5639: $$tstatus='expired';
5640: } elsif ($$tend<$now) {
5641: $$tstatus='will_not';
5642: }
5643: }
5644: }
5645: }
5646: }
5647:
1.1104 raeburn 5648: sub get_groups_roles {
5649: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5650: return unless((ref($cdom_courseroles) eq 'HASH') &&
5651: (ref($rolecodes) eq 'ARRAY') &&
5652: (ref($groups_roles) eq 'HASH'));
5653: if (keys(%{$cdom_courseroles}) > 0) {
5654: my ($cnum) = ($rest =~ /^($match_courseid)/);
5655: if ($cdom ne '' && $cnum ne '') {
5656: foreach my $key (keys(%{$cdom_courseroles})) {
5657: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5658: my $crsrole = $1;
5659: my $crssec = $2;
5660: if ($crsrole =~ /^cr/) {
5661: unless (grep(/^cr$/,@{$rolecodes})) {
5662: push(@{$rolecodes},'cr');
5663: }
5664: } else {
5665: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5666: push(@{$rolecodes},$crsrole);
5667: }
5668: }
5669: my $rolekey = "$crsrole./$cdom/$cnum";
5670: if ($crssec ne '') {
5671: $rolekey .= "/$crssec";
5672: }
5673: $rolekey .= './';
5674: $groups_roles->{$rolekey} = $rolecodes;
5675: }
5676: }
5677: }
5678: }
5679: return;
5680: }
5681:
5682: sub delete_env_groupprivs {
5683: my ($where,$courseroles,$possroles) = @_;
5684: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5685: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5686: unless (ref($courseroles->{$udom}) eq 'HASH') {
5687: %{$courseroles->{$udom}} =
5688: &get_my_roles('','','userroles',['active'],
5689: $possroles,[$udom],1);
5690: }
5691: if (ref($courseroles->{$udom}) eq 'HASH') {
5692: foreach my $item (keys(%{$courseroles->{$udom}})) {
5693: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5694: my $area = '/'.$cdom.'/'.$cnum;
5695: my $privkey = "user.priv.$crsrole.$area";
5696: if ($crssec ne '') {
5697: $privkey .= '/'.$crssec;
5698: }
5699: $privkey .= ".$area/$group";
5700: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5701: }
5702: }
5703: return;
5704: }
5705:
1.994 raeburn 5706: sub check_adhoc_privs {
1.1104 raeburn 5707: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5708: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5709: my $setprivs;
1.994 raeburn 5710: if ($env{$cckey}) {
5711: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5712: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5713: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5714: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5715: $setprivs = 1;
1.994 raeburn 5716: }
5717: } else {
1.1088 raeburn 5718: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5719: $setprivs = 1;
1.994 raeburn 5720: }
1.1172.2.9 raeburn 5721: return $setprivs;
1.994 raeburn 5722: }
5723:
5724: sub set_adhoc_privileges {
5725: # role can be cc or ca
1.1088 raeburn 5726: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5727: my $area = '/'.$dcdom.'/'.$pickedcourse;
5728: my $spec = $role.'.'.$area;
5729: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5730: $env{'user.name'},1);
1.994 raeburn 5731: my %ccrole = ();
5732: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5733: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5734: &appenv(\%userroles,[$role,'cm']);
5735: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5736: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5737: &appenv( {'request.role' => $spec,
5738: 'request.role.domain' => $dcdom,
5739: 'request.course.sec' => ''
5740: }
5741: );
5742: my $tadv=0;
5743: if (&allowed('adv') eq 'F') { $tadv=1; }
5744: &appenv({'request.role.adv' => $tadv});
5745: }
1.994 raeburn 5746: }
5747:
1.12 www 5748: # --------------------------------------------------------------- get interface
5749:
5750: sub get {
1.131 albertel 5751: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5752: my $items='';
1.800 albertel 5753: foreach my $item (@$storearr) {
5754: $items.=&escape($item).'&';
1.191 harris41 5755: }
1.12 www 5756: $items=~s/\&$//;
1.620 albertel 5757: if (!$udomain) { $udomain=$env{'user.domain'}; }
5758: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5759: my $uhome=&homeserver($uname,$udomain);
5760:
1.133 albertel 5761: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5762: my @pairs=split(/\&/,$rep);
1.273 albertel 5763: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5764: return @pairs;
5765: }
1.15 www 5766: my %returnhash=();
1.42 www 5767: my $i=0;
1.800 albertel 5768: foreach my $item (@$storearr) {
5769: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5770: $i++;
1.191 harris41 5771: }
1.15 www 5772: return %returnhash;
1.27 www 5773: }
5774:
5775: # --------------------------------------------------------------- del interface
5776:
5777: sub del {
1.133 albertel 5778: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5779: my $items='';
1.800 albertel 5780: foreach my $item (@$storearr) {
5781: $items.=&escape($item).'&';
1.191 harris41 5782: }
1.984 neumanie 5783:
1.27 www 5784: $items=~s/\&$//;
1.620 albertel 5785: if (!$udomain) { $udomain=$env{'user.domain'}; }
5786: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5787: my $uhome=&homeserver($uname,$udomain);
5788: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5789: }
5790:
5791: # -------------------------------------------------------------- dump interface
5792:
1.1172.2.22 raeburn 5793: sub unserialize {
5794: my ($rep, $escapedkeys) = @_;
5795:
5796: return {} if $rep =~ /^error/;
5797:
5798: my %returnhash=();
5799: foreach my $item (split(/\&/,$rep)) {
5800: my ($key, $value) = split(/=/, $item, 2);
5801: $key = unescape($key) unless $escapedkeys;
5802: next if $key =~ /^error: 2 /;
5803: $returnhash{$key} = &thaw_unescape($value);
5804: }
5805: return \%returnhash;
5806: }
5807:
5808: # see Lond::dump_with_regexp
5809: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5810: sub dump {
1.1172.2.22 raeburn 5811: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5812: if (!$udomain) { $udomain=$env{'user.domain'}; }
5813: if (!$uname) { $uname=$env{'user.name'}; }
5814: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5815:
1.1172.2.55 raeburn 5816: if ($regexp) {
5817: $regexp=&escape($regexp);
5818: } else {
5819: $regexp='.';
5820: }
1.1172.2.22 raeburn 5821: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5822: # user is hosted on this machine
1.1172.2.55 raeburn 5823: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5824: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5825: return %{&unserialize($reply, $escapedkeys)};
5826: }
1.1166 raeburn 5827: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5828: my @pairs=split(/\&/,$rep);
5829: my %returnhash=();
1.1098 foxr 5830: if (!($rep =~ /^error/ )) {
5831: foreach my $item (@pairs) {
5832: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5833: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5834: next if ($key =~ /^error: 2 /);
5835: $returnhash{$key}=&thaw_unescape($value);
5836: }
1.755 albertel 5837: }
5838: return %returnhash;
1.407 www 5839: }
5840:
1.1098 foxr 5841:
1.717 albertel 5842: # --------------------------------------------------------- dumpstore interface
5843:
5844: sub dumpstore {
5845: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5846: # same as dump but keys must be escaped. They may contain colon separated
5847: # lists of values that may themself contain colons (e.g. symbs).
5848: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5849: }
5850:
1.407 www 5851: # -------------------------------------------------------------- keys interface
5852:
5853: sub getkeys {
5854: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5855: if (!$udomain) { $udomain=$env{'user.domain'}; }
5856: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5857: my $uhome=&homeserver($uname,$udomain);
5858: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5859: my @keyarray=();
1.800 albertel 5860: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5861: next if ($key =~ /^error: 2 /);
1.800 albertel 5862: push(@keyarray,&unescape($key));
1.407 www 5863: }
5864: return @keyarray;
1.318 matthew 5865: }
5866:
1.319 matthew 5867: # --------------------------------------------------------------- currentdump
5868: sub currentdump {
1.328 matthew 5869: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5870: $courseid = $env{'request.course.id'} if (! defined($courseid));
5871: $sdom = $env{'user.domain'} if (! defined($sdom));
5872: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5873: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5874: my $rep;
5875:
5876: if (grep { $_ eq $uhome } current_machine_ids()) {
5877: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5878: $courseid)));
5879: } else {
5880: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5881: }
5882:
1.318 matthew 5883: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5884: #
1.318 matthew 5885: my %returnhash=();
1.319 matthew 5886: #
5887: if ($rep eq "unknown_cmd") {
5888: # an old lond will not know currentdump
5889: # Do a dump and make it look like a currentdump
1.822 albertel 5890: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5891: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5892: my %hash = @tmp;
5893: @tmp=();
1.424 matthew 5894: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5895: } else {
5896: my @pairs=split(/\&/,$rep);
1.800 albertel 5897: foreach my $pair (@pairs) {
5898: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5899: my ($symb,$param) = split(/:/,$key);
5900: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5901: &thaw_unescape($value);
1.319 matthew 5902: }
1.191 harris41 5903: }
1.12 www 5904: return %returnhash;
1.424 matthew 5905: }
5906:
5907: sub convert_dump_to_currentdump{
5908: my %hash = %{shift()};
5909: my %returnhash;
5910: # Code ripped from lond, essentially. The only difference
5911: # here is the unescaping done by lonnet::dump(). Conceivably
5912: # we might run in to problems with parameter names =~ /^v\./
5913: while (my ($key,$value) = each(%hash)) {
5914: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5915: $symb = &unescape($symb);
5916: $param = &unescape($param);
1.424 matthew 5917: next if ($v eq 'version' || $symb eq 'keys');
5918: next if (exists($returnhash{$symb}) &&
5919: exists($returnhash{$symb}->{$param}) &&
5920: $returnhash{$symb}->{'v.'.$param} > $v);
5921: $returnhash{$symb}->{$param}=$value;
5922: $returnhash{$symb}->{'v.'.$param}=$v;
5923: }
5924: #
5925: # Remove all of the keys in the hashes which keep track of
5926: # the version of the parameter.
5927: while (my ($symb,$param_hash) = each(%returnhash)) {
5928: # use a foreach because we are going to delete from the hash.
5929: foreach my $key (keys(%$param_hash)) {
5930: delete($param_hash->{$key}) if ($key =~ /^v\./);
5931: }
5932: }
5933: return \%returnhash;
1.12 www 5934: }
5935:
1.627 albertel 5936: # ------------------------------------------------------ critical inc interface
5937:
5938: sub cinc {
5939: return &inc(@_,'critical');
5940: }
5941:
1.449 matthew 5942: # --------------------------------------------------------------- inc interface
5943:
5944: sub inc {
1.627 albertel 5945: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5946: if (!$udomain) { $udomain=$env{'user.domain'}; }
5947: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5948: my $uhome=&homeserver($uname,$udomain);
5949: my $items='';
5950: if (! ref($store)) {
5951: # got a single value, so use that instead
5952: $items = &escape($store).'=&';
5953: } elsif (ref($store) eq 'SCALAR') {
5954: $items = &escape($$store).'=&';
5955: } elsif (ref($store) eq 'ARRAY') {
5956: $items = join('=&',map {&escape($_);} @{$store});
5957: } elsif (ref($store) eq 'HASH') {
5958: while (my($key,$value) = each(%{$store})) {
5959: $items.= &escape($key).'='.&escape($value).'&';
5960: }
5961: }
5962: $items=~s/\&$//;
1.627 albertel 5963: if ($critical) {
5964: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5965: } else {
5966: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5967: }
1.449 matthew 5968: }
5969:
1.12 www 5970: # --------------------------------------------------------------- put interface
5971:
5972: sub put {
1.134 albertel 5973: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5974: if (!$udomain) { $udomain=$env{'user.domain'}; }
5975: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5976: my $uhome=&homeserver($uname,$udomain);
1.12 www 5977: my $items='';
1.800 albertel 5978: foreach my $item (keys(%$storehash)) {
5979: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5980: }
1.12 www 5981: $items=~s/\&$//;
1.134 albertel 5982: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5983: }
5984:
1.631 albertel 5985: # ------------------------------------------------------------ newput interface
5986:
5987: sub newput {
5988: my ($namespace,$storehash,$udomain,$uname)=@_;
5989: if (!$udomain) { $udomain=$env{'user.domain'}; }
5990: if (!$uname) { $uname=$env{'user.name'}; }
5991: my $uhome=&homeserver($uname,$udomain);
5992: my $items='';
5993: foreach my $key (keys(%$storehash)) {
5994: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5995: }
5996: $items=~s/\&$//;
5997: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5998: }
5999:
6000: # --------------------------------------------------------- putstore interface
6001:
1.524 raeburn 6002: sub putstore {
1.1172.2.59 raeburn 6003: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6004: if (!$udomain) { $udomain=$env{'user.domain'}; }
6005: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6006: my $uhome=&homeserver($uname,$udomain);
6007: my $items='';
1.715 albertel 6008: foreach my $key (keys(%$storehash)) {
6009: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6010: }
1.715 albertel 6011: $items=~s/\&$//;
1.716 albertel 6012: my $esc_symb=&escape($symb);
6013: my $esc_v=&escape($version);
1.715 albertel 6014: my $reply =
1.716 albertel 6015: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6016: $uhome);
1.1172.2.59 raeburn 6017: if (($tolog) && ($reply eq 'ok')) {
6018: my $namevalue='';
6019: foreach my $key (keys(%{$storehash})) {
6020: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6021: }
6022: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6023: '&host='.&escape($perlvar{'lonHostID'}).
6024: '&version='.$esc_v.
6025: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6026: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6027: }
1.715 albertel 6028: if ($reply eq 'unknown_cmd') {
1.716 albertel 6029: # gfall back to way things use to be done
1.715 albertel 6030: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6031: $uname);
1.524 raeburn 6032: }
1.715 albertel 6033: return $reply;
6034: }
6035:
6036: sub old_putstore {
1.716 albertel 6037: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6038: if (!$udomain) { $udomain=$env{'user.domain'}; }
6039: if (!$uname) { $uname=$env{'user.name'}; }
6040: my $uhome=&homeserver($uname,$udomain);
6041: my %newstorehash;
1.800 albertel 6042: foreach my $item (keys(%$storehash)) {
6043: my $key = $version.':'.&escape($symb).':'.$item;
6044: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6045: }
6046: my $items='';
6047: my %allitems = ();
1.800 albertel 6048: foreach my $item (keys(%newstorehash)) {
6049: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6050: my $key = $1.':keys:'.$2;
6051: $allitems{$key} .= $3.':';
6052: }
1.800 albertel 6053: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6054: }
1.800 albertel 6055: foreach my $item (keys(%allitems)) {
6056: $allitems{$item} =~ s/\:$//;
6057: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6058: }
6059: $items=~s/\&$//;
6060: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6061: }
6062:
1.47 www 6063: # ------------------------------------------------------ critical put interface
6064:
6065: sub cput {
1.134 albertel 6066: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6067: if (!$udomain) { $udomain=$env{'user.domain'}; }
6068: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6069: my $uhome=&homeserver($uname,$udomain);
1.47 www 6070: my $items='';
1.800 albertel 6071: foreach my $item (keys(%$storehash)) {
6072: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6073: }
1.47 www 6074: $items=~s/\&$//;
1.134 albertel 6075: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6076: }
6077:
6078: # -------------------------------------------------------------- eget interface
6079:
6080: sub eget {
1.133 albertel 6081: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6082: my $items='';
1.800 albertel 6083: foreach my $item (@$storearr) {
6084: $items.=&escape($item).'&';
1.191 harris41 6085: }
1.12 www 6086: $items=~s/\&$//;
1.620 albertel 6087: if (!$udomain) { $udomain=$env{'user.domain'}; }
6088: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6089: my $uhome=&homeserver($uname,$udomain);
6090: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6091: my @pairs=split(/\&/,$rep);
6092: my %returnhash=();
1.42 www 6093: my $i=0;
1.800 albertel 6094: foreach my $item (@$storearr) {
6095: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6096: $i++;
1.191 harris41 6097: }
1.12 www 6098: return %returnhash;
6099: }
6100:
1.667 albertel 6101: # ------------------------------------------------------------ tmpput interface
6102: sub tmpput {
1.802 raeburn 6103: my ($storehash,$server,$context)=@_;
1.667 albertel 6104: my $items='';
1.800 albertel 6105: foreach my $item (keys(%$storehash)) {
6106: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6107: }
6108: $items=~s/\&$//;
1.802 raeburn 6109: if (defined($context)) {
6110: $items .= ':'.&escape($context);
6111: }
1.667 albertel 6112: return &reply("tmpput:$items",$server);
6113: }
6114:
6115: # ------------------------------------------------------------ tmpget interface
6116: sub tmpget {
1.688 albertel 6117: my ($token,$server)=@_;
6118: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6119: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6120: my %returnhash;
6121: foreach my $item (split(/\&/,$rep)) {
6122: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6123: next if ($key =~ /^error: 2 /);
1.667 albertel 6124: $returnhash{&unescape($key)}=&thaw_unescape($value);
6125: }
6126: return %returnhash;
6127: }
6128:
1.1113 raeburn 6129: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6130: sub tmpdel {
6131: my ($token,$server)=@_;
6132: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6133: return &reply("tmpdel:$token",$server);
6134: }
6135:
1.1172.2.13 raeburn 6136: # ------------------------------------------------------------ get_timebased_id
6137:
6138: sub get_timebased_id {
6139: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6140: $maxtries) = @_;
6141: my ($newid,$error,$dellock);
6142: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6143: return ('','ok','invalid call to get suffix');
6144: }
6145:
6146: # set defaults for any optional args for which values were not supplied
6147: if ($who eq '') {
6148: $who = $env{'user.name'}.':'.$env{'user.domain'};
6149: }
6150: if (!$locktries) {
6151: $locktries = 3;
6152: }
6153: if (!$maxtries) {
6154: $maxtries = 10;
6155: }
6156:
6157: if (($cdom eq '') || ($cnum eq '')) {
6158: if ($env{'request.course.id'}) {
6159: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6160: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6161: }
6162: if (($cdom eq '') || ($cnum eq '')) {
6163: return ('','ok','call to get suffix not in course context');
6164: }
6165: }
6166:
6167: # construct locking item
6168: my $lockhash = {
6169: $prefix."\0".'locked_'.$keyid => $who,
6170: };
6171: my $tries = 0;
6172:
6173: # attempt to get lock on nohist_$namespace file
6174: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6175: while (($gotlock ne 'ok') && $tries <$locktries) {
6176: $tries ++;
6177: sleep 1;
6178: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6179: }
6180:
6181: # attempt to get unique identifier, based on current timestamp
6182: if ($gotlock eq 'ok') {
6183: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6184: my $id = time;
6185: $newid = $id;
1.1172.2.56 raeburn 6186: if ($idtype eq 'addcode') {
6187: $newid .= &sixnum_code();
6188: }
1.1172.2.13 raeburn 6189: my $idtries = 0;
6190: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6191: if ($idtype eq 'concat') {
6192: $newid = $id.$idtries;
1.1172.2.56 raeburn 6193: } elsif ($idtype eq 'addcode') {
6194: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6195: } else {
6196: $newid ++;
6197: }
6198: $idtries ++;
6199: }
6200: if (!exists($inuse{$prefix."\0".$newid})) {
6201: my %new_item = (
6202: $prefix."\0".$newid => $who,
6203: );
6204: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6205: $cdom,$cnum);
6206: if ($putresult ne 'ok') {
6207: undef($newid);
6208: $error = 'error saving new item: '.$putresult;
6209: }
6210: } else {
1.1172.2.56 raeburn 6211: undef($newid);
1.1172.2.13 raeburn 6212: $error = ('error: no unique suffix available for the new item ');
6213: }
6214: # remove lock
6215: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6216: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6217: } else {
6218: $error = "error: could not obtain lockfile\n";
6219: $dellock = 'ok';
1.1172.2.58 raeburn 6220: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6221: $dellock = 'nolock';
6222: }
1.1172.2.13 raeburn 6223: }
6224: return ($newid,$dellock,$error);
6225: }
6226:
1.1172.2.56 raeburn 6227: sub sixnum_code {
6228: my $code;
6229: for (0..6) {
6230: $code .= int( rand(9) );
6231: }
6232: return $code;
6233: }
6234:
1.765 albertel 6235: # -------------------------------------------------- portfolio access checking
6236:
6237: sub portfolio_access {
1.766 albertel 6238: my ($requrl) = @_;
1.765 albertel 6239: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6240: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6241: if ($result) {
6242: my %setters;
6243: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6244: my ($startblock,$endblock) =
6245: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6246: if ($startblock && $endblock) {
6247: return 'B';
6248: }
6249: } else {
6250: my ($startblock,$endblock) =
6251: &Apache::loncommon::blockcheck(\%setters,'port');
6252: if ($startblock && $endblock) {
6253: return 'B';
6254: }
6255: }
6256: }
1.765 albertel 6257: if ($result eq 'ok') {
1.766 albertel 6258: return 'F';
1.765 albertel 6259: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6260: return 'A';
1.765 albertel 6261: }
1.766 albertel 6262: return '';
1.765 albertel 6263: }
6264:
6265: sub get_portfolio_access {
1.767 albertel 6266: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6267:
6268: if (!ref($access_hash)) {
6269: my $current_perms = &get_portfile_permissions($udom,$unum);
6270: my %access_controls = &get_access_controls($current_perms,$group,
6271: $file_name);
6272: $access_hash = $access_controls{$file_name};
6273: }
6274:
1.765 albertel 6275: my ($public,$guest,@domains,@users,@courses,@groups);
6276: my $now = time;
6277: if (ref($access_hash) eq 'HASH') {
6278: foreach my $key (keys(%{$access_hash})) {
6279: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6280: if ($start > $now) {
6281: next;
6282: }
6283: if ($end && $end<$now) {
6284: next;
6285: }
6286: if ($scope eq 'public') {
6287: $public = $key;
6288: last;
6289: } elsif ($scope eq 'guest') {
6290: $guest = $key;
6291: } elsif ($scope eq 'domains') {
6292: push(@domains,$key);
6293: } elsif ($scope eq 'users') {
6294: push(@users,$key);
6295: } elsif ($scope eq 'course') {
6296: push(@courses,$key);
6297: } elsif ($scope eq 'group') {
6298: push(@groups,$key);
6299: }
6300: }
6301: if ($public) {
6302: return 'ok';
6303: }
6304: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6305: if ($guest) {
6306: return $guest;
6307: }
6308: } else {
6309: if (@domains > 0) {
6310: foreach my $domkey (@domains) {
6311: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6312: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6313: return 'ok';
6314: }
6315: }
6316: }
6317: }
6318: if (@users > 0) {
6319: foreach my $userkey (@users) {
1.865 raeburn 6320: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6321: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6322: if (ref($item) eq 'HASH') {
6323: if (($item->{'uname'} eq $env{'user.name'}) &&
6324: ($item->{'udom'} eq $env{'user.domain'})) {
6325: return 'ok';
6326: }
6327: }
6328: }
6329: }
1.765 albertel 6330: }
6331: }
6332: my %roleshash;
6333: my @courses_and_groups = @courses;
6334: push(@courses_and_groups,@groups);
6335: if (@courses_and_groups > 0) {
6336: my (%allgroups,%allroles);
6337: my ($start,$end,$role,$sec,$group);
6338: foreach my $envkey (%env) {
1.1060 raeburn 6339: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6340: my $cid = $2.'_'.$3;
6341: if ($1 eq 'gr') {
6342: $group = $4;
6343: $allgroups{$cid}{$group} = $env{$envkey};
6344: } else {
6345: if ($4 eq '') {
6346: $sec = 'none';
6347: } else {
6348: $sec = $4;
6349: }
6350: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6351: }
1.811 albertel 6352: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6353: my $cid = $2.'_'.$3;
6354: if ($4 eq '') {
6355: $sec = 'none';
6356: } else {
6357: $sec = $4;
6358: }
6359: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6360: }
6361: }
6362: if (keys(%allroles) == 0) {
6363: return;
6364: }
6365: foreach my $key (@courses_and_groups) {
6366: my %content = %{$$access_hash{$key}};
6367: my $cnum = $content{'number'};
6368: my $cdom = $content{'domain'};
6369: my $cid = $cdom.'_'.$cnum;
6370: if (!exists($allroles{$cid})) {
6371: next;
6372: }
6373: foreach my $role_id (keys(%{$content{'roles'}})) {
6374: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6375: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6376: my @status = @{$content{'roles'}{$role_id}{'access'}};
6377: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6378: foreach my $role (keys(%{$allroles{$cid}})) {
6379: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6380: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6381: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6382: if (grep/^all$/,@sections) {
6383: return 'ok';
6384: } else {
6385: if (grep/^$sec$/,@sections) {
6386: return 'ok';
6387: }
6388: }
6389: }
6390: }
6391: if (keys(%{$allgroups{$cid}}) == 0) {
6392: if (grep/^none$/,@groups) {
6393: return 'ok';
6394: }
6395: } else {
6396: if (grep/^all$/,@groups) {
6397: return 'ok';
6398: }
6399: foreach my $group (keys(%{$allgroups{$cid}})) {
6400: if (grep/^$group$/,@groups) {
6401: return 'ok';
6402: }
6403: }
6404: }
6405: }
6406: }
6407: }
6408: }
6409: }
6410: if ($guest) {
6411: return $guest;
6412: }
6413: }
6414: }
6415: return;
6416: }
6417:
6418: sub course_group_datechecker {
6419: my ($dates,$now,$status) = @_;
6420: my ($start,$end) = split(/\./,$dates);
6421: if (!$start && !$end) {
6422: return 'ok';
6423: }
6424: if (grep/^active$/,@{$status}) {
6425: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6426: return 'ok';
6427: }
6428: }
6429: if (grep/^previous$/,@{$status}) {
6430: if ($end > $now ) {
6431: return 'ok';
6432: }
6433: }
6434: if (grep/^future$/,@{$status}) {
6435: if ($start > $now) {
6436: return 'ok';
6437: }
6438: }
6439: return;
6440: }
6441:
6442: sub parse_portfolio_url {
6443: my ($url) = @_;
6444:
6445: my ($type,$udom,$unum,$group,$file_name);
6446:
1.823 albertel 6447: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6448: $type = 1;
6449: $udom = $1;
6450: $unum = $2;
6451: $file_name = $3;
1.823 albertel 6452: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6453: $type = 2;
6454: $udom = $1;
6455: $unum = $2;
6456: $group = $3;
6457: $file_name = $3.'/'.$4;
6458: }
6459: if (wantarray) {
6460: return ($type,$udom,$unum,$file_name,$group);
6461: }
6462: return $type;
6463: }
6464:
6465: sub is_portfolio_url {
6466: my ($url) = @_;
6467: return scalar(&parse_portfolio_url($url));
6468: }
6469:
1.798 raeburn 6470: sub is_portfolio_file {
6471: my ($file) = @_;
1.820 raeburn 6472: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6473: return 1;
6474: }
6475: return;
6476: }
6477:
1.976 raeburn 6478: sub usertools_access {
1.1084 raeburn 6479: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6480: my ($access,%tools);
6481: if ($context eq '') {
6482: $context = 'tools';
6483: }
6484: if ($context eq 'requestcourses') {
6485: %tools = (
6486: official => 1,
6487: unofficial => 1,
1.1006 raeburn 6488: community => 1,
1.1172.2.37 raeburn 6489: textbook => 1,
1.985 raeburn 6490: );
1.1172.2.9 raeburn 6491: } elsif ($context eq 'requestauthor') {
6492: %tools = (
6493: requestauthor => 1,
6494: );
1.985 raeburn 6495: } else {
6496: %tools = (
6497: aboutme => 1,
6498: blog => 1,
1.1172.2.6 raeburn 6499: webdav => 1,
1.985 raeburn 6500: portfolio => 1,
6501: );
6502: }
1.976 raeburn 6503: return if (!defined($tools{$tool}));
6504:
1.1172.2.35 raeburn 6505: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6506: $udom = $env{'user.domain'};
6507: $uname = $env{'user.name'};
6508: }
6509:
1.978 raeburn 6510: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6511: if ($action ne 'reload') {
1.985 raeburn 6512: if ($context eq 'requestcourses') {
6513: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6514: } elsif ($context eq 'requestauthor') {
6515: return $env{'environment.canrequest.author'};
1.985 raeburn 6516: } else {
6517: return $env{'environment.availabletools.'.$tool};
6518: }
6519: }
1.976 raeburn 6520: }
6521:
1.1172.2.9 raeburn 6522: my ($toolstatus,$inststatus,$envkey);
6523: if ($context eq 'requestauthor') {
6524: $envkey = $context;
6525: } else {
6526: $envkey = $context.'.'.$tool;
6527: }
1.976 raeburn 6528:
1.985 raeburn 6529: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6530: ($action ne 'reload')) {
1.1172.2.9 raeburn 6531: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6532: $inststatus = $env{'environment.inststatus'};
6533: } else {
1.1084 raeburn 6534: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6535: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6536: $inststatus = $userenvref->{'inststatus'};
6537: } else {
1.1172.2.9 raeburn 6538: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6539: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6540: $inststatus = $userenv{'inststatus'};
6541: }
1.976 raeburn 6542: }
6543:
6544: if ($toolstatus ne '') {
6545: if ($toolstatus) {
6546: $access = 1;
6547: } else {
6548: $access = 0;
6549: }
6550: return $access;
6551: }
6552:
1.1084 raeburn 6553: my ($is_adv,%domdef);
6554: if (ref($is_advref) eq 'HASH') {
6555: $is_adv = $is_advref->{'is_adv'};
6556: } else {
6557: $is_adv = &is_advanced_user($udom,$uname);
6558: }
6559: if (ref($domdefref) eq 'HASH') {
6560: %domdef = %{$domdefref};
6561: } else {
6562: %domdef = &get_domain_defaults($udom);
6563: }
1.976 raeburn 6564: if (ref($domdef{$tool}) eq 'HASH') {
6565: if ($is_adv) {
6566: if ($domdef{$tool}{'_LC_adv'} ne '') {
6567: if ($domdef{$tool}{'_LC_adv'}) {
6568: $access = 1;
6569: } else {
6570: $access = 0;
6571: }
6572: return $access;
6573: }
6574: }
6575: if ($inststatus ne '') {
6576: my ($hasaccess,$hasnoaccess);
6577: foreach my $affiliation (split(/:/,$inststatus)) {
6578: if ($domdef{$tool}{$affiliation} ne '') {
6579: if ($domdef{$tool}{$affiliation}) {
6580: $hasaccess = 1;
6581: } else {
6582: $hasnoaccess = 1;
6583: }
6584: }
6585: }
6586: if ($hasaccess || $hasnoaccess) {
6587: if ($hasaccess) {
6588: $access = 1;
6589: } elsif ($hasnoaccess) {
6590: $access = 0;
6591: }
6592: return $access;
6593: }
6594: } else {
6595: if ($domdef{$tool}{'default'} ne '') {
6596: if ($domdef{$tool}{'default'}) {
6597: $access = 1;
6598: } elsif ($domdef{$tool}{'default'} == 0) {
6599: $access = 0;
6600: }
6601: return $access;
6602: }
6603: }
6604: } else {
1.1172.2.6 raeburn 6605: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6606: $access = 1;
6607: } else {
6608: $access = 0;
6609: }
1.976 raeburn 6610: return $access;
6611: }
6612: }
6613:
1.1050 raeburn 6614: sub is_course_owner {
6615: my ($cdom,$cnum,$udom,$uname) = @_;
6616: if (($udom eq '') || ($uname eq '')) {
6617: $udom = $env{'user.domain'};
6618: $uname = $env{'user.name'};
6619: }
6620: unless (($udom eq '') || ($uname eq '')) {
6621: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6622: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6623: return 1;
6624: } else {
6625: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6626: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6627: return 1;
6628: }
6629: }
6630: }
6631: }
6632: return;
6633: }
6634:
1.976 raeburn 6635: sub is_advanced_user {
6636: my ($udom,$uname) = @_;
1.1085 raeburn 6637: if ($udom ne '' && $uname ne '') {
6638: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6639: if (wantarray) {
6640: return ($env{'user.adv'},$env{'user.author'});
6641: } else {
6642: return $env{'user.adv'};
6643: }
1.1085 raeburn 6644: }
6645: }
1.976 raeburn 6646: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6647: my %allroles;
1.1128 raeburn 6648: my ($is_adv,$is_author);
1.976 raeburn 6649: foreach my $role (keys(%roleshash)) {
6650: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6651: my $area = '/'.$tdomain.'/'.$trest;
6652: if ($sec ne '') {
6653: $area .= '/'.$sec;
6654: }
6655: if (($area ne '') && ($trole ne '')) {
6656: my $spec=$trole.'.'.$area;
6657: if ($trole =~ /^cr\//) {
6658: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6659: } elsif ($trole ne 'gr') {
6660: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6661: }
1.1128 raeburn 6662: if ($trole eq 'au') {
6663: $is_author = 1;
6664: }
1.976 raeburn 6665: }
6666: }
6667: foreach my $role (keys(%allroles)) {
6668: last if ($is_adv);
6669: foreach my $item (split(/:/,$allroles{$role})) {
6670: if ($item ne '') {
6671: my ($privilege,$restrictions)=split(/&/,$item);
6672: if ($privilege eq 'adv') {
6673: $is_adv = 1;
6674: last;
6675: }
6676: }
6677: }
6678: }
1.1128 raeburn 6679: if (wantarray) {
6680: return ($is_adv,$is_author);
6681: }
1.976 raeburn 6682: return $is_adv;
6683: }
1.798 raeburn 6684:
1.1035 raeburn 6685: sub check_can_request {
1.1036 raeburn 6686: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6687: my $canreq = 0;
6688: my ($types,$typename) = &Apache::loncommon::course_types();
6689: my @options = ('approval','validate','autolimit');
6690: my $optregex = join('|',@options);
6691: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6692: foreach my $type (@{$types}) {
6693: if (&usertools_access($env{'user.name'},
6694: $env{'user.domain'},
6695: $type,undef,'requestcourses')) {
6696: $canreq ++;
1.1036 raeburn 6697: if (ref($request_domains) eq 'HASH') {
6698: push(@{$request_domains->{$type}},$env{'user.domain'});
6699: }
1.1035 raeburn 6700: if ($dom eq $env{'user.domain'}) {
6701: $can_request->{$type} = 1;
6702: }
6703: }
6704: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6705: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6706: if (@curr > 0) {
1.1036 raeburn 6707: foreach my $item (@curr) {
6708: if (ref($request_domains) eq 'HASH') {
6709: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6710: if ($otherdom ne '') {
6711: if (ref($request_domains->{$type}) eq 'ARRAY') {
6712: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6713: push(@{$request_domains->{$type}},$otherdom);
6714: }
6715: } else {
6716: push(@{$request_domains->{$type}},$otherdom);
6717: }
6718: }
6719: }
6720: }
6721: unless($dom eq $env{'user.domain'}) {
6722: $canreq ++;
1.1035 raeburn 6723: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6724: $can_request->{$type} = 1;
6725: }
6726: }
6727: }
6728: }
6729: }
6730: }
6731: return $canreq;
6732: }
6733:
1.341 www 6734: # ---------------------------------------------- Custom access rule evaluation
6735:
6736: sub customaccess {
6737: my ($priv,$uri)=@_;
1.807 albertel 6738: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6739: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6740: $udom = &LONCAPA::clean_domain($udom);
6741: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6742: my $access=0;
1.800 albertel 6743: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6744: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6745: if ($type eq 'user') {
6746: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6747: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6748: if ($tdom) {
6749: if ($tdom ne $env{'user.domain'}) { next; }
6750: }
1.896 albertel 6751: if ($tuname) {
6752: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6753: }
6754: $access=($effect eq 'allow');
6755: last;
6756: }
6757: } else {
6758: if ($role) {
6759: if ($role ne $urole) { next; }
6760: }
6761: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6762: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6763: if ($tdom) {
6764: if ($tdom ne $udom) { next; }
6765: }
6766: if ($tcrs) {
6767: if ($tcrs ne $ucrs) { next; }
6768: }
6769: if ($tsec) {
6770: if ($tsec ne $usec) { next; }
6771: }
6772: $access=($effect eq 'allow');
6773: last;
6774: }
6775: if ($realm eq '' && $role eq '') {
6776: $access=($effect eq 'allow');
6777: }
1.402 bowersj2 6778: }
1.341 www 6779: }
6780: return $access;
6781: }
6782:
1.103 harris41 6783: # ------------------------------------------------- Check for a user privilege
1.12 www 6784:
6785: sub allowed {
1.1172.2.65 raeburn 6786: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6787: my $ver_orguri=$uri;
1.439 www 6788: $uri=&deversion($uri);
1.152 www 6789: my $orguri=$uri;
1.52 www 6790: $uri=&declutter($uri);
1.809 raeburn 6791:
1.810 raeburn 6792: if ($priv eq 'evb') {
6793: # Evade communication block restrictions for specified role in a course
6794: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6795: return $1;
6796: } else {
6797: return;
6798: }
6799: }
6800:
1.620 albertel 6801: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6802: # Free bre access to adm and meta resources
1.775 albertel 6803: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6804: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6805: && ($priv eq 'bre')) {
1.14 www 6806: return 'F';
1.159 www 6807: }
6808:
1.545 banghart 6809: # Free bre access to user's own portfolio contents
1.714 raeburn 6810: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6811: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6812: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6813: my %setters;
6814: my ($startblock,$endblock) =
6815: &Apache::loncommon::blockcheck(\%setters,'port');
6816: if ($startblock && $endblock) {
6817: return 'B';
6818: } else {
6819: return 'F';
6820: }
1.545 banghart 6821: }
6822:
1.762 raeburn 6823: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6824: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6825: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6826: if (exists($env{'request.course.id'})) {
6827: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6828: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6829: if (($domain eq $cdom) && ($name eq $cnum)) {
6830: my $courseprivid=$env{'request.course.id'};
6831: $courseprivid=~s/\_/\//;
6832: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6833: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6834: return $1;
1.762 raeburn 6835: } else {
6836: if ($env{'request.course.sec'}) {
6837: $courseprivid.='/'.$env{'request.course.sec'};
6838: }
6839: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6840: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6841: return $2;
6842: }
1.714 raeburn 6843: }
6844: }
6845: }
6846: }
6847:
1.159 www 6848: # Free bre to public access
6849:
6850: if ($priv eq 'bre') {
1.238 www 6851: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6852: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6853: return 'F';
6854: }
1.238 www 6855: if ($copyright eq 'priv') {
6856: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6857: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6858: return '';
6859: }
6860: }
6861: if ($copyright eq 'domain') {
6862: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6863: unless (($env{'user.domain'} eq $1) ||
6864: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6865: return '';
6866: }
1.262 matthew 6867: }
1.620 albertel 6868: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6869: # Library role, so allow browsing of resources in this domain.
6870: return 'F';
1.238 www 6871: }
1.341 www 6872: if ($copyright eq 'custom') {
6873: unless (&customaccess($priv,$uri)) { return ''; }
6874: }
1.14 www 6875: }
1.264 matthew 6876: # Domain coordinator is trying to create a course
1.620 albertel 6877: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6878: # uri is the requested domain in this case.
6879: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6880: # a role of dc for the domain in question.
1.620 albertel 6881: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6882: }
1.29 www 6883:
1.52 www 6884: my $thisallowed='';
6885: my $statecond=0;
6886: my $courseprivid='';
6887:
1.1039 raeburn 6888: my $ownaccess;
1.1043 raeburn 6889: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6890: if (($priv eq 'bro') && ($env{'user.author'})) {
6891: if ($uri eq '') {
6892: $ownaccess = 1;
6893: } else {
6894: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6895: my $udom = $env{'user.domain'};
6896: my $uname = $env{'user.name'};
6897: if ($uri =~ m{^\Q$udom\E/?$}) {
6898: $ownaccess = 1;
1.1040 raeburn 6899: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6900: unless ($uri =~ m{\.\./}) {
6901: $ownaccess = 1;
6902: }
6903: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6904: my $now = time;
6905: if ($uri =~ m{^([^/]+)/?$}) {
6906: my $adom = $1;
6907: foreach my $key (keys(%env)) {
1.1042 raeburn 6908: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6909: my ($start,$end) = split('.',$env{$key});
6910: if (($now >= $start) && (!$end || $end < $now)) {
6911: $ownaccess = 1;
6912: last;
6913: }
6914: }
6915: }
6916: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6917: my $adom = $1;
6918: my $aname = $2;
1.1042 raeburn 6919: foreach my $role ('ca','aa') {
6920: if ($env{"user.role.$role./$adom/$aname"}) {
6921: my ($start,$end) =
6922: split('.',$env{"user.role.$role./$adom/$aname"});
6923: if (($now >= $start) && (!$end || $end < $now)) {
6924: $ownaccess = 1;
6925: last;
6926: }
1.1039 raeburn 6927: }
6928: }
6929: }
6930: }
6931: }
6932: }
6933: }
6934:
1.52 www 6935: # Course
6936:
1.620 albertel 6937: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6938: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6939: $thisallowed.=$1;
6940: }
1.52 www 6941: }
1.29 www 6942:
1.52 www 6943: # Domain
6944:
1.620 albertel 6945: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6946: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6947: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6948: $thisallowed.=$1;
6949: }
1.12 www 6950: }
1.52 www 6951:
1.1141 raeburn 6952: # User who is not author or co-author might still be able to edit
6953: # resource of an author in the domain (e.g., if Domain Coordinator).
6954: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6955: (&allowed('mdc',$env{'request.course.id'}))) {
6956: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6957: $thisallowed.=$1;
6958: }
6959: }
6960:
1.52 www 6961: # Course: uri itself is a course
1.66 www 6962: my $courseuri=$uri;
6963: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6964: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6965:
1.620 albertel 6966: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6967: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6968: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6969: $thisallowed.=$1;
6970: }
1.12 www 6971: }
1.29 www 6972:
1.665 albertel 6973: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6974: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6975: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6976: $thisallowed='';
1.671 raeburn 6977: my ($match)=&is_on_map($uri);
6978: if ($match) {
6979: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6980: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 6981: my $value = $1;
6982: if ($noblockcheck) {
6983: $thisallowed.=$value;
1.1162 raeburn 6984: } else {
1.1172.2.65 raeburn 6985: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6986: if (@blockers > 0) {
6987: $thisallowed = 'B';
6988: } else {
6989: $thisallowed.=$value;
6990: }
1.1162 raeburn 6991: }
1.671 raeburn 6992: }
6993: } else {
1.705 albertel 6994: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6995: if ($refuri) {
6996: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6997: $thisallowed='F';
1.671 raeburn 6998: } else {
6999: $refuri=&declutter($refuri);
7000: my ($match) = &is_on_map($refuri);
7001: if ($match) {
1.1172.2.65 raeburn 7002: if ($noblockcheck) {
1.1162 raeburn 7003: $thisallowed='F';
1.1172.2.65 raeburn 7004: } else {
7005: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7006: if (@blockers > 0) {
7007: $thisallowed = 'B';
7008: } else {
7009: $thisallowed='F';
7010: }
1.1162 raeburn 7011: }
1.671 raeburn 7012: }
1.669 raeburn 7013: }
1.671 raeburn 7014: }
7015: }
1.314 www 7016: }
1.492 albertel 7017:
1.766 albertel 7018: if ($priv eq 'bre'
7019: && $thisallowed ne 'F'
7020: && $thisallowed ne '2'
7021: && &is_portfolio_url($uri)) {
7022: $thisallowed = &portfolio_access($uri);
7023: }
7024:
1.52 www 7025: # Full access at system, domain or course-wide level? Exit.
1.29 www 7026: if ($thisallowed=~/F/) {
7027: return 'F';
7028: }
7029:
1.52 www 7030: # If this is generating or modifying users, exit with special codes
1.29 www 7031:
1.643 www 7032: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7033: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7034: my ($audom,$auname)=split('/',$uri);
1.643 www 7035: # no author name given, so this just checks on the general right to make a co-author in this domain
7036: unless ($auname) { return $thisallowed; }
7037: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7038: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7039: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7040: ($audom ne $env{'request.role.domain'}))) { return ''; }
7041: }
1.52 www 7042: return $thisallowed;
7043: }
7044: #
1.103 harris41 7045: # Gathered so far: system, domain and course wide privileges
1.52 www 7046: #
7047: # Course: See if uri or referer is an individual resource that is part of
7048: # the course
7049:
1.620 albertel 7050: if ($env{'request.course.id'}) {
1.232 www 7051:
1.620 albertel 7052: $courseprivid=$env{'request.course.id'};
7053: if ($env{'request.course.sec'}) {
7054: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7055: }
7056: $courseprivid=~s/\_/\//;
7057: my $checkreferer=1;
1.232 www 7058: my ($match,$cond)=&is_on_map($uri);
7059: if ($match) {
7060: $statecond=$cond;
1.620 albertel 7061: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7062: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7063: my $value = $1;
7064: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7065: if ($noblockcheck) {
1.1162 raeburn 7066: $thisallowed.=$value;
1.1172.2.65 raeburn 7067: } else {
7068: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7069: if (@blockers > 0) {
7070: $thisallowed = 'B';
7071: } else {
7072: $thisallowed.=$value;
7073: }
1.1162 raeburn 7074: }
7075: } else {
7076: $thisallowed.=$value;
7077: }
1.52 www 7078: $checkreferer=0;
7079: }
1.29 www 7080: }
1.83 www 7081:
1.148 www 7082: if ($checkreferer) {
1.620 albertel 7083: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7084: unless ($refuri) {
1.800 albertel 7085: foreach my $key (keys(%env)) {
7086: if ($key=~/^httpref\..*\*/) {
7087: my $pattern=$key;
1.156 www 7088: $pattern=~s/^httpref\.\/res\///;
1.148 www 7089: $pattern=~s/\*/\[\^\/\]\+/g;
7090: $pattern=~s/\//\\\//g;
1.152 www 7091: if ($orguri=~/$pattern/) {
1.800 albertel 7092: $refuri=$env{$key};
1.148 www 7093: }
7094: }
1.191 harris41 7095: }
1.148 www 7096: }
1.232 www 7097:
1.148 www 7098: if ($refuri) {
1.152 www 7099: $refuri=&declutter($refuri);
1.232 www 7100: my ($match,$cond)=&is_on_map($refuri);
7101: if ($match) {
7102: my $refstatecond=$cond;
1.620 albertel 7103: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7104: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7105: my $value = $1;
7106: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7107: if ($noblockcheck) {
1.1162 raeburn 7108: $thisallowed.=$value;
1.1172.2.65 raeburn 7109: } else {
7110: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7111: if (@blockers > 0) {
7112: $thisallowed = 'B';
7113: } else {
7114: $thisallowed.=$value;
7115: }
1.1162 raeburn 7116: }
7117: } else {
7118: $thisallowed.=$value;
7119: }
1.53 www 7120: $uri=$refuri;
7121: $statecond=$refstatecond;
1.52 www 7122: }
7123: }
1.148 www 7124: }
1.29 www 7125: }
1.52 www 7126: }
1.29 www 7127:
1.52 www 7128: #
1.103 harris41 7129: # Gathered now: all privileges that could apply, and condition number
1.52 www 7130: #
7131: #
7132: # Full or no access?
7133: #
1.29 www 7134:
1.52 www 7135: if ($thisallowed=~/F/) {
7136: return 'F';
7137: }
1.29 www 7138:
1.52 www 7139: unless ($thisallowed) {
7140: return '';
7141: }
1.29 www 7142:
1.52 www 7143: # Restrictions exist, deal with them
7144: #
7145: # C:according to course preferences
7146: # R:according to resource settings
7147: # L:unless locked
7148: # X:according to user session state
7149: #
7150:
7151: # Possibly locked functionality, check all courses
1.54 www 7152: # Locks might take effect only after 10 minutes cache expiration for other
7153: # courses, and 2 minutes for current course
1.52 www 7154:
7155: my $envkey;
7156: if ($thisallowed=~/L/) {
1.1000 raeburn 7157: foreach $envkey (keys(%env)) {
1.54 www 7158: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7159: my $courseid=$2;
7160: my $roleid=$1.'.'.$2;
1.92 www 7161: $courseid=~s/^\///;
1.54 www 7162: my $expiretime=600;
1.620 albertel 7163: if ($env{'request.role'} eq $roleid) {
1.54 www 7164: $expiretime=120;
7165: }
7166: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7167: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7168: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7169: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7170: }
1.620 albertel 7171: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7172: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7173: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7174: &log($env{'user.domain'},$env{'user.name'},
7175: $env{'user.home'},
1.57 www 7176: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7177: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7178: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7179: return '';
7180: }
7181: }
1.620 albertel 7182: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7183: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7184: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7185: &log($env{'user.domain'},$env{'user.name'},
7186: $env{'user.home'},
1.57 www 7187: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7188: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7189: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7190: return '';
7191: }
7192: }
7193: }
1.29 www 7194: }
1.52 www 7195: }
7196:
7197: #
7198: # Rest of the restrictions depend on selected course
7199: #
7200:
1.620 albertel 7201: unless ($env{'request.course.id'}) {
1.766 albertel 7202: if ($thisallowed eq 'A') {
7203: return 'A';
1.814 raeburn 7204: } elsif ($thisallowed eq 'B') {
7205: return 'B';
1.766 albertel 7206: } else {
7207: return '1';
7208: }
1.52 www 7209: }
1.29 www 7210:
1.52 www 7211: #
7212: # Now user is definitely in a course
7213: #
1.53 www 7214:
7215:
7216: # Course preferences
7217:
7218: if ($thisallowed=~/C/) {
1.620 albertel 7219: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7220: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7221: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7222: =~/\Q$rolecode\E/) {
1.1103 raeburn 7223: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7224: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7225: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7226: $env{'request.course.id'});
7227: }
1.237 www 7228: return '';
7229: }
7230:
1.620 albertel 7231: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7232: =~/\Q$unamedom\E/) {
1.1103 raeburn 7233: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7234: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7235: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7236: $env{'request.course.id'});
7237: }
1.54 www 7238: return '';
7239: }
1.53 www 7240: }
7241:
7242: # Resource preferences
7243:
7244: if ($thisallowed=~/R/) {
1.620 albertel 7245: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7246: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7247: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7248: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7249: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7250: }
7251: return '';
1.54 www 7252: }
1.53 www 7253: }
1.30 www 7254:
1.246 www 7255: # Restricted by state or randomout?
1.30 www 7256:
1.52 www 7257: if ($thisallowed=~/X/) {
1.620 albertel 7258: if ($env{'acc.randomout'}) {
1.579 albertel 7259: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7260: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7261: return '';
7262: }
1.247 www 7263: }
7264: if (&condval($statecond)) {
1.52 www 7265: return '2';
7266: } else {
7267: return '';
7268: }
7269: }
1.30 www 7270:
1.766 albertel 7271: if ($thisallowed eq 'A') {
7272: return 'A';
1.814 raeburn 7273: } elsif ($thisallowed eq 'B') {
7274: return 'B';
1.766 albertel 7275: }
1.52 www 7276: return 'F';
1.232 www 7277: }
1.1162 raeburn 7278:
1.1172.2.13 raeburn 7279: # ------------------------------------------- Check construction space access
7280:
7281: sub constructaccess {
7282: my ($url,$setpriv)=@_;
7283:
7284: # We do not allow editing of previous versions of files
7285: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7286:
7287: # Get username and domain from URL
7288: my ($ownername,$ownerdomain,$ownerhome);
7289:
7290: ($ownerdomain,$ownername) =
7291: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7292:
7293: # The URL does not really point to any authorspace, forget it
7294: unless (($ownername) && ($ownerdomain)) { return ''; }
7295:
7296: # Now we need to see if the user has access to the authorspace of
7297: # $ownername at $ownerdomain
7298:
7299: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7300: # Real author for this?
7301: $ownerhome = $env{'user.home'};
7302: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7303: return ($ownername,$ownerdomain,$ownerhome);
7304: }
7305: } else {
7306: # Co-author for this?
7307: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7308: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7309: $ownerhome = &homeserver($ownername,$ownerdomain);
7310: return ($ownername,$ownerdomain,$ownerhome);
7311: }
7312: }
7313:
7314: # We don't have any access right now. If we are not possibly going to do anything about this,
7315: # we might as well leave
7316: unless ($setpriv) { return ''; }
7317:
7318: # Backdoor access?
7319: my $allowed=&allowed('eco',$ownerdomain);
7320: # Nope
7321: unless ($allowed) { return ''; }
7322: # Looks like we may have access, but could be locked by the owner of the construction space
7323: if ($allowed eq 'U') {
7324: my %blocked=&get('environment',['domcoord.author'],
7325: $ownerdomain,$ownername);
7326: # Is blocked by owner
7327: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7328: }
7329: if (($allowed eq 'F') || ($allowed eq 'U')) {
7330: # Grant temporary access
7331: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7332: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7333: if (!$update) { $update = $then; }
7334: my $refresh=$env{'user.refresh.time'};
7335: if (!$refresh) { $refresh = $update; }
7336: my $now = time;
7337: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7338: $now,'ca','constructaccess');
7339: $ownerhome = &homeserver($ownername,$ownerdomain);
7340: return($ownername,$ownerdomain,$ownerhome);
7341: }
7342: # No business here
7343: return '';
7344: }
7345:
1.1172.2.66 raeburn 7346: # ----------------------------------------------------------- Content Blocking
7347:
7348: {
7349: # Caches for faster Course Contents display where content blocking
7350: # is in operation (i.e., interval param set) for timed quiz.
7351: #
7352: # User for whom data are being temporarily cached.
7353: my $cacheduser='';
7354: # Cached blockers for this user (a hash of blocking items).
7355: my %cachedblockers=();
7356: # When the data were last cached.
7357: my $cachedlast='';
7358:
7359: sub load_all_blockers {
7360: my ($uname,$udom,$blocks)=@_;
7361: if (($uname ne '') && ($udom ne '')) {
7362: if (($cacheduser eq $uname.':'.$udom) &&
7363: (abs($cachedlast-time)<5)) {
7364: return;
7365: }
7366: }
7367: $cachedlast=time;
7368: $cacheduser=$uname.':'.$udom;
7369: %cachedblockers = &get_commblock_resources($blocks);
7370: }
7371:
1.1162 raeburn 7372: sub get_comm_blocks {
7373: my ($cdom,$cnum) = @_;
7374: if ($cdom eq '' || $cnum eq '') {
7375: return unless ($env{'request.course.id'});
7376: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7377: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7378: }
7379: my %commblocks;
7380: my $hashid=$cdom.'_'.$cnum;
7381: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7382: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7383: %commblocks = %{$blocksref};
7384: } else {
7385: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7386: my $cachetime = 600;
7387: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7388: }
7389: return %commblocks;
7390: }
7391:
1.1172.2.66 raeburn 7392: sub get_commblock_resources {
7393: my ($blocks) = @_;
7394: my %blockers = ();
7395: return %blockers unless ($env{'request.course.id'});
7396: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7397: my %commblocks;
7398: if (ref($blocks) eq 'HASH') {
7399: %commblocks = %{$blocks};
7400: } else {
7401: %commblocks = &get_comm_blocks();
7402: }
1.1172.2.66 raeburn 7403: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7404: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7405: return %blockers unless (ref($navmap));
7406: my $now = time;
1.1162 raeburn 7407: foreach my $block (keys(%commblocks)) {
7408: if ($block =~ /^(\d+)____(\d+)$/) {
7409: my ($start,$end) = ($1,$2);
7410: if ($start <= $now && $end >= $now) {
7411: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7412: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7413: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7414: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7415: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7416: }
7417: }
7418: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7419: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7420: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7421: }
7422: }
7423: }
7424: }
7425: }
7426: } elsif ($block =~ /^firstaccess____(.+)$/) {
7427: my $item = $1;
1.1163 raeburn 7428: my @to_test;
1.1162 raeburn 7429: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7430: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7431: my @interval;
7432: my $type = 'map';
7433: if ($item eq 'course') {
7434: $type = 'course';
7435: @interval=&EXT("resource.0.interval");
7436: } else {
7437: if ($item =~ /___\d+___/) {
7438: $type = 'resource';
7439: @interval=&EXT("resource.0.interval",$item);
7440: if (ref($navmap)) {
7441: my $res = $navmap->getBySymb($item);
7442: push(@to_test,$res);
7443: }
1.1162 raeburn 7444: } else {
1.1172.2.66 raeburn 7445: my $mapsymb = &symbread($item,1);
7446: if ($mapsymb) {
7447: if (ref($navmap)) {
7448: my $mapres = $navmap->getBySymb($mapsymb);
7449: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7450: foreach my $res (@to_test) {
7451: my $symb = $res->symb();
7452: next if ($symb eq $mapsymb);
7453: if ($symb ne '') {
7454: @interval=&EXT("resource.0.interval",$symb);
7455: if ($interval[1] eq 'map') {
7456: last;
1.1162 raeburn 7457: }
7458: }
7459: }
7460: }
7461: }
7462: }
1.1172.2.66 raeburn 7463: }
7464: if ($interval[0] =~ /^\d+$/) {
7465: my $first_access;
7466: if ($type eq 'resource') {
7467: $first_access=&get_first_access($interval[1],$item);
7468: } elsif ($type eq 'map') {
7469: $first_access=&get_first_access($interval[1],undef,$item);
7470: } else {
7471: $first_access=&get_first_access($interval[1]);
7472: }
7473: if ($first_access) {
7474: my $timesup = $first_access+$interval[0];
7475: if ($timesup > $now) {
7476: my $activeblock;
7477: foreach my $res (@to_test) {
7478: if ($res->answerable()) {
7479: $activeblock = 1;
7480: last;
7481: }
7482: }
7483: if ($activeblock) {
7484: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7485: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7486: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7487: }
7488: }
7489: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7490: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7491: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7492: }
1.1162 raeburn 7493: }
7494: }
7495: }
7496: }
7497: }
7498: }
7499: }
7500: }
7501: }
1.1172.2.66 raeburn 7502: return %blockers;
1.1162 raeburn 7503: }
7504:
1.1172.2.66 raeburn 7505: sub has_comm_blocking {
7506: my ($priv,$symb,$uri,$blocks) = @_;
7507: my @blockers;
7508: return unless ($env{'request.course.id'});
7509: return unless ($priv eq 'bre');
7510: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7511: return if ($env{'request.state'} eq 'construct');
7512: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7513: return unless (keys(%cachedblockers) > 0);
7514: my (%possibles,@symbs);
7515: if (!$symb) {
7516: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7517: }
1.1172.2.66 raeburn 7518: if ($symb) {
7519: @symbs = ($symb);
7520: } elsif (keys(%possibles)) {
7521: @symbs = keys(%possibles);
7522: }
7523: my $noblock;
7524: foreach my $symb (@symbs) {
7525: last if ($noblock);
7526: my ($map,$resid,$resurl)=&decode_symb($symb);
7527: foreach my $block (keys(%cachedblockers)) {
7528: if ($block =~ /^firstaccess____(.+)$/) {
7529: my $item = $1;
7530: if (($item eq $map) || ($item eq $symb)) {
7531: $noblock = 1;
7532: last;
7533: }
1.1162 raeburn 7534: }
1.1172.2.66 raeburn 7535: if (ref($cachedblockers{$block}) eq 'HASH') {
7536: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7537: if ($cachedblockers{$block}{'resources'}{$symb}) {
7538: unless (grep(/^\Q$block\E$/,@blockers)) {
7539: push(@blockers,$block);
7540: }
7541: }
7542: }
7543: }
7544: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7545: if ($cachedblockers{$block}{'maps'}{$map}) {
7546: unless (grep(/^\Q$block\E$/,@blockers)) {
7547: push(@blockers,$block);
7548: }
7549: }
1.1162 raeburn 7550: }
7551: }
7552: }
1.1172.2.66 raeburn 7553: return if ($noblock);
7554: return @blockers;
7555: }
1.1162 raeburn 7556: }
7557:
1.1172.2.66 raeburn 7558: # -------------------------------- Deversion and split uri into path an filename
7559:
1.1133 foxr 7560: #
1.1172.2.66 raeburn 7561: # Removes the version from a URI and
1.1133 foxr 7562: # splits it in to its filename and path to the filename.
7563: # Seems like File::Basename could have done this more clearly.
7564: # Parameters:
7565: # $uri - input URI
7566: # Returns:
7567: # Two element list consisting of
7568: # $pathname - the URI up to and excluding the trailing /
7569: # $filename - The part of the URI following the last /
7570: # NOTE:
7571: # Another realization of this is simply:
7572: # use File::Basename;
7573: # ...
7574: # $uri = shift;
7575: # $filename = basename($uri);
7576: # $path = dirname($uri);
7577: # return ($filename, $path);
7578: #
7579: # The implementation below is probably faster however.
7580: #
1.710 albertel 7581: sub split_uri_for_cond {
7582: my $uri=&deversion(&declutter(shift));
7583: my @uriparts=split(/\//,$uri);
7584: my $filename=pop(@uriparts);
7585: my $pathname=join('/',@uriparts);
7586: return ($pathname,$filename);
7587: }
1.232 www 7588: # --------------------------------------------------- Is a resource on the map?
7589:
7590: sub is_on_map {
1.710 albertel 7591: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7592: #Trying to find the conditional for the file
1.620 albertel 7593: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7594: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7595: if ($match) {
1.289 bowersj2 7596: return (1,$1);
7597: } else {
1.434 www 7598: return (0,0);
1.289 bowersj2 7599: }
1.12 www 7600: }
7601:
1.427 www 7602: # --------------------------------------------------------- Get symb from alias
7603:
7604: sub get_symb_from_alias {
7605: my $symb=shift;
7606: my ($map,$resid,$url)=&decode_symb($symb);
7607: # Already is a symb
7608: if ($url) { return $symb; }
7609: # Must be an alias
7610: my $aliassymb='';
7611: my %bighash;
1.620 albertel 7612: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7613: &GDBM_READER(),0640)) {
7614: my $rid=$bighash{'mapalias_'.$symb};
7615: if ($rid) {
7616: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7617: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7618: $resid,$bighash{'src_'.$rid});
1.427 www 7619: }
7620: untie %bighash;
7621: }
7622: return $aliassymb;
7623: }
7624:
1.12 www 7625: # ----------------------------------------------------------------- Define Role
7626:
7627: sub definerole {
7628: if (allowed('mcr','/')) {
7629: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7630: foreach my $role (split(':',$sysrole)) {
7631: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7632: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7633: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7634: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7635: return "refused:s:$crole&$cqual";
7636: }
7637: }
1.191 harris41 7638: }
1.800 albertel 7639: foreach my $role (split(':',$domrole)) {
7640: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7641: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7642: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7643: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7644: return "refused:d:$crole&$cqual";
7645: }
7646: }
1.191 harris41 7647: }
1.800 albertel 7648: foreach my $role (split(':',$courole)) {
7649: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7650: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7651: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7652: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7653: return "refused:c:$crole&$cqual";
7654: }
7655: }
1.191 harris41 7656: }
1.620 albertel 7657: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7658: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7659: "rolesdef_$rolename=".
7660: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7661: return reply($command,$env{'user.home'});
1.12 www 7662: } else {
7663: return 'refused';
7664: }
1.105 harris41 7665: }
7666:
7667: # ---------------- Make a metadata query against the network of library servers
7668:
7669: sub metadata_query {
1.1172.2.33 raeburn 7670: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7671: my %rhash;
1.845 albertel 7672: my %libserv = &all_library();
1.244 matthew 7673: my @server_list = (defined($server_array) ? @$server_array
7674: : keys(%libserv) );
7675: for my $server (@server_list) {
1.1172.2.33 raeburn 7676: my $domains = '';
7677: if (ref($domains_hash) eq 'HASH') {
7678: $domains = $domains_hash->{$server};
7679: }
1.118 harris41 7680: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7681: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7682: $rhash{$server}=$reply;
7683: }
7684: else {
7685: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7686: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7687: $server);
7688: $rhash{$server}=$reply;
7689: }
1.112 harris41 7690: }
1.118 harris41 7691: return \%rhash;
1.240 www 7692: }
7693:
7694: # ----------------------------------------- Send log queries and wait for reply
7695:
7696: sub log_query {
7697: my ($uname,$udom,$query,%filters)=@_;
7698: my $uhome=&homeserver($uname,$udom);
7699: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7700: my $uhost=&hostname($uhome);
1.800 albertel 7701: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7702: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7703: $uhome);
1.479 albertel 7704: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7705: return get_query_reply($queryid);
7706: }
7707:
1.818 raeburn 7708: # -------------------------- Update MySQL table for portfolio file
7709:
7710: sub update_portfolio_table {
1.821 raeburn 7711: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7712: if ($group ne '') {
7713: $file_name =~s /^\Q$group\E//;
7714: }
1.818 raeburn 7715: my $homeserver = &homeserver($uname,$udom);
7716: my $queryid=
1.821 raeburn 7717: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7718: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7719: my $reply = &get_query_reply($queryid);
7720: return $reply;
7721: }
7722:
1.899 raeburn 7723: # -------------------------- Update MySQL allusers table
7724:
7725: sub update_allusers_table {
7726: my ($uname,$udom,$names) = @_;
7727: my $homeserver = &homeserver($uname,$udom);
7728: my $queryid=
7729: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7730: 'lastname='.&escape($names->{'lastname'}).'%%'.
7731: 'firstname='.&escape($names->{'firstname'}).'%%'.
7732: 'middlename='.&escape($names->{'middlename'}).'%%'.
7733: 'generation='.&escape($names->{'generation'}).'%%'.
7734: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7735: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7736: return;
1.899 raeburn 7737: }
7738:
1.508 raeburn 7739: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7740:
7741: sub fetch_enrollment_query {
1.511 raeburn 7742: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7743: my $homeserver;
1.547 raeburn 7744: my $maxtries = 1;
1.508 raeburn 7745: if ($context eq 'automated') {
7746: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7747: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7748: } else {
7749: $homeserver = &homeserver($cnum,$dom);
7750: }
1.838 albertel 7751: my $host=&hostname($homeserver);
1.506 raeburn 7752: my $cmd = '';
1.1000 raeburn 7753: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7754: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7755: }
7756: $cmd =~ s/%%$//;
7757: $cmd = &escape($cmd);
7758: my $query = 'fetchenrollment';
1.620 albertel 7759: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7760: unless ($queryid=~/^\Q$host\E\_/) {
7761: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7762: return 'error: '.$queryid;
7763: }
1.506 raeburn 7764: my $reply = &get_query_reply($queryid);
1.547 raeburn 7765: my $tries = 1;
7766: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7767: $reply = &get_query_reply($queryid);
7768: $tries ++;
7769: }
1.526 raeburn 7770: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7771: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7772: } else {
1.901 albertel 7773: my @responses = split(/:/,$reply);
1.515 raeburn 7774: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7775: foreach my $line (@responses) {
7776: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7777: $$replyref{$key} = $value;
7778: }
7779: } else {
1.1117 foxr 7780: my $pathname = LONCAPA::tempdir();
1.800 albertel 7781: foreach my $line (@responses) {
7782: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7783: $$replyref{$key} = $value;
7784: if ($value > 0) {
1.800 albertel 7785: foreach my $item (@{$$affiliatesref{$key}}) {
7786: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7787: my $destname = $pathname.'/'.$filename;
7788: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7789: if ($xml_classlist =~ /^error/) {
7790: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7791: } else {
1.506 raeburn 7792: if ( open(FILE,">$destname") ) {
7793: print FILE &unescape($xml_classlist);
7794: close(FILE);
1.526 raeburn 7795: } else {
7796: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7797: }
7798: }
7799: }
7800: }
7801: }
7802: }
7803: return 'ok';
7804: }
7805: return 'error';
7806: }
7807:
1.242 www 7808: sub get_query_reply {
7809: my $queryid=shift;
1.1117 foxr 7810: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7811: my $reply='';
7812: for (1..100) {
7813: sleep 2;
7814: if (-e $replyfile.'.end') {
1.448 albertel 7815: if (open(my $fh,$replyfile)) {
1.904 albertel 7816: $reply = join('',<$fh>);
7817: close($fh);
1.240 www 7818: } else { return 'error: reply_file_error'; }
1.242 www 7819: return &unescape($reply);
7820: }
1.240 www 7821: }
1.242 www 7822: return 'timeout:'.$queryid;
1.240 www 7823: }
7824:
7825: sub courselog_query {
1.241 www 7826: #
7827: # possible filters:
7828: # url: url or symb
7829: # username
7830: # domain
7831: # action: view, submit, grade
7832: # start: timestamp
7833: # end: timestamp
7834: #
1.240 www 7835: my (%filters)=@_;
1.620 albertel 7836: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7837: if ($filters{'url'}) {
7838: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7839: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7840: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7841: }
1.620 albertel 7842: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7843: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7844: return &log_query($cname,$cdom,'courselog',%filters);
7845: }
7846:
7847: sub userlog_query {
1.858 raeburn 7848: #
7849: # possible filters:
7850: # action: log check role
7851: # start: timestamp
7852: # end: timestamp
7853: #
1.240 www 7854: my ($uname,$udom,%filters)=@_;
7855: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7856: }
7857:
1.506 raeburn 7858: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7859:
7860: sub auto_run {
1.508 raeburn 7861: my ($cnum,$cdom) = @_;
1.876 raeburn 7862: my $response = 0;
7863: my $settings;
7864: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7865: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7866: $settings = $domconfig{'autoenroll'};
7867: if ($settings->{'run'} eq '1') {
7868: $response = 1;
7869: }
7870: } else {
1.934 raeburn 7871: my $homeserver;
7872: if (&is_course($cdom,$cnum)) {
7873: $homeserver = &homeserver($cnum,$cdom);
7874: } else {
7875: $homeserver = &domain($cdom,'primary');
7876: }
7877: if ($homeserver ne 'no_host') {
7878: $response = &reply('autorun:'.$cdom,$homeserver);
7879: }
1.876 raeburn 7880: }
1.506 raeburn 7881: return $response;
7882: }
1.776 albertel 7883:
1.506 raeburn 7884: sub auto_get_sections {
1.508 raeburn 7885: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7886: my $homeserver;
7887: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7888: $homeserver = &homeserver($cnum,$cdom);
7889: }
7890: if (!defined($homeserver)) {
7891: if ($cdom =~ /^$match_domain$/) {
7892: $homeserver = &domain($cdom,'primary');
7893: }
7894: }
7895: my @secs;
7896: if (defined($homeserver)) {
7897: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7898: unless ($response eq 'refused') {
7899: @secs = split(/:/,$response);
7900: }
1.506 raeburn 7901: }
7902: return @secs;
7903: }
1.776 albertel 7904:
1.506 raeburn 7905: sub auto_new_course {
1.1099 raeburn 7906: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7907: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7908: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7909: return $response;
7910: }
1.776 albertel 7911:
1.506 raeburn 7912: sub auto_validate_courseID {
1.508 raeburn 7913: my ($cnum,$cdom,$inst_course_id) = @_;
7914: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7915: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7916: return $response;
7917: }
1.776 albertel 7918:
1.1007 raeburn 7919: sub auto_validate_instcode {
1.1020 raeburn 7920: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7921: my ($homeserver,$response);
7922: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7923: $homeserver = &homeserver($cnum,$cdom);
7924: }
7925: if (!defined($homeserver)) {
7926: if ($cdom =~ /^$match_domain$/) {
7927: $homeserver = &domain($cdom,'primary');
7928: }
7929: }
1.1065 raeburn 7930: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7931: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7932: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7933: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7934: }
7935:
1.506 raeburn 7936: sub auto_create_password {
1.873 raeburn 7937: my ($cnum,$cdom,$authparam,$udom) = @_;
7938: my ($homeserver,$response);
1.506 raeburn 7939: my $create_passwd = 0;
7940: my $authchk = '';
1.873 raeburn 7941: if ($udom =~ /^$match_domain$/) {
7942: $homeserver = &domain($udom,'primary');
7943: }
7944: if ($homeserver eq '') {
7945: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7946: $homeserver = &homeserver($cnum,$cdom);
7947: }
7948: }
7949: if ($homeserver eq '') {
7950: $authchk = 'nodomain';
1.506 raeburn 7951: } else {
1.873 raeburn 7952: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7953: if ($response eq 'refused') {
7954: $authchk = 'refused';
7955: } else {
1.901 albertel 7956: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7957: }
1.506 raeburn 7958: }
7959: return ($authparam,$create_passwd,$authchk);
7960: }
7961:
1.706 raeburn 7962: sub auto_photo_permission {
7963: my ($cnum,$cdom,$students) = @_;
7964: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7965: my ($outcome,$perm_reqd,$conditions) =
7966: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7967: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7968: return (undef,undef);
7969: }
1.706 raeburn 7970: return ($outcome,$perm_reqd,$conditions);
7971: }
7972:
7973: sub auto_checkphotos {
7974: my ($uname,$udom,$pid) = @_;
7975: my $homeserver = &homeserver($uname,$udom);
7976: my ($result,$resulttype);
7977: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7978: &escape($uname).':'.&escape($pid),
7979: $homeserver));
1.709 albertel 7980: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7981: return (undef,undef);
7982: }
1.706 raeburn 7983: if ($outcome) {
7984: ($result,$resulttype) = split(/:/,$outcome);
7985: }
7986: return ($result,$resulttype);
7987: }
7988:
7989: sub auto_photochoice {
7990: my ($cnum,$cdom) = @_;
7991: my $homeserver = &homeserver($cnum,$cdom);
7992: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7993: &escape($cdom),
7994: $homeserver)));
1.709 albertel 7995: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7996: return (undef,undef);
7997: }
1.706 raeburn 7998: return ($update,$comment);
7999: }
8000:
8001: sub auto_photoupdate {
8002: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8003: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8004: my $host=&hostname($homeserver);
1.706 raeburn 8005: my $cmd = '';
8006: my $maxtries = 1;
1.800 albertel 8007: foreach my $affiliate (keys(%{$affiliatesref})) {
8008: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8009: }
8010: $cmd =~ s/%%$//;
8011: $cmd = &escape($cmd);
8012: my $query = 'institutionalphotos';
8013: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8014: unless ($queryid=~/^\Q$host\E\_/) {
8015: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8016: return 'error: '.$queryid;
8017: }
8018: my $reply = &get_query_reply($queryid);
8019: my $tries = 1;
8020: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8021: $reply = &get_query_reply($queryid);
8022: $tries ++;
8023: }
8024: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8025: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8026: } else {
8027: my @responses = split(/:/,$reply);
8028: my $outcome = shift(@responses);
8029: foreach my $item (@responses) {
8030: my ($key,$value) = split(/=/,$item);
8031: $$photo{$key} = $value;
8032: }
8033: return $outcome;
8034: }
8035: return 'error';
8036: }
8037:
1.521 raeburn 8038: sub auto_instcode_format {
1.793 albertel 8039: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8040: $cat_order) = @_;
1.521 raeburn 8041: my $courses = '';
1.772 raeburn 8042: my @homeservers;
1.521 raeburn 8043: if ($caller eq 'global') {
1.841 albertel 8044: my %servers = &get_servers($codedom,'library');
8045: foreach my $tryserver (keys(%servers)) {
8046: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8047: push(@homeservers,$tryserver);
8048: }
1.584 raeburn 8049: }
1.1022 raeburn 8050: } elsif ($caller eq 'requests') {
8051: if ($codedom =~ /^$match_domain$/) {
8052: my $chome = &domain($codedom,'primary');
8053: unless ($chome eq 'no_host') {
8054: push(@homeservers,$chome);
8055: }
8056: }
1.521 raeburn 8057: } else {
1.772 raeburn 8058: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8059: }
1.793 albertel 8060: foreach my $code (keys(%{$instcodes})) {
8061: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8062: }
8063: chop($courses);
1.772 raeburn 8064: my $ok_response = 0;
8065: my $response;
8066: while (@homeservers > 0 && $ok_response == 0) {
8067: my $server = shift(@homeservers);
8068: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8069: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8070: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8071: split(/:/,$response);
1.772 raeburn 8072: %{$codes} = (%{$codes},&str2hash($codes_str));
8073: push(@{$codetitles},&str2array($codetitles_str));
8074: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8075: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8076: $ok_response = 1;
8077: }
8078: }
8079: if ($ok_response) {
1.521 raeburn 8080: return 'ok';
1.772 raeburn 8081: } else {
8082: return $response;
1.521 raeburn 8083: }
8084: }
8085:
1.792 raeburn 8086: sub auto_instcode_defaults {
8087: my ($domain,$returnhash,$code_order) = @_;
8088: my @homeservers;
1.841 albertel 8089:
8090: my %servers = &get_servers($domain,'library');
8091: foreach my $tryserver (keys(%servers)) {
8092: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8093: push(@homeservers,$tryserver);
8094: }
1.792 raeburn 8095: }
1.841 albertel 8096:
1.792 raeburn 8097: my $response;
1.841 albertel 8098: foreach my $server (@homeservers) {
1.792 raeburn 8099: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8100: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8101:
8102: foreach my $pair (split(/\&/,$response)) {
8103: my ($name,$value)=split(/\=/,$pair);
8104: if ($name eq 'code_order') {
8105: @{$code_order} = split(/\&/,&unescape($value));
8106: } else {
8107: $returnhash->{&unescape($name)}=&unescape($value);
8108: }
8109: }
8110: return 'ok';
1.792 raeburn 8111: }
1.841 albertel 8112:
8113: return $response;
1.1003 raeburn 8114: }
8115:
8116: sub auto_possible_instcodes {
1.1007 raeburn 8117: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8118: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8119: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8120: return;
8121: }
1.1003 raeburn 8122: my (@homeservers,$uhome);
8123: if (defined(&domain($domain,'primary'))) {
8124: $uhome=&domain($domain,'primary');
8125: push(@homeservers,&domain($domain,'primary'));
8126: } else {
8127: my %servers = &get_servers($domain,'library');
8128: foreach my $tryserver (keys(%servers)) {
8129: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8130: push(@homeservers,$tryserver);
8131: }
8132: }
8133: }
8134: my $response;
8135: foreach my $server (@homeservers) {
8136: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8137: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8138: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8139: split(':',$response);
8140: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8141: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8142: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8143: my ($name,$value)=split('=',$item);
8144: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8145: }
8146: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8147: my ($name,$value)=split('=',$item);
8148: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8149: }
8150: return 'ok';
8151: }
8152: return $response;
8153: }
1.792 raeburn 8154:
1.1010 raeburn 8155: sub auto_courserequest_checks {
8156: my ($dom) = @_;
1.1020 raeburn 8157: my ($homeserver,%validations);
8158: if ($dom =~ /^$match_domain$/) {
8159: $homeserver = &domain($dom,'primary');
8160: }
8161: unless ($homeserver eq 'no_host') {
8162: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8163: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8164: my @items = split(/&/,$response);
8165: foreach my $item (@items) {
8166: my ($key,$value) = split('=',$item);
8167: $validations{&unescape($key)} = &thaw_unescape($value);
8168: }
8169: }
8170: }
1.1010 raeburn 8171: return %validations;
8172: }
8173:
1.1020 raeburn 8174: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8175: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8176: my ($homeserver,$response);
8177: if ($dom =~ /^$match_domain$/) {
8178: $homeserver = &domain($dom,'primary');
8179: }
1.1172.2.43 raeburn 8180: unless ($homeserver eq 'no_host') {
8181: my $customdata;
8182: if (ref($custominfo) eq 'HASH') {
8183: $customdata = &freeze_escape($custominfo);
8184: }
1.1020 raeburn 8185: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8186: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8187: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8188: $customdata,$homeserver));
1.1020 raeburn 8189: }
8190: return $response;
8191: }
8192:
1.777 albertel 8193: sub auto_validate_class_sec {
1.918 raeburn 8194: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8195: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8196: my $ownerlist;
8197: if (ref($owners) eq 'ARRAY') {
8198: $ownerlist = join(',',@{$owners});
8199: } else {
8200: $ownerlist = $owners;
8201: }
1.773 raeburn 8202: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8203: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8204: return $response;
8205: }
8206:
1.1172.2.38 raeburn 8207: sub auto_crsreq_update {
8208: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8209: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8210: my ($homeserver,%crsreqresponse);
8211: if ($cdom =~ /^$match_domain$/) {
8212: $homeserver = &domain($cdom,'primary');
8213: }
8214: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8215: my $info;
8216: if (ref($inbound) eq 'HASH') {
8217: $info = &freeze_escape($inbound);
8218: }
8219: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8220: ':'.&escape($action).':'.&escape($ownername).':'.
8221: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8222: &escape($title).':'.&escape($code).':'.
8223: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8224: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8225: my @items = split(/&/,$response);
8226: foreach my $item (@items) {
8227: my ($key,$value) = split('=',$item);
8228: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8229: }
8230: }
8231: }
8232: return \%crsreqresponse;
8233: }
8234:
1.1172.2.68 raeburn 8235: sub check_instcode_cloning {
8236: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8237: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8238: return;
8239: }
8240: my $canclone;
8241: if (@{$code_order} > 0) {
8242: my $instcoderegexp ='^';
8243: my @clonecodes = split(/\&/,$cloner);
8244: foreach my $item (@{$code_order}) {
8245: if (grep(/^\Q$item\E=/,@clonecodes)) {
8246: foreach my $pair (@clonecodes) {
8247: my ($key,$val) = split(/\=/,$pair,2);
8248: $val = &unescape($val);
8249: if ($key eq $item) {
8250: $instcoderegexp .= '('.$val.')';
8251: last;
8252: }
8253: }
8254: } else {
8255: $instcoderegexp .= $codedefaults->{$item};
8256: }
8257: }
8258: $instcoderegexp .= '$';
8259: my (@from,@to);
8260: eval {
8261: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8262: (@to) = ($clonetocode =~ /$instcoderegexp/);
8263: };
8264: if ((@from > 0) && (@to > 0)) {
8265: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8266: if (!@diffs) {
8267: $canclone = 1;
8268: }
8269: }
8270: }
8271: return $canclone;
8272: }
8273:
8274: sub default_instcode_cloning {
8275: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8276: my (%codedefaults,@code_order,$canclone);
8277: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8278: %codedefaults = %{$codedefaultsref};
8279: @code_order = @{$codeorderref};
8280: } elsif ($clonedom) {
8281: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8282: }
8283: if (($domdefclone) && (@code_order)) {
8284: my @clonecodes = split(/\+/,$domdefclone);
8285: my $instcoderegexp ='^';
8286: foreach my $item (@code_order) {
8287: if (grep(/^\Q$item\E$/,@clonecodes)) {
8288: $instcoderegexp .= '('.$codedefaults{$item}.')';
8289: } else {
8290: $instcoderegexp .= $codedefaults{$item};
8291: }
8292: }
8293: $instcoderegexp .= '$';
8294: my (@from,@to);
8295: eval {
8296: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8297: (@to) = ($clonetocode =~ /$instcoderegexp/);
8298: };
8299: if ((@from > 0) && (@to > 0)) {
8300: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8301: if (!@diffs) {
8302: $canclone = 1;
8303: }
8304: }
8305: }
8306: return $canclone;
8307: }
8308:
1.679 raeburn 8309: # ------------------------------------------------------- Course Group routines
8310:
8311: sub get_coursegroups {
1.809 raeburn 8312: my ($cdom,$cnum,$group,$namespace) = @_;
8313: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8314: }
8315:
1.679 raeburn 8316: sub modify_coursegroup {
8317: my ($cdom,$cnum,$groupsettings) = @_;
8318: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8319: }
8320:
1.809 raeburn 8321: sub toggle_coursegroup_status {
8322: my ($cdom,$cnum,$group,$action) = @_;
8323: my ($from_namespace,$to_namespace);
8324: if ($action eq 'delete') {
8325: $from_namespace = 'coursegroups';
8326: $to_namespace = 'deleted_groups';
8327: } else {
8328: $from_namespace = 'deleted_groups';
8329: $to_namespace = 'coursegroups';
8330: }
8331: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8332: if (my $tmp = &error(%curr_group)) {
8333: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8334: return ('read error',$tmp);
8335: } else {
8336: my %savedsettings = %curr_group;
1.809 raeburn 8337: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8338: my $deloutcome;
8339: if ($result eq 'ok') {
1.809 raeburn 8340: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8341: } else {
8342: return ('write error',$result);
8343: }
8344: if ($deloutcome eq 'ok') {
8345: return 'ok';
8346: } else {
8347: return ('delete error',$deloutcome);
8348: }
8349: }
8350: }
8351:
1.679 raeburn 8352: sub modify_group_roles {
1.957 raeburn 8353: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8354: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8355: my $role = 'gr/'.&escape($userprivs);
8356: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8357: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8358: if ($result eq 'ok') {
8359: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8360: }
1.679 raeburn 8361: return $result;
8362: }
8363:
8364: sub modify_coursegroup_membership {
8365: my ($cdom,$cnum,$membership) = @_;
8366: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8367: return $result;
8368: }
8369:
1.682 raeburn 8370: sub get_active_groups {
8371: my ($udom,$uname,$cdom,$cnum) = @_;
8372: my $now = time;
8373: my %groups = ();
8374: foreach my $key (keys(%env)) {
1.811 albertel 8375: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8376: my ($start,$end) = split(/\./,$env{$key});
8377: if (($end!=0) && ($end<$now)) { next; }
8378: if (($start!=0) && ($start>$now)) { next; }
8379: if ($1 eq $cdom && $2 eq $cnum) {
8380: $groups{$3} = $env{$key} ;
8381: }
8382: }
8383: }
8384: return %groups;
8385: }
8386:
1.683 raeburn 8387: sub get_group_membership {
8388: my ($cdom,$cnum,$group) = @_;
8389: return(&dump('groupmembership',$cdom,$cnum,$group));
8390: }
8391:
8392: sub get_users_groups {
8393: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8394: my @usersgroups;
1.683 raeburn 8395: my $cachetime=1800;
8396:
8397: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8398: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8399: if (defined($cached)) {
1.734 albertel 8400: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8401: } else {
8402: $grouplist = '';
1.816 raeburn 8403: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8404: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8405: my $access_end = $env{'course.'.$courseid.
8406: '.default_enrollment_end_date'};
8407: my $now = time;
8408: foreach my $key (keys(%roleshash)) {
8409: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8410: my $group = $1;
8411: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8412: my $start = $2;
8413: my $end = $1;
8414: if ($start == -1) { next; } # deleted from group
8415: if (($start!=0) && ($start>$now)) { next; }
8416: if (($end!=0) && ($end<$now)) {
8417: if ($access_end && $access_end < $now) {
8418: if ($access_end - $end < 86400) {
8419: push(@usersgroups,$group);
1.733 raeburn 8420: }
8421: }
1.817 raeburn 8422: next;
1.733 raeburn 8423: }
1.817 raeburn 8424: push(@usersgroups,$group);
1.683 raeburn 8425: }
8426: }
8427: }
1.817 raeburn 8428: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8429: $grouplist = join(':',@usersgroups);
8430: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8431: }
1.733 raeburn 8432: return @usersgroups;
1.683 raeburn 8433: }
8434:
8435: sub devalidate_getgroups_cache {
8436: my ($udom,$uname,$cdom,$cnum)=@_;
8437: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8438:
1.683 raeburn 8439: my $hashid="$udom:$uname:$courseid";
8440: &devalidate_cache_new('getgroups',$hashid);
8441: }
8442:
1.12 www 8443: # ------------------------------------------------------------------ Plain Text
8444:
8445: sub plaintext {
1.988 raeburn 8446: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8447: if ($short =~ m{^cr/}) {
1.758 albertel 8448: return (split('/',$short))[-1];
8449: }
1.742 raeburn 8450: if (!defined($cid)) {
8451: $cid = $env{'request.course.id'};
8452: }
8453: my %rolenames = (
1.1008 raeburn 8454: Course => 'std',
8455: Community => 'alt1',
1.742 raeburn 8456: );
1.1037 raeburn 8457: if ($cid ne '') {
8458: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8459: unless ($forcedefault) {
8460: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8461: &Apache::lonlocal::mt_escape(\$roletext);
8462: return &Apache::lonlocal::mt($roletext);
8463: }
8464: }
8465: }
8466: if ((defined($type)) && (defined($rolenames{$type})) &&
8467: (defined($rolenames{$type})) &&
8468: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8469: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8470: } elsif ($cid ne '') {
8471: my $crstype = $env{'course.'.$cid.'.type'};
8472: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8473: (defined($prp{$short}{$rolenames{$crstype}}))) {
8474: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8475: }
1.742 raeburn 8476: }
1.1037 raeburn 8477: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8478: }
8479:
8480: # ----------------------------------------------------------------- Assign Role
8481:
8482: sub assignrole {
1.957 raeburn 8483: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8484: $context)=@_;
1.21 www 8485: my $mrole;
8486: if ($role =~ /^cr\//) {
1.393 www 8487: my $cwosec=$url;
1.811 albertel 8488: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8489: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8490: my $refused = 1;
8491: if ($context eq 'requestcourses') {
8492: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8493: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8494: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8495: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8496: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8497: if ($crsenv{'internal.courseowner'} eq
8498: $env{'user.name'}.':'.$env{'user.domain'}) {
8499: $refused = '';
8500: }
8501: }
8502: }
8503: }
8504: }
8505: if ($refused) {
8506: &logthis('Refused custom assignrole: '.
8507: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8508: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8509: return 'refused';
8510: }
1.104 www 8511: }
1.21 www 8512: $mrole='cr';
1.678 raeburn 8513: } elsif ($role =~ /^gr\//) {
8514: my $cwogrp=$url;
1.811 albertel 8515: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8516: unless (&allowed('mdg',$cwogrp)) {
8517: &logthis('Refused group assignrole: '.
8518: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8519: $env{'user.name'}.' at '.$env{'user.domain'});
8520: return 'refused';
8521: }
8522: $mrole='gr';
1.21 www 8523: } else {
1.82 www 8524: my $cwosec=$url;
1.811 albertel 8525: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8526: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8527: my $refused;
8528: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8529: if (!(&allowed('c'.$role,$url))) {
8530: $refused = 1;
8531: }
8532: } else {
8533: $refused = 1;
8534: }
1.947 raeburn 8535: if ($refused) {
1.1045 raeburn 8536: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8537: if (!$selfenroll && $context eq 'course') {
8538: my %crsenv;
8539: if ($role eq 'cc' || $role eq 'co') {
8540: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8541: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8542: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8543: if ($crsenv{'internal.courseowner'} eq
8544: $env{'user.name'}.':'.$env{'user.domain'}) {
8545: $refused = '';
8546: }
8547: }
8548: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8549: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8550: if ($crsenv{'internal.courseowner'} eq
8551: $env{'user.name'}.':'.$env{'user.domain'}) {
8552: $refused = '';
8553: }
8554: }
8555: }
8556: }
8557: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8558: $refused = '';
1.1017 raeburn 8559: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8560: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8561: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8562: my $wrongcc;
8563: if ($cnum =~ /^$match_community$/) {
8564: $wrongcc = 1 if ($role eq 'cc');
8565: } else {
8566: $wrongcc = 1 if ($role eq 'co');
8567: }
8568: unless ($wrongcc) {
8569: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8570: if ($crsenv{'internal.courseowner'} eq
8571: $env{'user.name'}.':'.$env{'user.domain'}) {
8572: $refused = '';
8573: }
1.1017 raeburn 8574: }
8575: }
1.1172.2.9 raeburn 8576: } elsif ($context eq 'requestauthor') {
8577: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8578: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8579: if ($env{'environment.requestauthor'} eq 'automatic') {
8580: $refused = '';
8581: } else {
8582: my %domdefaults = &get_domain_defaults($udom);
8583: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8584: my $checkbystatus;
8585: if ($env{'user.adv'}) {
8586: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8587: if ($disposition eq 'automatic') {
8588: $refused = '';
8589: } elsif ($disposition eq '') {
8590: $checkbystatus = 1;
8591: }
8592: } else {
8593: $checkbystatus = 1;
8594: }
8595: if ($checkbystatus) {
8596: if ($env{'environment.inststatus'}) {
8597: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8598: foreach my $type (@inststatuses) {
8599: if (($type ne '') &&
8600: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8601: $refused = '';
8602: }
8603: }
8604: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8605: $refused = '';
8606: }
8607: }
8608: }
8609: }
8610: }
1.1017 raeburn 8611: }
8612: if ($refused) {
1.947 raeburn 8613: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8614: ' '.$role.' '.$end.' '.$start.' by '.
8615: $env{'user.name'}.' at '.$env{'user.domain'});
8616: return 'refused';
8617: }
1.932 raeburn 8618: }
1.1131 raeburn 8619: } elsif ($role eq 'au') {
8620: if ($url ne '/'.$udom.'/') {
8621: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8622: ' to assign author role for '.$uname.':'.$udom.
8623: ' in domain: '.$url.' refused (wrong domain).');
8624: return 'refused';
8625: }
1.104 www 8626: }
1.21 www 8627: $mrole=$role;
8628: }
1.620 albertel 8629: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8630: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8631: if ($end) { $command.='_'.$end; }
1.21 www 8632: if ($start) {
8633: if ($end) {
1.81 www 8634: $command.='_'.$start;
1.21 www 8635: } else {
1.81 www 8636: $command.='_0_'.$start;
1.21 www 8637: }
8638: }
1.739 raeburn 8639: my $origstart = $start;
8640: my $origend = $end;
1.957 raeburn 8641: my $delflag;
1.357 www 8642: # actually delete
8643: if ($deleteflag) {
1.373 www 8644: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8645: # modify command to delete the role
1.620 albertel 8646: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8647: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8648: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8649: # set start and finish to negative values for userrolelog
8650: $start=-1;
8651: $end=-1;
1.957 raeburn 8652: $delflag = 1;
1.357 www 8653: }
8654: }
8655: # send command
1.349 www 8656: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8657: # log new user role if status is ok
1.349 www 8658: if ($answer eq 'ok') {
1.663 raeburn 8659: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8660: if (($role eq 'cc') || ($role eq 'in') ||
8661: ($role eq 'ep') || ($role eq 'ad') ||
8662: ($role eq 'ta') || ($role eq 'st') ||
8663: ($role=~/^cr/) || ($role eq 'gr') ||
8664: ($role eq 'co')) {
1.1172.2.13 raeburn 8665: # for course roles, perform group memberships changes triggered by role change.
8666: unless ($role =~ /^gr/) {
8667: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8668: $origstart,$selfenroll,$context);
8669: }
1.1172.2.9 raeburn 8670: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8671: $selfenroll,$context);
8672: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8673: ($role eq 'au') || ($role eq 'dc')) {
8674: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8675: $context);
8676: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8677: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8678: $context);
8679: }
1.1053 raeburn 8680: if ($role eq 'cc') {
8681: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8682: }
1.349 www 8683: }
8684: return $answer;
1.169 harris41 8685: }
8686:
1.1053 raeburn 8687: sub autoupdate_coowners {
8688: my ($url,$end,$start,$uname,$udom) = @_;
8689: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8690: if (($cdom ne '') && ($cnum ne '')) {
8691: my $now = time;
8692: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8693: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8694: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8695: my $instcode = $coursehash{'internal.coursecode'};
8696: if ($instcode ne '') {
1.1056 raeburn 8697: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8698: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8699: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8700: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8701: if ($result eq 'valid') {
8702: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8703: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8704: push(@newcoowners,$coowner);
8705: }
8706: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8707: push(@newcoowners,$uname.':'.$udom);
8708: }
8709: @newcoowners = sort(@newcoowners);
8710: } else {
8711: push(@newcoowners,$uname.':'.$udom);
8712: }
8713: } else {
8714: if ($coursehash{'internal.co-owners'}) {
8715: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8716: unless ($coowner eq $uname.':'.$udom) {
8717: push(@newcoowners,$coowner);
8718: }
8719: }
8720: unless (@newcoowners > 0) {
8721: $delcoowners = 1;
8722: $coowners = '';
8723: }
8724: }
8725: }
8726: if (@newcoowners || $delcoowners) {
8727: &store_coowners($cdom,$cnum,$coursehash{'home'},
8728: $delcoowners,@newcoowners);
8729: }
8730: }
8731: }
8732: }
8733: }
8734: }
8735: }
8736:
8737: sub store_coowners {
8738: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8739: my $cid = $cdom.'_'.$cnum;
8740: my ($coowners,$delresult,$putresult);
8741: if (@newcoowners) {
8742: $coowners = join(',',@newcoowners);
8743: my %coownershash = (
8744: 'internal.co-owners' => $coowners,
8745: );
8746: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8747: if ($putresult eq 'ok') {
8748: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8749: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8750: }
8751: }
8752: }
8753: if ($delcoowners) {
8754: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8755: if ($delresult eq 'ok') {
8756: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8757: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8758: }
8759: }
8760: }
8761: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8762: my %crsinfo =
8763: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8764: if (ref($crsinfo{$cid}) eq 'HASH') {
8765: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8766: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8767: }
8768: }
8769: }
8770:
1.169 harris41 8771: # -------------------------------------------------- Modify user authentication
1.197 www 8772: # Overrides without validation
8773:
1.169 harris41 8774: sub modifyuserauth {
8775: my ($udom,$uname,$umode,$upass)=@_;
8776: my $uhome=&homeserver($uname,$udom);
1.197 www 8777: unless (&allowed('mau',$udom)) { return 'refused'; }
8778: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8779: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8780: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8781: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8782: &escape($upass),$uhome);
1.620 albertel 8783: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8784: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8785: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8786: &log($udom,,$uname,$uhome,
1.620 albertel 8787: 'Authentication changed by '.$env{'user.domain'}.', '.
8788: $env{'user.name'}.', '.$umode.
1.197 www 8789: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8790: unless ($reply eq 'ok') {
1.197 www 8791: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8792: return 'error: '.$reply;
8793: }
1.170 harris41 8794: return 'ok';
1.80 www 8795: }
8796:
1.81 www 8797: # --------------------------------------------------------------- Modify a user
1.80 www 8798:
1.81 www 8799: sub modifyuser {
1.206 matthew 8800: my ($udom, $uname, $uid,
8801: $umode, $upass, $first,
8802: $middle, $last, $gene,
1.1058 raeburn 8803: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8804: $udom= &LONCAPA::clean_domain($udom);
8805: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8806: my $showcandelete = 'none';
8807: if (ref($candelete) eq 'ARRAY') {
8808: if (@{$candelete} > 0) {
8809: $showcandelete = join(', ',@{$candelete});
8810: }
8811: }
1.81 www 8812: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8813: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8814: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8815: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8816: ' desiredhome not specified').
1.620 albertel 8817: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8818: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8819: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8820: my $newuser;
8821: if ($uhome eq 'no_host') {
8822: $newuser = 1;
8823: }
1.80 www 8824: # ----------------------------------------------------------------- Create User
1.406 albertel 8825: if (($uhome eq 'no_host') &&
8826: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8827: my $unhome='';
1.844 albertel 8828: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8829: $unhome = $desiredhome;
1.620 albertel 8830: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8831: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8832: } else { # load balancing routine for determining $unhome
1.81 www 8833: my $loadm=10000000;
1.841 albertel 8834: my %servers = &get_servers($udom,'library');
8835: foreach my $tryserver (keys(%servers)) {
8836: my $answer=reply('load',$tryserver);
8837: if (($answer=~/\d+/) && ($answer<$loadm)) {
8838: $loadm=$answer;
8839: $unhome=$tryserver;
8840: }
1.80 www 8841: }
8842: }
8843: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8844: return 'error: unable to find a home server for '.$uname.
8845: ' in domain '.$udom;
1.80 www 8846: }
8847: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8848: &escape($upass),$unhome);
8849: unless ($reply eq 'ok') {
8850: return 'error: '.$reply;
8851: }
1.230 stredwic 8852: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8853: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8854: return 'error: unable verify users home machine.';
1.80 www 8855: }
1.209 matthew 8856: } # End of creation of new user
1.80 www 8857: # ---------------------------------------------------------------------- Add ID
8858: if ($uid) {
8859: $uid=~tr/A-Z/a-z/;
8860: my %uidhash=&idrget($udom,$uname);
1.196 www 8861: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8862: && (!$forceid)) {
1.80 www 8863: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8864: return 'error: user id "'.$uid.'" does not match '.
8865: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8866: }
8867: } else {
8868: &idput($udom,($uname => $uid));
8869: }
8870: }
8871: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8872: my @tmp=&get('environment',
1.899 raeburn 8873: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8874: 'permanentemail','inststatus'],
1.134 albertel 8875: $udom,$uname);
1.1075 raeburn 8876: my (%names,%oldnames);
1.313 matthew 8877: if ($tmp[0] =~ m/^error:.*/) {
8878: %names=();
8879: } else {
8880: %names = @tmp;
1.1075 raeburn 8881: %oldnames = %names;
1.313 matthew 8882: }
1.388 www 8883: #
1.1058 raeburn 8884: # If name, email and/or uid are blank (e.g., because an uploaded file
8885: # of users did not contain them), do not overwrite existing values
8886: # unless field is in $candelete array ref.
8887: #
8888:
8889: my @fields = ('firstname','middlename','lastname','generation',
8890: 'permanentemail','id');
8891: my %newvalues;
8892: if (ref($candelete) eq 'ARRAY') {
8893: foreach my $field (@fields) {
8894: if (grep(/^\Q$field\E$/,@{$candelete})) {
8895: if ($field eq 'firstname') {
8896: $names{$field} = $first;
8897: } elsif ($field eq 'middlename') {
8898: $names{$field} = $middle;
8899: } elsif ($field eq 'lastname') {
8900: $names{$field} = $last;
8901: } elsif ($field eq 'generation') {
8902: $names{$field} = $gene;
8903: } elsif ($field eq 'permanentemail') {
8904: $names{$field} = $email;
8905: } elsif ($field eq 'id') {
8906: $names{$field} = $uid;
8907: }
8908: }
8909: }
8910: }
1.388 www 8911: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8912: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8913: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8914: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8915: if ($email) {
8916: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8917: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8918: }
1.899 raeburn 8919: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8920: if (defined($inststatus)) {
8921: $names{'inststatus'} = '';
8922: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8923: if (ref($usertypes) eq 'HASH') {
8924: my @okstatuses;
8925: foreach my $item (split(/:/,$inststatus)) {
8926: if (defined($usertypes->{$item})) {
8927: push(@okstatuses,$item);
8928: }
8929: }
8930: if (@okstatuses) {
8931: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8932: }
8933: }
8934: }
1.1075 raeburn 8935: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8936: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8937: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8938: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8939: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8940: } else {
8941: $logmsg .= ' during self creation';
8942: }
1.1075 raeburn 8943: my $changed;
8944: if ($newuser) {
8945: $changed = 1;
8946: } else {
8947: foreach my $field (@fields) {
8948: if ($names{$field} ne $oldnames{$field}) {
8949: $changed = 1;
8950: last;
8951: }
8952: }
8953: }
8954: unless ($changed) {
8955: $logmsg = 'No changes in user information needed for: '.$logmsg;
8956: &logthis($logmsg);
8957: return 'ok';
8958: }
8959: my $reply = &put('environment', \%names, $udom,$uname);
8960: if ($reply ne 'ok') {
8961: return 'error: '.$reply;
8962: }
1.1087 raeburn 8963: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8964: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8965: }
1.1075 raeburn 8966: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8967: &devalidate_cache_new('namescache',$uname.':'.$udom);
8968: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8969: &logthis($logmsg);
1.134 albertel 8970: return 'ok';
1.80 www 8971: }
8972:
1.81 www 8973: # -------------------------------------------------------------- Modify student
1.80 www 8974:
1.81 www 8975: sub modifystudent {
8976: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8977: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76! raeburn 8978: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 8979: if (!$cid) {
1.620 albertel 8980: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8981: return 'not_in_class';
8982: }
1.80 www 8983: }
8984: # --------------------------------------------------------------- Make the user
1.81 www 8985: my $reply=&modifyuser
1.209 matthew 8986: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8987: $desiredhome,$email,$inststatus);
1.80 www 8988: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8989: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8990: # student's environment
1.297 matthew 8991: $uid = undef if (!$forceid);
1.455 albertel 8992: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8993: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76! raeburn 8994: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 8995: return $reply;
8996: }
8997:
8998: sub modify_student_enrollment {
1.1172.2.23 raeburn 8999: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76! raeburn 9000: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9001: my ($cdom,$cnum,$chome);
9002: if (!$cid) {
1.620 albertel 9003: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9004: return 'not_in_class';
9005: }
1.620 albertel 9006: $cdom=$env{'course.'.$cid.'.domain'};
9007: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9008: } else {
9009: ($cdom,$cnum)=split(/_/,$cid);
9010: }
1.620 albertel 9011: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9012: if (!$chome) {
1.457 raeburn 9013: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9014: }
1.455 albertel 9015: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9016: # Make sure the user exists
1.81 www 9017: my $uhome=&homeserver($uname,$udom);
9018: if (($uhome eq '') || ($uhome eq 'no_host')) {
9019: return 'error: no such user';
9020: }
1.297 matthew 9021: # Get student data if we were not given enough information
9022: if (!defined($first) || $first eq '' ||
9023: !defined($last) || $last eq '' ||
9024: !defined($uid) || $uid eq '' ||
9025: !defined($middle) || $middle eq '' ||
9026: !defined($gene) || $gene eq '') {
1.294 matthew 9027: # They did not supply us with enough data to enroll the student, so
9028: # we need to pick up more information.
1.297 matthew 9029: my %tmp = &get('environment',
1.294 matthew 9030: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9031: ,$udom,$uname);
9032:
1.800 albertel 9033: #foreach my $key (keys(%tmp)) {
9034: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9035: #}
1.294 matthew 9036: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9037: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9038: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9039: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9040: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9041: }
1.556 albertel 9042: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9043: my $user = "$uname:$udom";
9044: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9045: my $reply=cput('classlist',
1.1148 raeburn 9046: {$user =>
1.1172.2.76! raeburn 9047: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9048: $cdom,$cnum);
1.1148 raeburn 9049: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9050: &devalidate_getsection_cache($udom,$uname,$cid);
9051: } else {
1.81 www 9052: return 'error: '.$reply;
9053: }
1.297 matthew 9054: # Add student role to user
1.83 www 9055: my $uurl='/'.$cid;
1.81 www 9056: $uurl=~s/\_/\//g;
9057: if ($usec) {
9058: $uurl.='/'.$usec;
9059: }
1.1148 raeburn 9060: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9061: $selfenroll,$context);
9062: if ($result ne 'ok') {
9063: if ($old_entry{$user} ne '') {
9064: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9065: } else {
9066: $reply = &del('classlist',[$user],$cdom,$cnum);
9067: }
9068: }
9069: return $result;
1.21 www 9070: }
9071:
1.556 albertel 9072: sub format_name {
9073: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9074: my $name;
9075: if ($first ne 'lastname') {
9076: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9077: } else {
9078: if ($lastname=~/\S/) {
9079: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9080: $name=~s/\s+,/,/;
9081: } else {
9082: $name.= $firstname.' '.$middlename.' '.$generation;
9083: }
9084: }
9085: $name=~s/^\s+//;
9086: $name=~s/\s+$//;
9087: $name=~s/\s+/ /g;
9088: return $name;
9089: }
9090:
1.84 www 9091: # ------------------------------------------------- Write to course preferences
9092:
9093: sub writecoursepref {
9094: my ($courseid,%prefs)=@_;
9095: $courseid=~s/^\///;
9096: $courseid=~s/\_/\//g;
9097: my ($cdomain,$cnum)=split(/\//,$courseid);
9098: my $chome=homeserver($cnum,$cdomain);
9099: if (($chome eq '') || ($chome eq 'no_host')) {
9100: return 'error: no such course';
9101: }
9102: my $cstring='';
1.800 albertel 9103: foreach my $pref (keys(%prefs)) {
9104: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9105: }
1.84 www 9106: $cstring=~s/\&$//;
9107: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9108: }
9109:
9110: # ---------------------------------------------------------- Make/modify course
9111:
9112: sub createcourse {
1.741 raeburn 9113: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9114: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9115: $url=&declutter($url);
9116: my $cid='';
1.1028 raeburn 9117: if ($context eq 'requestcourses') {
9118: my $can_create = 0;
9119: my ($ownername,$ownerdom) = split(':',$course_owner);
9120: if ($udom eq $ownerdom) {
9121: if (&usertools_access($ownername,$ownerdom,$category,undef,
9122: $context)) {
9123: $can_create = 1;
9124: }
9125: } else {
9126: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9127: $category);
9128: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9129: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9130: if (@curr > 0) {
9131: my @options = qw(approval validate autolimit);
9132: my $optregex = join('|',@options);
9133: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9134: $can_create = 1;
9135: }
9136: }
9137: }
9138: }
9139: if ($can_create) {
9140: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9141: unless (&allowed('ccc',$udom)) {
9142: return 'refused';
9143: }
1.1017 raeburn 9144: }
9145: } else {
9146: return 'refused';
9147: }
1.1028 raeburn 9148: } elsif (!&allowed('ccc',$udom)) {
9149: return 'refused';
1.84 www 9150: }
1.1011 raeburn 9151: # --------------------------------------------------------------- Get Unique ID
9152: my $uname;
9153: if ($cnum =~ /^$match_courseid$/) {
9154: my $chome=&homeserver($cnum,$udom,'true');
9155: if (($chome eq '') || ($chome eq 'no_host')) {
9156: $uname = $cnum;
9157: } else {
1.1038 raeburn 9158: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9159: }
9160: } else {
1.1038 raeburn 9161: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9162: }
9163: return $uname if ($uname =~ /^error/);
9164: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9165: if (!defined($course_server)) {
9166: if (defined(&domain($udom,'primary'))) {
9167: $course_server = &domain($udom,'primary');
9168: } else {
9169: $course_server = $env{'user.home'};
9170: }
9171: }
9172: my %host_servers =
9173: &Apache::lonnet::get_servers($udom,'library');
9174: unless ($host_servers{$course_server}) {
9175: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9176: }
1.84 www 9177: # ------------------------------------------------------------- Make the course
9178: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9179: $course_server);
1.84 www 9180: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9181: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9182: if (($uhome eq '') || ($uhome eq 'no_host')) {
9183: return 'error: no such course';
9184: }
1.271 www 9185: # ----------------------------------------------------------------- Course made
1.516 raeburn 9186: # log existence
1.1029 raeburn 9187: my $now = time;
1.918 raeburn 9188: my $newcourse = {
9189: $udom.'_'.$uname => {
1.921 raeburn 9190: description => $description,
9191: inst_code => $inst_code,
9192: owner => $course_owner,
9193: type => $crstype,
1.1029 raeburn 9194: creator => $env{'user.name'}.':'.
9195: $env{'user.domain'},
9196: created => $now,
9197: context => $context,
1.918 raeburn 9198: },
9199: };
1.921 raeburn 9200: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9201: # set toplevel url
1.271 www 9202: my $topurl=$url;
9203: unless ($nonstandard) {
9204: # ------------------------------------------ For standard courses, make top url
9205: my $mapurl=&clutter($url);
1.278 www 9206: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9207: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9208: <map>
9209: <resource id="1" type="start"></resource>
9210: <resource id="2" src="$mapurl"></resource>
9211: <resource id="3" type="finish"></resource>
9212: <link index="1" from="1" to="2"></link>
9213: <link index="2" from="2" to="3"></link>
9214: </map>
9215: ENDINITMAP
9216: $topurl=&declutter(
1.638 albertel 9217: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9218: );
9219: }
9220: # ----------------------------------------------------------- Write preferences
1.84 www 9221: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9222: ('description' => $description,
9223: 'url' => $topurl,
9224: 'internal.creator' => $env{'user.name'}.':'.
9225: $env{'user.domain'},
9226: 'internal.created' => $now,
9227: 'internal.creationcontext' => $context)
9228: );
1.84 www 9229: return '/'.$udom.'/'.$uname;
9230: }
9231:
1.1011 raeburn 9232: # ------------------------------------------------------------------- Create ID
9233: sub generate_coursenum {
1.1038 raeburn 9234: my ($udom,$crstype) = @_;
1.1011 raeburn 9235: my $domdesc = &domain($udom);
9236: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9237: my $first;
9238: if ($crstype eq 'Community') {
9239: $first = '0';
9240: } else {
9241: $first = int(1+rand(9));
9242: }
9243: my $uname=$first.
1.1011 raeburn 9244: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9245: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9246: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9247: # ----------------------------------------------- Make sure that does not exist
9248: my $uhome=&homeserver($uname,$udom,'true');
9249: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9250: if ($crstype eq 'Community') {
9251: $first = '0';
9252: } else {
9253: $first = int(1+rand(9));
9254: }
9255: $uname=$first.
1.1011 raeburn 9256: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9257: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9258: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9259: $uhome=&homeserver($uname,$udom,'true');
9260: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9261: return 'error: unable to generate unique course-ID';
9262: }
9263: }
9264: return $uname;
9265: }
9266:
1.813 albertel 9267: sub is_course {
1.1167 droeschl 9268: my ($cdom, $cnum) = scalar(@_) == 1 ?
9269: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9270:
9271: return unless $cdom and $cnum;
9272:
9273: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9274: '.');
9275:
1.1172.2.23 raeburn 9276: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9277: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9278: }
9279:
1.1015 raeburn 9280: sub store_userdata {
9281: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9282: my $result;
1.1016 raeburn 9283: if ($datakey ne '') {
1.1013 raeburn 9284: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9285: if ($udom eq '' || $uname eq '') {
9286: $udom = $env{'user.domain'};
9287: $uname = $env{'user.name'};
9288: }
9289: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9290: if (($uhome eq '') || ($uhome eq 'no_host')) {
9291: $result = 'error: no_host';
9292: } else {
9293: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9294: $storehash->{'host'} = $perlvar{'lonHostID'};
9295:
9296: my $namevalue='';
9297: foreach my $key (keys(%{$storehash})) {
9298: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9299: }
9300: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9301: unless ($namespace eq 'courserequests') {
9302: $datakey = &escape($datakey);
9303: }
1.1105 raeburn 9304: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9305: $namevalue,$uhome);
1.1013 raeburn 9306: }
9307: } else {
9308: $result = 'error: data to store was not a hash reference';
9309: }
9310: } else {
9311: $result= 'error: invalid requestkey';
9312: }
9313: return $result;
9314: }
9315:
1.21 www 9316: # ---------------------------------------------------------- Assign Custom Role
9317:
9318: sub assigncustomrole {
1.957 raeburn 9319: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9320: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9321: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9322: }
9323:
9324: # ----------------------------------------------------------------- Revoke Role
9325:
9326: sub revokerole {
1.957 raeburn 9327: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9328: my $now=time;
1.965 raeburn 9329: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9330: }
9331:
9332: # ---------------------------------------------------------- Revoke Custom Role
9333:
9334: sub revokecustomrole {
1.957 raeburn 9335: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9336: my $now=time;
1.357 www 9337: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9338: $deleteflag,$selfenroll,$context);
1.17 www 9339: }
9340:
1.533 banghart 9341: # ------------------------------------------------------------ Disk usage
1.535 albertel 9342: sub diskusage {
1.955 raeburn 9343: my ($udom,$uname,$directorypath,$getpropath)=@_;
9344: $directorypath =~ s/\/$//;
9345: my $listing=&reply('du2:'.&escape($directorypath).':'
9346: .&escape($getpropath).':'.&escape($uname).':'
9347: .&escape($udom),homeserver($uname,$udom));
9348: if ($listing eq 'unknown_cmd') {
9349: if ($getpropath) {
9350: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9351: }
9352: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9353: }
1.514 albertel 9354: return $listing;
1.512 banghart 9355: }
9356:
1.566 banghart 9357: sub is_locked {
1.1096 raeburn 9358: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9359: my @check;
9360: my $is_locked;
1.1093 raeburn 9361: push (@check,$file_name);
1.613 albertel 9362: my %locked = &get('file_permissions',\@check,
1.620 albertel 9363: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9364: my ($tmp)=keys(%locked);
9365: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9366:
1.566 banghart 9367: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9368: $is_locked = 'false';
9369: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9370: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9371: $is_locked = 'true';
1.1096 raeburn 9372: if (ref($which) eq 'ARRAY') {
9373: push(@{$which},$entry);
9374: } else {
9375: last;
9376: }
1.745 raeburn 9377: }
9378: }
1.566 banghart 9379: } else {
9380: $is_locked = 'false';
9381: }
1.1093 raeburn 9382: return $is_locked;
1.566 banghart 9383: }
9384:
1.759 albertel 9385: sub declutter_portfile {
9386: my ($file) = @_;
1.833 albertel 9387: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9388: return $file;
9389: }
9390:
1.559 banghart 9391: # ------------------------------------------------------------- Mark as Read Only
9392:
9393: sub mark_as_readonly {
9394: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9395: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9396: my ($tmp)=keys(%current_permissions);
9397: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9398: foreach my $file (@{$files}) {
1.759 albertel 9399: $file = &declutter_portfile($file);
1.561 banghart 9400: push(@{$current_permissions{$file}},$what);
1.559 banghart 9401: }
1.613 albertel 9402: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9403: return;
9404: }
9405:
1.572 banghart 9406: # ------------------------------------------------------------Save Selected Files
9407:
9408: sub save_selected_files {
9409: my ($user, $path, @files) = @_;
9410: my $filename = $user."savedfiles";
1.573 banghart 9411: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9412: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9413: foreach my $file (@files) {
1.620 albertel 9414: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9415: }
9416: foreach my $file (@other_files) {
1.574 banghart 9417: print (OUT $file."\n");
1.572 banghart 9418: }
1.574 banghart 9419: close (OUT);
1.572 banghart 9420: return 'ok';
9421: }
9422:
1.574 banghart 9423: sub clear_selected_files {
9424: my ($user) = @_;
9425: my $filename = $user."savedfiles";
1.1117 foxr 9426: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9427: print (OUT undef);
9428: close (OUT);
9429: return ("ok");
9430: }
9431:
1.572 banghart 9432: sub files_in_path {
9433: my ($user, $path) = @_;
9434: my $filename = $user."savedfiles";
9435: my %return_files;
1.1117 foxr 9436: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9437: while (my $line_in = <IN>) {
1.574 banghart 9438: chomp ($line_in);
9439: my @paths_and_file = split (m!/!, $line_in);
9440: my $file_part = pop (@paths_and_file);
9441: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9442: $path_part.='/';
9443: my $path_and_file = $path_part.$file_part;
9444: if ($path_part eq $path) {
9445: $return_files{$file_part}= 'selected';
9446: }
9447: }
1.574 banghart 9448: close (IN);
9449: return (\%return_files);
1.572 banghart 9450: }
9451:
9452: # called in portfolio select mode, to show files selected NOT in current directory
9453: sub files_not_in_path {
9454: my ($user, $path) = @_;
9455: my $filename = $user."savedfiles";
9456: my @return_files;
9457: my $path_part;
1.1117 foxr 9458: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9459: while (my $line = <IN>) {
1.572 banghart 9460: #ok, I know it's clunky, but I want it to work
1.800 albertel 9461: my @paths_and_file = split(m|/|, $line);
9462: my $file_part = pop(@paths_and_file);
9463: chomp($file_part);
9464: my $path_part = join('/', @paths_and_file);
1.572 banghart 9465: $path_part .= '/';
9466: my $path_and_file = $path_part.$file_part;
9467: if ($path_part ne $path) {
1.800 albertel 9468: push(@return_files, ($path_and_file));
1.572 banghart 9469: }
9470: }
1.800 albertel 9471: close(OUT);
1.574 banghart 9472: return (@return_files);
1.572 banghart 9473: }
9474:
1.745 raeburn 9475: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9476:
1.745 raeburn 9477: sub get_portfile_permissions {
9478: my ($domain,$user) = @_;
1.613 albertel 9479: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9480: my ($tmp)=keys(%current_permissions);
9481: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9482: return \%current_permissions;
9483: }
9484:
9485: #---------------------------------------------Get portfolio file access controls
9486:
1.749 raeburn 9487: sub get_access_controls {
1.745 raeburn 9488: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9489: my %access;
9490: my $real_file = $file;
9491: $file =~ s/\.meta$//;
1.745 raeburn 9492: if (defined($file)) {
1.749 raeburn 9493: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9494: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9495: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9496: }
9497: }
1.745 raeburn 9498: } else {
1.749 raeburn 9499: foreach my $key (keys(%{$current_permissions})) {
9500: if ($key =~ /\0accesscontrol$/) {
9501: if (defined($group)) {
9502: if ($key !~ m-^\Q$group\E/-) {
9503: next;
9504: }
9505: }
9506: my ($fullpath) = split(/\0/,$key);
9507: if (ref($$current_permissions{$key}) eq 'HASH') {
9508: foreach my $control (keys(%{$$current_permissions{$key}})) {
9509: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9510: }
9511: }
9512: }
9513: }
9514: }
9515: return %access;
9516: }
9517:
9518: sub modify_access_controls {
9519: my ($file_name,$changes,$domain,$user)=@_;
9520: my ($outcome,$deloutcome);
9521: my %store_permissions;
9522: my %new_values;
9523: my %new_control;
9524: my %translation;
9525: my @deletions = ();
9526: my $now = time;
9527: if (exists($$changes{'activate'})) {
9528: if (ref($$changes{'activate'}) eq 'HASH') {
9529: my @newitems = sort(keys(%{$$changes{'activate'}}));
9530: my $numnew = scalar(@newitems);
9531: for (my $i=0; $i<$numnew; $i++) {
9532: my $newkey = $newitems[$i];
9533: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9534: if ($newkey =~ /^\d+:/) {
9535: $newkey =~ s/^(\d+)/$newid/;
9536: $translation{$1} = $newid;
9537: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9538: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9539: $translation{$1} = $newid;
9540: }
1.749 raeburn 9541: $new_values{$file_name."\0".$newkey} =
9542: $$changes{'activate'}{$newitems[$i]};
9543: $new_control{$newkey} = $now;
9544: }
9545: }
9546: }
9547: my %todelete;
9548: my %changed_items;
9549: foreach my $action ('delete','update') {
9550: if (exists($$changes{$action})) {
9551: if (ref($$changes{$action}) eq 'HASH') {
9552: foreach my $key (keys(%{$$changes{$action}})) {
9553: my ($itemnum) = ($key =~ /^([^:]+):/);
9554: if ($action eq 'delete') {
9555: $todelete{$itemnum} = 1;
9556: } else {
9557: $changed_items{$itemnum} = $key;
9558: }
9559: }
1.745 raeburn 9560: }
9561: }
1.749 raeburn 9562: }
9563: # get lock on access controls for file.
9564: my $lockhash = {
9565: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9566: ':'.$env{'user.domain'},
9567: };
9568: my $tries = 0;
9569: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9570:
9571: while (($gotlock ne 'ok') && $tries <3) {
9572: $tries ++;
9573: sleep 1;
9574: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9575: }
9576: if ($gotlock eq 'ok') {
9577: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9578: my ($tmp)=keys(%curr_permissions);
9579: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9580: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9581: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9582: if (ref($curr_controls) eq 'HASH') {
9583: foreach my $control_item (keys(%{$curr_controls})) {
9584: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9585: if (defined($todelete{$itemnum})) {
9586: push(@deletions,$file_name."\0".$control_item);
9587: } else {
9588: if (defined($changed_items{$itemnum})) {
9589: $new_control{$changed_items{$itemnum}} = $now;
9590: push(@deletions,$file_name."\0".$control_item);
9591: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9592: } else {
9593: $new_control{$control_item} = $$curr_controls{$control_item};
9594: }
9595: }
1.745 raeburn 9596: }
9597: }
9598: }
1.970 raeburn 9599: my ($group);
9600: if (&is_course($domain,$user)) {
9601: ($group,my $file) = split(/\//,$file_name,2);
9602: }
1.749 raeburn 9603: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9604: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9605: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9606: # remove lock
9607: my @del_lock = ($file_name."\0".'locked_access_records');
9608: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9609: my $sqlresult =
1.970 raeburn 9610: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9611: $group);
1.749 raeburn 9612: } else {
9613: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9614: }
1.749 raeburn 9615: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9616: }
9617:
1.827 raeburn 9618: sub make_public_indefinitely {
9619: my ($requrl) = @_;
9620: my $now = time;
9621: my $action = 'activate';
9622: my $aclnum = 0;
9623: if (&is_portfolio_url($requrl)) {
9624: my (undef,$udom,$unum,$file_name,$group) =
9625: &parse_portfolio_url($requrl);
9626: my $current_perms = &get_portfile_permissions($udom,$unum);
9627: my %access_controls = &get_access_controls($current_perms,
9628: $group,$file_name);
9629: foreach my $key (keys(%{$access_controls{$file_name}})) {
9630: my ($num,$scope,$end,$start) =
9631: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9632: if ($scope eq 'public') {
9633: if ($start <= $now && $end == 0) {
9634: $action = 'none';
9635: } else {
9636: $action = 'update';
9637: $aclnum = $num;
9638: }
9639: last;
9640: }
9641: }
9642: if ($action eq 'none') {
9643: return 'ok';
9644: } else {
9645: my %changes;
9646: my $newend = 0;
9647: my $newstart = $now;
9648: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9649: $changes{$action}{$newkey} = {
9650: type => 'public',
9651: time => {
9652: start => $newstart,
9653: end => $newend,
9654: },
9655: };
9656: my ($outcome,$deloutcome,$new_values,$translation) =
9657: &modify_access_controls($file_name,\%changes,$udom,$unum);
9658: return $outcome;
9659: }
9660: } else {
9661: return 'invalid';
9662: }
9663: }
9664:
1.745 raeburn 9665: #------------------------------------------------------Get Marked as Read Only
9666:
9667: sub get_marked_as_readonly {
9668: my ($domain,$user,$what,$group) = @_;
9669: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9670: my @readonly_files;
1.629 banghart 9671: my $cmp1=$what;
9672: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9673: while (my ($file_name,$value) = each(%{$current_permissions})) {
9674: if (defined($group)) {
9675: if ($file_name !~ m-^\Q$group\E/-) {
9676: next;
9677: }
9678: }
1.561 banghart 9679: if (ref($value) eq "ARRAY"){
9680: foreach my $stored_what (@{$value}) {
1.629 banghart 9681: my $cmp2=$stored_what;
1.759 albertel 9682: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9683: $cmp2=join('',@{$stored_what});
1.745 raeburn 9684: }
1.629 banghart 9685: if ($cmp1 eq $cmp2) {
1.561 banghart 9686: push(@readonly_files, $file_name);
1.745 raeburn 9687: last;
1.563 banghart 9688: } elsif (!defined($what)) {
9689: push(@readonly_files, $file_name);
1.745 raeburn 9690: last;
1.561 banghart 9691: }
9692: }
1.745 raeburn 9693: }
1.561 banghart 9694: }
9695: return @readonly_files;
9696: }
1.577 banghart 9697: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9698:
1.577 banghart 9699: sub get_marked_as_readonly_hash {
1.745 raeburn 9700: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9701: my %readonly_files;
1.745 raeburn 9702: while (my ($file_name,$value) = each(%{$current_permissions})) {
9703: if (defined($group)) {
9704: if ($file_name !~ m-^\Q$group\E/-) {
9705: next;
9706: }
9707: }
1.577 banghart 9708: if (ref($value) eq "ARRAY"){
9709: foreach my $stored_what (@{$value}) {
1.745 raeburn 9710: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9711: foreach my $lock_descriptor(@{$stored_what}) {
9712: if ($lock_descriptor eq 'graded') {
9713: $readonly_files{$file_name} = 'graded';
9714: } elsif ($lock_descriptor eq 'handback') {
9715: $readonly_files{$file_name} = 'handback';
9716: } else {
9717: if (!exists($readonly_files{$file_name})) {
9718: $readonly_files{$file_name} = 'locked';
9719: }
9720: }
1.745 raeburn 9721: }
1.750 banghart 9722: }
1.577 banghart 9723: }
9724: }
9725: }
9726: return %readonly_files;
9727: }
1.559 banghart 9728: # ------------------------------------------------------------ Unmark as Read Only
9729:
9730: sub unmark_as_readonly {
1.629 banghart 9731: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9732: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9733: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9734: $file_name = &declutter_portfile($file_name);
1.634 albertel 9735: my $symb_crs = $what;
9736: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9737: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9738: my ($tmp)=keys(%current_permissions);
9739: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9740: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9741: foreach my $file (@readonly_files) {
1.759 albertel 9742: my $clean_file = &declutter_portfile($file);
9743: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9744: my $current_locks = $current_permissions{$file};
1.563 banghart 9745: my @new_locks;
9746: my @del_keys;
9747: if (ref($current_locks) eq "ARRAY"){
9748: foreach my $locker (@{$current_locks}) {
1.632 albertel 9749: my $compare=$locker;
1.749 raeburn 9750: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9751: $compare=join('',@{$locker});
1.746 raeburn 9752: if ($compare ne $symb_crs) {
9753: push(@new_locks, $locker);
9754: }
1.563 banghart 9755: }
9756: }
1.650 albertel 9757: if (scalar(@new_locks) > 0) {
1.563 banghart 9758: $current_permissions{$file} = \@new_locks;
9759: } else {
9760: push(@del_keys, $file);
1.613 albertel 9761: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9762: delete($current_permissions{$file});
1.563 banghart 9763: }
9764: }
1.561 banghart 9765: }
1.613 albertel 9766: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9767: return;
9768: }
1.512 banghart 9769:
1.17 www 9770: # ------------------------------------------------------------ Directory lister
9771:
9772: sub dirlist {
1.955 raeburn 9773: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9774: $uri=~s/^\///;
9775: $uri=~s/\/$//;
1.253 stredwic 9776: my ($udom, $uname);
1.955 raeburn 9777: if ($getuserdir) {
1.253 stredwic 9778: $udom = $userdomain;
9779: $uname = $username;
1.955 raeburn 9780: } else {
9781: (undef,$udom,$uname)=split(/\//,$uri);
9782: if(defined($userdomain)) {
9783: $udom = $userdomain;
9784: }
9785: if(defined($username)) {
9786: $uname = $username;
9787: }
1.253 stredwic 9788: }
1.955 raeburn 9789: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9790:
1.955 raeburn 9791: $dirRoot = $perlvar{'lonDocRoot'};
9792: if (defined($getpropath)) {
9793: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9794: $dirRoot =~ s/\/$//;
1.955 raeburn 9795: } elsif (defined($getuserdir)) {
9796: my $subdir=$uname.'__';
9797: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9798: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9799: ."/$udom/$subdir/$uname";
9800: } elsif (defined($alternateRoot)) {
9801: $dirRoot = $alternateRoot;
1.751 banghart 9802: }
1.253 stredwic 9803:
9804: if($udom) {
9805: if($uname) {
1.1135 raeburn 9806: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9807: if ($uhome eq 'no_host') {
9808: return ([],'no_host');
9809: }
1.955 raeburn 9810: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9811: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9812: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9813: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9814: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9815: } else {
9816: @listing_results = map { &unescape($_); } split(/:/,$listing);
9817: }
1.605 matthew 9818: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9819: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9820: @listing_results = split(/:/,$listing);
9821: } else {
9822: @listing_results = map { &unescape($_); } split(/:/,$listing);
9823: }
1.1135 raeburn 9824: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9825: ($listing eq 'rejected') || ($listing eq 'refused') ||
9826: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9827: return ([],$listing);
9828: } else {
9829: return (\@listing_results);
1.1135 raeburn 9830: }
1.955 raeburn 9831: } elsif(!$alternateRoot) {
1.1136 raeburn 9832: my (%allusers,%listerror);
1.841 albertel 9833: my %servers = &get_servers($udom,'library');
1.955 raeburn 9834: foreach my $tryserver (keys(%servers)) {
9835: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9836: &escape($udom),$tryserver);
9837: if ($listing eq 'unknown_cmd') {
9838: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9839: $udom, $tryserver);
9840: } else {
9841: @listing_results = map { &unescape($_); } split(/:/,$listing);
9842: }
1.841 albertel 9843: if ($listing eq 'unknown_cmd') {
9844: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9845: $udom, $tryserver);
9846: @listing_results = split(/:/,$listing);
9847: } else {
9848: @listing_results =
9849: map { &unescape($_); } split(/:/,$listing);
9850: }
1.1136 raeburn 9851: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9852: ($listing eq 'rejected') || ($listing eq 'refused') ||
9853: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9854: $listerror{$tryserver} = $listing;
9855: } else {
1.841 albertel 9856: foreach my $line (@listing_results) {
9857: my ($entry) = split(/&/,$line,2);
9858: $allusers{$entry} = 1;
9859: }
9860: }
1.253 stredwic 9861: }
1.1136 raeburn 9862: my @alluserslist=();
1.800 albertel 9863: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9864: push(@alluserslist,$user.'&user');
1.253 stredwic 9865: }
1.1136 raeburn 9866: return (\@alluserslist);
1.253 stredwic 9867: } else {
1.1136 raeburn 9868: return ([],'missing username');
1.253 stredwic 9869: }
1.955 raeburn 9870: } elsif(!defined($getpropath)) {
1.1136 raeburn 9871: my $path = $perlvar{'lonDocRoot'}.'/res/';
9872: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9873: return (\@all_domains);
1.955 raeburn 9874: } else {
1.1136 raeburn 9875: return ([],'missing domain');
1.275 stredwic 9876: }
9877: }
9878:
9879: # --------------------------------------------- GetFileTimestamp
9880: # This function utilizes dirlist and returns the date stamp for
9881: # when it was last modified. It will also return an error of -1
9882: # if an error occurs
9883:
9884: sub GetFileTimestamp {
1.955 raeburn 9885: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9886: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9887: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9888: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9889: undef,$getuserdir);
9890: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9891: return -1;
9892: }
9893: if (ref($fileref) eq 'ARRAY') {
9894: my @stats = split('&',$fileref->[0]);
1.375 matthew 9895: # @stats contains first the filename, then the stat output
9896: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9897: } else {
9898: return -1;
1.253 stredwic 9899: }
1.26 www 9900: }
9901:
1.712 albertel 9902: sub stat_file {
9903: my ($uri) = @_;
1.787 albertel 9904: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9905:
1.955 raeburn 9906: my ($udom,$uname,$file);
1.712 albertel 9907: if ($uri =~ m-^/(uploaded|editupload)/-) {
9908: ($udom,$uname,$file) =
1.811 albertel 9909: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9910: $file = 'userfiles/'.$file;
9911: }
9912: if ($uri =~ m-^/res/-) {
9913: ($udom,$uname) =
1.807 albertel 9914: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9915: $file = $uri;
9916: }
9917:
9918: if (!$udom || !$uname || !$file) {
9919: # unable to handle the uri
9920: return ();
9921: }
1.956 raeburn 9922: my $getpropath;
9923: if ($file =~ /^userfiles\//) {
9924: $getpropath = 1;
9925: }
1.1136 raeburn 9926: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9927: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9928: return ();
9929: } else {
9930: if (ref($listref) eq 'ARRAY') {
9931: my @stats = split('&',$listref->[0]);
9932: shift(@stats); #filename is first
9933: return @stats;
9934: }
1.712 albertel 9935: }
9936: return ();
9937: }
9938:
1.26 www 9939: # -------------------------------------------------------- Value of a Condition
9940:
1.713 albertel 9941: # gets the value of a specific preevaluated condition
9942: # stored in the string $env{user.state.<cid>}
9943: # or looks up a condition reference in the bighash and if if hasn't
9944: # already been evaluated recurses into docondval to get the value of
9945: # the condition, then memoizing it to
9946: # $env{user.state.<cid>.<condition>}
1.40 www 9947: sub directcondval {
9948: my $number=shift;
1.620 albertel 9949: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9950: &Apache::lonuserstate::evalstate();
9951: }
1.713 albertel 9952: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9953: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9954: } elsif ($number =~ /^_/) {
9955: my $sub_condition;
9956: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9957: &GDBM_READER(),0640)) {
9958: $sub_condition=$bighash{'conditions'.$number};
9959: untie(%bighash);
9960: }
9961: my $value = &docondval($sub_condition);
1.949 raeburn 9962: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9963: return $value;
9964: }
1.620 albertel 9965: if ($env{'user.state.'.$env{'request.course.id'}}) {
9966: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9967: } else {
9968: return 2;
9969: }
9970: }
9971:
1.713 albertel 9972: # get the collection of conditions for this resource
1.26 www 9973: sub condval {
9974: my $condidx=shift;
1.54 www 9975: my $allpathcond='';
1.713 albertel 9976: foreach my $cond (split(/\|/,$condidx)) {
9977: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9978: $allpathcond.=
9979: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9980: }
1.191 harris41 9981: }
1.54 www 9982: $allpathcond=~s/\|$//;
1.713 albertel 9983: return &docondval($allpathcond);
9984: }
9985:
9986: #evaluates an expression of conditions
9987: sub docondval {
9988: my ($allpathcond) = @_;
9989: my $result=0;
9990: if ($env{'request.course.id'}
9991: && defined($allpathcond)) {
9992: my $operand='|';
9993: my @stack;
9994: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9995: if ($chunk eq '(') {
9996: push @stack,($operand,$result);
9997: } elsif ($chunk eq ')') {
9998: my $before=pop @stack;
9999: if (pop @stack eq '&') {
10000: $result=$result>$before?$before:$result;
10001: } else {
10002: $result=$result>$before?$result:$before;
10003: }
10004: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10005: $operand=$chunk;
10006: } else {
10007: my $new=directcondval($chunk);
10008: if ($operand eq '&') {
10009: $result=$result>$new?$new:$result;
10010: } else {
10011: $result=$result>$new?$result:$new;
10012: }
10013: }
10014: }
1.26 www 10015: }
10016: return $result;
1.421 albertel 10017: }
10018:
10019: # ---------------------------------------------------- Devalidate courseresdata
10020:
10021: sub devalidatecourseresdata {
10022: my ($coursenum,$coursedomain)=@_;
10023: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10024: &devalidate_cache_new('courseres',$hashid);
1.28 www 10025: }
10026:
1.763 www 10027:
1.200 www 10028: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10029: #
10030: # Parameters:
10031: # $coursenum - Number of the course.
10032: # $coursedomain - Domain at which the course was created.
10033: # Returns:
10034: # A hash of the course parameters along (I think) with timestamps
10035: # and version info.
1.877 foxr 10036:
1.624 albertel 10037: sub get_courseresdata {
10038: my ($coursenum,$coursedomain)=@_;
1.200 www 10039: my $coursehom=&homeserver($coursenum,$coursedomain);
10040: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10041: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10042: my %dumpreply;
1.417 albertel 10043: unless (defined($cached)) {
1.624 albertel 10044: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10045: $result=\%dumpreply;
1.251 albertel 10046: my ($tmp) = keys(%dumpreply);
10047: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10048: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10049: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10050: return $tmp;
1.416 albertel 10051: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10052: $result=undef;
1.599 albertel 10053: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10054: }
10055: }
1.624 albertel 10056: return $result;
10057: }
10058:
1.633 albertel 10059: sub devalidateuserresdata {
10060: my ($uname,$udom)=@_;
10061: my $hashid="$udom:$uname";
10062: &devalidate_cache_new('userres',$hashid);
10063: }
10064:
1.624 albertel 10065: sub get_userresdata {
10066: my ($uname,$udom)=@_;
10067: #most student don\'t have any data set, check if there is some data
10068: if (&EXT_cache_status($udom,$uname)) { return undef; }
10069:
10070: my $hashid="$udom:$uname";
10071: my ($result,$cached)=&is_cached_new('userres',$hashid);
10072: if (!defined($cached)) {
10073: my %resourcedata=&dump('resourcedata',$udom,$uname);
10074: $result=\%resourcedata;
10075: &do_cache_new('userres',$hashid,$result,600);
10076: }
10077: my ($tmp)=keys(%$result);
10078: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10079: return $result;
10080: }
10081: #error 2 occurs when the .db doesn't exist
10082: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10083: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10084: &logthis("<font color=\"blue\">WARNING:".
10085: " Trying to get resource data for ".
10086: $uname." at ".$udom.": ".
10087: $tmp."</font>");
10088: }
1.624 albertel 10089: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10090: #&EXT_cache_set($udom,$uname);
10091: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10092: undef($tmp); # not really an error so don't send it back
1.624 albertel 10093: }
10094: return $tmp;
10095: }
1.879 foxr 10096: #----------------------------------------------- resdata - return resource data
10097: # Purpose:
10098: # Return resource data for either users or for a course.
10099: # Parameters:
10100: # $name - Course/user name.
10101: # $domain - Name of the domain the user/course is registered on.
10102: # $type - Type of thing $name is (must be 'course' or 'user'
10103: # @which - Array of names of resources desired.
10104: # Returns:
10105: # The value of the first reasource in @which that is found in the
10106: # resource hash.
10107: # Exceptional Conditions:
10108: # If the $type passed in is not valid (not the string 'course' or
10109: # 'user', an undefined reference is returned.
10110: # If none of the resources are found, an undef is returned
1.624 albertel 10111: sub resdata {
10112: my ($name,$domain,$type,@which)=@_;
10113: my $result;
10114: if ($type eq 'course') {
10115: $result=&get_courseresdata($name,$domain);
10116: } elsif ($type eq 'user') {
10117: $result=&get_userresdata($name,$domain);
10118: }
10119: if (!ref($result)) { return $result; }
1.251 albertel 10120: foreach my $item (@which) {
1.927 albertel 10121: if (defined($result->{$item->[0]})) {
10122: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10123: }
1.250 albertel 10124: }
1.291 albertel 10125: return undef;
1.200 www 10126: }
10127:
1.1172.2.31 raeburn 10128: sub get_numsuppfiles {
10129: my ($cnum,$cdom,$ignorecache)=@_;
10130: my $hashid=$cnum.':'.$cdom;
10131: my ($suppcount,$cached);
10132: unless ($ignorecache) {
10133: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10134: }
10135: unless (defined($cached)) {
10136: my $chome=&homeserver($cnum,$cdom);
10137: unless ($chome eq 'no_host') {
10138: ($suppcount,my $errors) = (0,0);
10139: my $suppmap = 'supplemental.sequence';
10140: ($suppcount,$errors) =
10141: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10142: }
10143: &do_cache_new('suppcount',$hashid,$suppcount,600);
10144: }
10145: return $suppcount;
10146: }
10147:
1.379 matthew 10148: #
10149: # EXT resource caching routines
10150: #
10151:
10152: sub clear_EXT_cache_status {
1.383 albertel 10153: &delenv('cache.EXT.');
1.379 matthew 10154: }
10155:
10156: sub EXT_cache_status {
10157: my ($target_domain,$target_user) = @_;
1.383 albertel 10158: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10159: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10160: # We know already the user has no data
10161: return 1;
10162: } else {
10163: return 0;
10164: }
10165: }
10166:
10167: sub EXT_cache_set {
10168: my ($target_domain,$target_user) = @_;
1.383 albertel 10169: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10170: #&appenv({$cachename => time});
1.379 matthew 10171: }
10172:
1.28 www 10173: # --------------------------------------------------------- Value of a Variable
1.58 www 10174: sub EXT {
1.715 albertel 10175:
1.1172.2.28 raeburn 10176: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10177: unless ($varname) { return ''; }
1.218 albertel 10178: #get real user name/domain, courseid and symb
10179: my $courseid;
1.359 albertel 10180: my $publicuser;
1.427 www 10181: if ($symbparm) {
10182: $symbparm=&get_symb_from_alias($symbparm);
10183: }
1.218 albertel 10184: if (!($uname && $udom)) {
1.790 albertel 10185: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10186: if (!$symbparm) { $symbparm=$cursymb; }
10187: } else {
1.620 albertel 10188: $courseid=$env{'request.course.id'};
1.218 albertel 10189: }
1.48 www 10190: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10191: my $rest;
1.320 albertel 10192: if (defined($therest[0])) {
1.48 www 10193: $rest=join('.',@therest);
10194: } else {
10195: $rest='';
10196: }
1.320 albertel 10197:
1.57 www 10198: my $qualifierrest=$qualifier;
10199: if ($rest) { $qualifierrest.='.'.$rest; }
10200: my $spacequalifierrest=$space;
10201: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10202: if ($realm eq 'user') {
1.48 www 10203: # --------------------------------------------------------------- user.resource
10204: if ($space eq 'resource') {
1.651 albertel 10205: if ( (defined($Apache::lonhomework::parsing_a_problem)
10206: || defined($Apache::lonhomework::parsing_a_task))
10207: &&
1.744 albertel 10208: ($symbparm eq &symbread()) ) {
10209: # if we are in the middle of processing the resource the
10210: # get the value we are planning on committing
10211: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10212: return $Apache::lonhomework::results{$qualifierrest};
10213: } else {
10214: return $Apache::lonhomework::history{$qualifierrest};
10215: }
1.335 albertel 10216: } else {
1.359 albertel 10217: my %restored;
1.620 albertel 10218: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10219: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10220: } else {
10221: %restored=&restore($symbparm,$courseid,$udom,$uname);
10222: }
1.335 albertel 10223: return $restored{$qualifierrest};
10224: }
1.48 www 10225: # ----------------------------------------------------------------- user.access
10226: } elsif ($space eq 'access') {
1.218 albertel 10227: # FIXME - not supporting calls for a specific user
1.48 www 10228: return &allowed($qualifier,$rest);
10229: # ------------------------------------------ user.preferences, user.environment
10230: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10231: if (($uname eq $env{'user.name'}) &&
10232: ($udom eq $env{'user.domain'})) {
10233: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10234: } else {
1.359 albertel 10235: my %returnhash;
10236: if (!$publicuser) {
10237: %returnhash=&userenvironment($udom,$uname,
10238: $qualifierrest);
10239: }
1.218 albertel 10240: return $returnhash{$qualifierrest};
10241: }
1.48 www 10242: # ----------------------------------------------------------------- user.course
10243: } elsif ($space eq 'course') {
1.218 albertel 10244: # FIXME - not supporting calls for a specific user
1.620 albertel 10245: return $env{join('.',('request.course',$qualifier))};
1.48 www 10246: # ------------------------------------------------------------------- user.role
10247: } elsif ($space eq 'role') {
1.218 albertel 10248: # FIXME - not supporting calls for a specific user
1.620 albertel 10249: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10250: if ($qualifier eq 'value') {
10251: return $role;
10252: } elsif ($qualifier eq 'extent') {
10253: return $where;
10254: }
10255: # ----------------------------------------------------------------- user.domain
10256: } elsif ($space eq 'domain') {
1.218 albertel 10257: return $udom;
1.48 www 10258: # ------------------------------------------------------------------- user.name
10259: } elsif ($space eq 'name') {
1.218 albertel 10260: return $uname;
1.48 www 10261: # ---------------------------------------------------- Any other user namespace
1.29 www 10262: } else {
1.359 albertel 10263: my %reply;
10264: if (!$publicuser) {
10265: %reply=&get($space,[$qualifierrest],$udom,$uname);
10266: }
10267: return $reply{$qualifierrest};
1.48 www 10268: }
1.236 www 10269: } elsif ($realm eq 'query') {
10270: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10271: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10272: [$spacequalifierrest]);
1.620 albertel 10273: return $env{'form.'.$spacequalifierrest};
1.236 www 10274: } elsif ($realm eq 'request') {
1.48 www 10275: # ------------------------------------------------------------- request.browser
10276: if ($space eq 'browser') {
1.1145 bisitz 10277: return $env{'browser.'.$qualifier};
1.57 www 10278: # ------------------------------------------------------------ request.filename
10279: } else {
1.620 albertel 10280: return $env{'request.'.$spacequalifierrest};
1.29 www 10281: }
1.28 www 10282: } elsif ($realm eq 'course') {
1.48 www 10283: # ---------------------------------------------------------- course.description
1.620 albertel 10284: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10285: } elsif ($realm eq 'resource') {
1.165 www 10286:
1.620 albertel 10287: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10288: if (!$symbparm) { $symbparm=&symbread(); }
10289: }
1.693 albertel 10290:
1.1172.2.30 raeburn 10291: if ($qualifier eq '') {
10292: if ($space eq 'title') {
10293: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10294: return &gettitle($symbparm);
10295: }
1.693 albertel 10296:
1.1172.2.30 raeburn 10297: if ($space eq 'map') {
10298: my ($map) = &decode_symb($symbparm);
10299: return &symbread($map);
10300: }
10301: if ($space eq 'maptitle') {
10302: my ($map) = &decode_symb($symbparm);
10303: return &gettitle($map);
10304: }
10305: if ($space eq 'filename') {
10306: if ($symbparm) {
10307: return &clutter((&decode_symb($symbparm))[2]);
10308: }
10309: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10310: }
1.1172.2.30 raeburn 10311:
10312: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10313: if ($space eq 'visibleparts') {
10314: my $navmap = Apache::lonnavmaps::navmap->new();
10315: my $item;
10316: if (ref($navmap)) {
10317: my $res = $navmap->getBySymb($symbparm);
10318: my $parts = $res->parts();
10319: if (ref($parts) eq 'ARRAY') {
10320: $item = join(',',@{$parts});
10321: }
10322: undef($navmap);
10323: }
10324: return $item;
10325: }
10326: }
10327: }
1.693 albertel 10328:
10329: my ($section, $group, @groups);
1.593 albertel 10330: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10331: if (($courseid eq '') && ($cid)) {
10332: $courseid = $cid;
10333: }
10334: if (($symbparm && $courseid) &&
10335: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10336:
1.218 albertel 10337: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10338:
1.60 www 10339: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10340: my $symbp=$symbparm;
1.735 albertel 10341: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10342:
10343: my $symbparm=$symbp.'.'.$spacequalifierrest;
10344: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10345:
1.620 albertel 10346: if (($env{'user.name'} eq $uname) &&
10347: ($env{'user.domain'} eq $udom)) {
10348: $section=$env{'request.course.sec'};
1.733 raeburn 10349: @groups = split(/:/,$env{'request.course.groups'});
10350: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10351: } else {
1.539 albertel 10352: if (! defined($usection)) {
1.551 albertel 10353: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10354: } else {
10355: $section = $usection;
10356: }
1.733 raeburn 10357: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10358: }
10359:
10360: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10361: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10362: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10363:
1.593 albertel 10364: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10365: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10366: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10367:
1.60 www 10368: # ----------------------------------------------------------- first, check user
1.624 albertel 10369:
10370: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10371: ([$courselevelr,'resource'],
10372: [$courselevelm,'map' ],
10373: [$courselevel, 'course' ]));
1.931 albertel 10374: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10375:
1.594 albertel 10376: # ------------------------------------------------ second, check some of course
1.684 raeburn 10377: my $coursereply;
1.691 raeburn 10378: if (@groups > 0) {
10379: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10380: $mapparm,$spacequalifierrest);
1.927 albertel 10381: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10382: }
1.96 www 10383:
1.684 raeburn 10384: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10385: $env{'course.'.$courseid.'.domain'},
10386: 'course',
10387: ([$seclevelr, 'resource'],
10388: [$seclevelm, 'map' ],
10389: [$seclevel, 'course' ],
10390: [$courselevelr,'resource']));
10391: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10392:
1.60 www 10393: # ------------------------------------------------------ third, check map parms
1.218 albertel 10394: my %parmhash=();
10395: my $thisparm='';
10396: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10397: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10398: &GDBM_READER(),0640)) {
1.218 albertel 10399: $thisparm=$parmhash{$symbparm};
10400: untie(%parmhash);
10401: }
1.927 albertel 10402: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10403: }
1.594 albertel 10404: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10405:
1.218 albertel 10406: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10407: my $filename;
10408: if (!$symbparm) { $symbparm=&symbread(); }
10409: if ($symbparm) {
1.409 www 10410: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10411: } else {
1.620 albertel 10412: $filename=$env{'request.filename'};
1.282 albertel 10413: }
10414: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10415: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10416: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10417: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10418:
1.927 albertel 10419: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10420: if ($symbparm && defined($courseid) &&
1.620 albertel 10421: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10422: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10423: $env{'course.'.$courseid.'.domain'},
10424: 'course',
1.927 albertel 10425: ([$courselevelm,'map' ],
10426: [$courselevel, 'course']));
10427: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10428: }
1.145 www 10429: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10430: unless ($space eq '0') {
1.336 albertel 10431: my @parts=split(/_/,$space);
10432: my $id=pop(@parts);
10433: my $part=join('_',@parts);
10434: if ($part eq '') { $part='0'; }
1.927 albertel 10435: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10436: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10437: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10438: }
1.395 albertel 10439: if ($recurse) { return undef; }
10440: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10441: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10442: # ---------------------------------------------------- Any other user namespace
10443: } elsif ($realm eq 'environment') {
10444: # ----------------------------------------------------------------- environment
1.620 albertel 10445: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10446: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10447: } else {
1.770 albertel 10448: if ($uname eq 'anonymous' && $udom eq '') {
10449: return '';
10450: }
1.219 albertel 10451: my %returnhash=&userenvironment($udom,$uname,
10452: $spacequalifierrest);
10453: return $returnhash{$spacequalifierrest};
10454: }
1.28 www 10455: } elsif ($realm eq 'system') {
1.48 www 10456: # ----------------------------------------------------------------- system.time
10457: if ($space eq 'time') {
10458: return time;
10459: }
1.696 albertel 10460: } elsif ($realm eq 'server') {
10461: # ----------------------------------------------------------------- system.time
10462: if ($space eq 'name') {
10463: return $ENV{'SERVER_NAME'};
10464: }
1.28 www 10465: }
1.48 www 10466: return '';
1.61 www 10467: }
10468:
1.927 albertel 10469: sub get_reply {
10470: my ($reply_value) = @_;
1.940 raeburn 10471: if (ref($reply_value) eq 'ARRAY') {
10472: if (wantarray) {
10473: return @$reply_value;
10474: }
10475: return $reply_value->[0];
10476: } else {
10477: return $reply_value;
1.927 albertel 10478: }
10479: }
10480:
1.691 raeburn 10481: sub check_group_parms {
10482: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10483: my @groupitems = ();
10484: my $resultitem;
1.927 albertel 10485: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10486: foreach my $group (@{$groups}) {
10487: foreach my $level (@levels) {
1.927 albertel 10488: my $item = $courseid.'.['.$group.'].'.$level->[0];
10489: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10490: }
10491: }
10492: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10493: $env{'course.'.$courseid.'.domain'},
10494: 'course',@groupitems);
10495: return $coursereply;
10496: }
10497:
10498: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10499: my ($courseid,@groups) = @_;
10500: @groups = sort(@groups);
1.691 raeburn 10501: return @groups;
10502: }
10503:
1.395 albertel 10504: sub packages_tab_default {
10505: my ($uri,$varname)=@_;
10506: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10507:
10508: my (@extension,@specifics,$do_default);
10509: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10510: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10511: if ($pack_type eq 'default') {
10512: $do_default=1;
10513: } elsif ($pack_type eq 'extension') {
10514: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10515: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10516: # only look at packages defaults for packages that this id is
1.738 albertel 10517: push(@specifics,[$package,$pack_type,$pack_part]);
10518: }
10519: }
10520: # first look for a package that matches the requested part id
10521: foreach my $package (@specifics) {
10522: my (undef,$pack_type,$pack_part)=@{$package};
10523: next if ($pack_part ne $part);
10524: if (defined($packagetab{"$pack_type&$name&default"})) {
10525: return $packagetab{"$pack_type&$name&default"};
10526: }
10527: }
10528: # look for any possible matching non extension_ package
10529: foreach my $package (@specifics) {
10530: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10531: if (defined($packagetab{"$pack_type&$name&default"})) {
10532: return $packagetab{"$pack_type&$name&default"};
10533: }
1.585 albertel 10534: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10535: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10536: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10537: }
10538: }
1.738 albertel 10539: # look for any posible extension_ match
10540: foreach my $package (@extension) {
10541: my ($package,$pack_type)=@{$package};
10542: if (defined($packagetab{"$pack_type&$name&default"})) {
10543: return $packagetab{"$pack_type&$name&default"};
10544: }
10545: if (defined($packagetab{$package."&$name&default"})) {
10546: return $packagetab{$package."&$name&default"};
10547: }
10548: }
10549: # look for a global default setting
10550: if ($do_default && defined($packagetab{"default&$name&default"})) {
10551: return $packagetab{"default&$name&default"};
10552: }
1.395 albertel 10553: return undef;
10554: }
10555:
1.334 albertel 10556: sub add_prefix_and_part {
10557: my ($prefix,$part)=@_;
10558: my $keyroot;
10559: if (defined($prefix) && $prefix !~ /^__/) {
10560: # prefix that has a part already
10561: $keyroot=$prefix;
10562: } elsif (defined($prefix)) {
10563: # prefix that is missing a part
10564: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10565: } else {
10566: # no prefix at all
10567: if (defined($part)) { $keyroot='_'.$part; }
10568: }
10569: return $keyroot;
10570: }
10571:
1.71 www 10572: # ---------------------------------------------------------------- Get metadata
10573:
1.599 albertel 10574: my %metaentry;
1.1070 www 10575: my %importedpartids;
1.71 www 10576: sub metadata {
1.176 www 10577: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10578: $uri=&declutter($uri);
1.288 albertel 10579: # if it is a non metadata possible uri return quickly
1.529 albertel 10580: if (($uri eq '') ||
10581: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10582: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10583: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10584: return undef;
10585: }
1.1172.2.49 raeburn 10586: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10587: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10588: return undef;
1.288 albertel 10589: }
1.73 www 10590: my $filename=$uri;
10591: $uri=~s/\.meta$//;
1.172 www 10592: #
10593: # Is the metadata already cached?
1.177 www 10594: # Look at timestamp of caching
1.172 www 10595: # Everything is cached by the main uri, libraries are never directly cached
10596: #
1.428 albertel 10597: if (!defined($liburi)) {
1.599 albertel 10598: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10599: if (defined($cached)) { return $result->{':'.$what}; }
10600: }
10601: {
1.1069 www 10602: # Imported parts would go here
1.1070 www 10603: my %importedids=();
10604: my @origfileimportpartids=();
1.1069 www 10605: my $importedparts=0;
1.172 www 10606: #
10607: # Is this a recursive call for a library?
10608: #
1.599 albertel 10609: # if (! exists($metacache{$uri})) {
10610: # $metacache{$uri}={};
10611: # }
1.924 albertel 10612: my $cachetime = 60*60;
1.171 www 10613: if ($liburi) {
10614: $liburi=&declutter($liburi);
10615: $filename=$liburi;
1.401 bowersj2 10616: } else {
1.599 albertel 10617: &devalidate_cache_new('meta',$uri);
10618: undef(%metaentry);
1.401 bowersj2 10619: }
1.140 www 10620: my %metathesekeys=();
1.73 www 10621: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10622: my $metastring;
1.1140 www 10623: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10624: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10625: $metastring =
1.929 albertel 10626: &Apache::lonnet::ssi_body($which,
1.924 albertel 10627: ('grade_target' => 'meta'));
10628: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10629: } elsif (($uri !~ m -^(editupload)/-) &&
10630: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10631: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10632: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10633: $metastring=&getfile($file);
1.489 albertel 10634: }
1.208 albertel 10635: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10636: my $token;
1.140 www 10637: undef %metathesekeys;
1.71 www 10638: while ($token=$parser->get_token) {
1.339 albertel 10639: if ($token->[0] eq 'S') {
10640: if (defined($token->[2]->{'package'})) {
1.172 www 10641: #
10642: # This is a package - get package info
10643: #
1.339 albertel 10644: my $package=$token->[2]->{'package'};
10645: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10646: if (defined($token->[2]->{'id'})) {
10647: $keyroot.='_'.$token->[2]->{'id'};
10648: }
1.599 albertel 10649: if ($metaentry{':packages'}) {
10650: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10651: } else {
1.599 albertel 10652: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10653: }
1.736 albertel 10654: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10655: my $part=$keyroot;
10656: $part=~s/^\_//;
1.736 albertel 10657: if ($pack_entry=~/^\Q$package\E\&/ ||
10658: $pack_entry=~/^\Q$package\E_0\&/) {
10659: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10660: # ignore package.tab specified default values
10661: # here &package_tab_default() will fetch those
10662: if ($subp eq 'default') { next; }
1.736 albertel 10663: my $value=$packagetab{$pack_entry};
1.432 albertel 10664: my $unikey;
10665: if ($pack =~ /_0$/) {
10666: $unikey='parameter_0_'.$name;
10667: $part=0;
10668: } else {
10669: $unikey='parameter'.$keyroot.'_'.$name;
10670: }
1.339 albertel 10671: if ($subp eq 'display') {
10672: $value.=' [Part: '.$part.']';
10673: }
1.599 albertel 10674: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10675: $metathesekeys{$unikey}=1;
1.599 albertel 10676: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10677: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10678: }
1.599 albertel 10679: if (defined($metaentry{':'.$unikey.'.default'})) {
10680: $metaentry{':'.$unikey}=
10681: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10682: }
1.339 albertel 10683: }
10684: }
10685: } else {
1.172 www 10686: #
10687: # This is not a package - some other kind of start tag
1.339 albertel 10688: #
10689: my $entry=$token->[1];
1.1068 www 10690: my $unikey='';
1.175 www 10691:
1.339 albertel 10692: if ($entry eq 'import') {
1.175 www 10693: #
10694: # Importing a library here
1.339 albertel 10695: #
1.1067 www 10696: my $location=$parser->get_text('/import');
10697: my $dir=$filename;
10698: $dir=~s|[^/]*$||;
10699: $location=&filelocation($dir,$location);
1.1069 www 10700:
1.1068 www 10701: my $importmode=$token->[2]->{'importmode'};
10702: if ($importmode eq 'problem') {
1.1069 www 10703: # Import as problem/response
1.1068 www 10704: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10705: } elsif ($importmode eq 'part') {
10706: # Import as part(s)
1.1069 www 10707: $importedparts=1;
10708: # We need to get the original file and the imported file to get the part order correct
10709: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10710: # Load and inspect original file
1.1070 www 10711: if ($#origfileimportpartids<0) {
10712: undef(%importedpartids);
10713: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10714: my $origfile=&getfile($origfilelocation);
10715: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10716: }
10717:
1.1069 www 10718: # Load and inspect imported file
10719: my $impfile=&getfile($location);
10720: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10721: if ($#impfilepartids>=0) {
10722: # This problem had parts
1.1070 www 10723: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10724: } else {
10725: # Importing by turning a single problem into a problem part
10726: # It gets the import-tags ID as part-ID
10727: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10728: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10729: }
1.1068 www 10730: } else {
10731: # Normal import
10732: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10733: if (defined($token->[2]->{'id'})) {
10734: $unikey.='_'.$token->[2]->{'id'};
10735: }
1.1067 www 10736: }
10737:
1.339 albertel 10738: if ($depthcount<20) {
1.736 albertel 10739: my $metadata =
10740: &metadata($uri,'keys', $location,$unikey,
10741: $depthcount+1);
10742: foreach my $meta (split(',',$metadata)) {
10743: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10744: $metathesekeys{$meta}=1;
1.339 albertel 10745: }
1.1068 www 10746:
10747: }
1.1067 www 10748: } else {
10749: #
10750: # Not importing, some other kind of non-package, non-library start tag
10751: #
10752: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10753: if (defined($token->[2]->{'id'})) {
10754: $unikey.='_'.$token->[2]->{'id'};
10755: }
1.339 albertel 10756: if (defined($token->[2]->{'name'})) {
10757: $unikey.='_'.$token->[2]->{'name'};
10758: }
10759: $metathesekeys{$unikey}=1;
1.736 albertel 10760: foreach my $param (@{$token->[3]}) {
10761: $metaentry{':'.$unikey.'.'.$param} =
10762: $token->[2]->{$param};
1.339 albertel 10763: }
10764: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10765: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10766: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10767: # only ws inside the tag, and not in default, so use default
10768: # as value
1.599 albertel 10769: $metaentry{':'.$unikey}=$default;
1.908 albertel 10770: } elsif ( $internaltext =~ /\S/ ) {
10771: # something interesting inside the tag
10772: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10773: } else {
1.908 albertel 10774: # no interesting values, don't set a default
1.339 albertel 10775: }
1.172 www 10776: # end of not-a-package not-a-library import
1.339 albertel 10777: }
1.172 www 10778: # end of not-a-package start tag
1.339 albertel 10779: }
1.172 www 10780: # the next is the end of "start tag"
1.339 albertel 10781: }
10782: }
1.483 albertel 10783: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10784: $extension = lc($extension);
10785: if ($extension eq 'htm') { $extension='html'; }
10786:
1.737 albertel 10787: foreach my $key (keys(%packagetab)) {
1.483 albertel 10788: #no specific packages #how's our extension
10789: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10790: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10791: \%metathesekeys);
10792: }
1.883 albertel 10793:
10794: if (!exists($metaentry{':packages'})
10795: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10796: foreach my $key (keys(%packagetab)) {
1.483 albertel 10797: #no specific packages well let's get default then
10798: if ($key!~/^default&/) { next; }
1.488 albertel 10799: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10800: \%metathesekeys);
10801: }
10802: }
1.338 www 10803: # are there custom rights to evaluate
1.599 albertel 10804: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10805:
1.338 www 10806: #
10807: # Importing a rights file here
1.339 albertel 10808: #
10809: unless ($depthcount) {
1.599 albertel 10810: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10811: my $dir=$filename;
10812: $dir=~s|[^/]*$||;
10813: $location=&filelocation($dir,$location);
1.736 albertel 10814: my $rights_metadata =
10815: &metadata($uri,'keys',$location,'_rights',
10816: $depthcount+1);
10817: foreach my $rights (split(',',$rights_metadata)) {
10818: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10819: $metathesekeys{$rights}=1;
1.339 albertel 10820: }
10821: }
10822: }
1.737 albertel 10823: # uniqifiy package listing
10824: my %seen;
10825: my @uniq_packages =
10826: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10827: $metaentry{':packages'} = join(',',@uniq_packages);
10828:
1.1070 www 10829: if ($importedparts) {
10830: # We had imported parts and need to rebuild partorder
10831: $metaentry{':partorder'}='';
10832: $metathesekeys{'partorder'}=1;
10833: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10834: if ($origfileimportpartids[$index] eq 'part') {
10835: # original part, part of the problem
10836: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10837: } else {
10838: # we have imported parts at this position
10839: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10840: }
10841: }
10842: $metaentry{':partorder'}=~s/^\,//;
10843: }
10844:
1.737 albertel 10845: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10846: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10847: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10848: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10849: # this is the end of "was not already recently cached
1.71 www 10850: }
1.599 albertel 10851: return $metaentry{':'.$what};
1.261 albertel 10852: }
10853:
1.488 albertel 10854: sub metadata_create_package_def {
1.483 albertel 10855: my ($uri,$key,$package,$metathesekeys)=@_;
10856: my ($pack,$name,$subp)=split(/\&/,$key);
10857: if ($subp eq 'default') { next; }
10858:
1.599 albertel 10859: if (defined($metaentry{':packages'})) {
10860: $metaentry{':packages'}.=','.$package;
1.483 albertel 10861: } else {
1.599 albertel 10862: $metaentry{':packages'}=$package;
1.483 albertel 10863: }
10864: my $value=$packagetab{$key};
10865: my $unikey;
10866: $unikey='parameter_0_'.$name;
1.599 albertel 10867: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10868: $$metathesekeys{$unikey}=1;
1.599 albertel 10869: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10870: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10871: }
1.599 albertel 10872: if (defined($metaentry{':'.$unikey.'.default'})) {
10873: $metaentry{':'.$unikey}=
10874: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10875: }
10876: }
10877:
1.261 albertel 10878: sub metadata_generate_part0 {
10879: my ($metadata,$metacache,$uri) = @_;
10880: my %allnames;
1.737 albertel 10881: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10882: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10883: my $part=$$metacache{':'.$metakey.'.part'};
10884: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10885: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10886: $allnames{$name}=$part;
10887: }
10888: }
10889: }
10890: foreach my $name (keys(%allnames)) {
10891: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10892: my $key=":parameter_0_$name";
1.261 albertel 10893: $$metacache{"$key.part"}='0';
10894: $$metacache{"$key.name"}=$name;
1.428 albertel 10895: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10896: $allnames{$name}.'_'.$name.
10897: '.type'};
1.428 albertel 10898: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10899: '.display'};
1.644 www 10900: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10901: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10902: $$metacache{"$key.display"}=$olddis;
10903: }
1.71 www 10904: }
10905:
1.764 albertel 10906: # ------------------------------------------------------ Devalidate title cache
10907:
10908: sub devalidate_title_cache {
10909: my ($url)=@_;
10910: if (!$env{'request.course.id'}) { return; }
10911: my $symb=&symbread($url);
10912: if (!$symb) { return; }
10913: my $key=$env{'request.course.id'}."\0".$symb;
10914: &devalidate_cache_new('title',$key);
10915: }
10916:
1.1014 droeschl 10917: # ------------------------------------------------- Get the title of a course
10918:
10919: sub current_course_title {
10920: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10921: }
1.301 www 10922: # ------------------------------------------------- Get the title of a resource
10923:
10924: sub gettitle {
10925: my $urlsymb=shift;
10926: my $symb=&symbread($urlsymb);
1.534 albertel 10927: if ($symb) {
1.620 albertel 10928: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10929: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10930: if (defined($cached)) {
10931: return $result;
10932: }
1.534 albertel 10933: my ($map,$resid,$url)=&decode_symb($symb);
10934: my $title='';
1.907 albertel 10935: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10936: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10937: } else {
10938: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10939: &GDBM_READER(),0640)) {
10940: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10941: $title=$bighash{'title_'.$mapid.'.'.$resid};
10942: untie(%bighash);
10943: }
1.534 albertel 10944: }
10945: $title=~s/\&colon\;/\:/gs;
10946: if ($title) {
1.1159 www 10947: # Remember both $symb and $title for dynamic metadata
10948: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10949: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10950: # Cache this title and then return it
1.599 albertel 10951: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10952: }
10953: $urlsymb=$url;
10954: }
10955: my $title=&metadata($urlsymb,'title');
10956: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10957: return $title;
1.301 www 10958: }
1.613 albertel 10959:
1.614 albertel 10960: sub get_slot {
10961: my ($which,$cnum,$cdom)=@_;
10962: if (!$cnum || !$cdom) {
1.790 albertel 10963: (undef,my $courseid)=&whichuser();
1.620 albertel 10964: $cdom=$env{'course.'.$courseid.'.domain'};
10965: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10966: }
1.703 albertel 10967: my $key=join("\0",'slots',$cdom,$cnum,$which);
10968: my %slotinfo;
10969: if (exists($remembered{$key})) {
10970: $slotinfo{$which} = $remembered{$key};
10971: } else {
10972: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10973: &Apache::lonhomework::showhash(%slotinfo);
10974: my ($tmp)=keys(%slotinfo);
10975: if ($tmp=~/^error:/) { return (); }
10976: $remembered{$key} = $slotinfo{$which};
10977: }
1.616 albertel 10978: if (ref($slotinfo{$which}) eq 'HASH') {
10979: return %{$slotinfo{$which}};
10980: }
10981: return $slotinfo{$which};
1.614 albertel 10982: }
1.1150 raeburn 10983:
10984: sub get_reservable_slots {
10985: my ($cnum,$cdom,$uname,$udom) = @_;
10986: my $now = time;
10987: my $reservable_info;
10988: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10989: if (exists($remembered{$key})) {
10990: $reservable_info = $remembered{$key};
10991: } else {
10992: my %resv;
10993: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10994: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10995: $reservable_info = \%resv;
10996: $remembered{$key} = $reservable_info;
10997: }
10998: return $reservable_info;
10999: }
11000:
11001: sub get_course_slots {
11002: my ($cnum,$cdom) = @_;
11003: my $hashid=$cnum.':'.$cdom;
11004: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11005: if (defined($cached)) {
11006: if (ref($result) eq 'HASH') {
11007: return %{$result};
11008: }
11009: } else {
11010: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11011: my ($tmp) = keys(%slots);
11012: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11013: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11014: return %slots;
11015: }
11016: }
11017: return;
11018: }
11019:
11020: sub devalidate_slots_cache {
11021: my ($cnum,$cdom)=@_;
11022: my $hashid=$cnum.':'.$cdom;
11023: &devalidate_cache_new('allslots',$hashid);
11024: }
11025:
1.1172.2.8 raeburn 11026: sub get_coursechange {
11027: my ($cdom,$cnum) = @_;
11028: if ($cdom eq '' || $cnum eq '') {
11029: return unless ($env{'request.course.id'});
11030: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11031: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11032: }
11033: my $hashid=$cdom.'_'.$cnum;
11034: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11035: if ((defined($cached)) && ($change ne '')) {
11036: return $change;
11037: } else {
11038: my %crshash;
11039: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11040: if ($crshash{'internal.contentchange'} eq '') {
11041: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11042: if ($change eq '') {
11043: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11044: $change = $crshash{'internal.created'};
11045: }
11046: } else {
11047: $change = $crshash{'internal.contentchange'};
11048: }
11049: my $cachetime = 600;
11050: &do_cache_new('crschange',$hashid,$change,$cachetime);
11051: }
11052: return $change;
11053: }
11054:
11055: sub devalidate_coursechange_cache {
11056: my ($cnum,$cdom)=@_;
11057: my $hashid=$cnum.':'.$cdom;
11058: &devalidate_cache_new('crschange',$hashid);
11059: }
11060:
1.31 www 11061: # ------------------------------------------------- Update symbolic store links
11062:
11063: sub symblist {
11064: my ($mapname,%newhash)=@_;
1.438 www 11065: $mapname=&deversion(&declutter($mapname));
1.31 www 11066: my %hash;
1.620 albertel 11067: if (($env{'request.course.fn'}) && (%newhash)) {
11068: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11069: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11070: foreach my $url (keys(%newhash)) {
1.711 albertel 11071: next if ($url eq 'last_known'
11072: && $env{'form.no_update_last_known'});
11073: $hash{declutter($url)}=&encode_symb($mapname,
11074: $newhash{$url}->[1],
11075: $newhash{$url}->[0]);
1.191 harris41 11076: }
1.31 www 11077: if (untie(%hash)) {
11078: return 'ok';
11079: }
11080: }
11081: }
11082: return 'error';
1.212 www 11083: }
11084:
11085: # --------------------------------------------------------------- Verify a symb
11086:
11087: sub symbverify {
1.1172.2.11 raeburn 11088: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11089: my $thisfn=$thisurl;
1.439 www 11090: $thisfn=&declutter($thisfn);
1.215 www 11091: # direct jump to resource in page or to a sequence - will construct own symbs
11092: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11093: # check URL part
1.409 www 11094: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11095:
1.431 www 11096: unless ($url eq $thisfn) { return 0; }
1.213 www 11097:
1.216 www 11098: $symb=&symbclean($symb);
1.510 www 11099: $thisurl=&deversion($thisurl);
1.439 www 11100: $thisfn=&deversion($thisfn);
1.213 www 11101:
11102: my %bighash;
11103: my $okay=0;
1.431 www 11104:
1.620 albertel 11105: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11106: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11107: my $noclutter;
1.1032 raeburn 11108: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11109: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11110: if ($map =~ m{^uploaded/.+\.page$}) {
11111: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11112: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11113: $noclutter = 1;
11114: }
11115: }
11116: my $ids;
11117: if ($noclutter) {
11118: $ids=$bighash{'ids_'.$thisurl};
11119: } else {
11120: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11121: }
1.1102 raeburn 11122: unless ($ids) {
1.1172.2.13 raeburn 11123: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11124: $ids=$bighash{$idkey};
1.216 www 11125: }
11126: if ($ids) {
11127: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11128: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11129: $symb =~ s/\?.+$//;
11130: }
1.800 albertel 11131: foreach my $id (split(/\,/,$ids)) {
11132: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11133: if (
11134: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11135: eq $symb) {
1.1172.2.11 raeburn 11136: if (ref($encstate)) {
11137: $$encstate = $bighash{'encrypted_'.$id};
11138: }
1.1172.2.13 raeburn 11139: if (($env{'request.role.adv'}) ||
11140: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11141: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11142: $okay=1;
11143: last;
11144: }
11145: }
11146: }
1.216 www 11147: }
1.213 www 11148: untie(%bighash);
11149: }
11150: return $okay;
1.31 www 11151: }
11152:
1.210 www 11153: # --------------------------------------------------------------- Clean-up symb
11154:
11155: sub symbclean {
11156: my $symb=shift;
1.568 albertel 11157: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11158: # remove version from map
11159: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11160:
1.210 www 11161: # remove version from URL
11162: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11163:
1.507 www 11164: # remove wrapper
11165:
1.510 www 11166: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11167: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11168: return $symb;
1.409 www 11169: }
11170:
11171: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11172:
11173: sub encode_symb {
11174: my ($map,$resid,$url)=@_;
11175: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11176: }
1.409 www 11177:
11178: sub decode_symb {
1.568 albertel 11179: my $symb=shift;
11180: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11181: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11182: return (&fixversion($map),$resid,&fixversion($url));
11183: }
11184:
11185: sub fixversion {
11186: my $fn=shift;
1.609 banghart 11187: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11188: my %bighash;
11189: my $uri=&clutter($fn);
1.620 albertel 11190: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11191: # is this cached?
1.599 albertel 11192: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11193: if (defined($cached)) { return $result; }
11194: # unfortunately not cached, or expired
1.620 albertel 11195: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11196: &GDBM_READER(),0640)) {
11197: if ($bighash{'version_'.$uri}) {
11198: my $version=$bighash{'version_'.$uri};
1.444 www 11199: unless (($version eq 'mostrecent') ||
11200: ($version==&getversion($uri))) {
1.440 www 11201: $uri=~s/\.(\w+)$/\.$version\.$1/;
11202: }
11203: }
11204: untie %bighash;
1.413 www 11205: }
1.599 albertel 11206: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11207: }
11208:
11209: sub deversion {
11210: my $url=shift;
11211: $url=~s/\.\d+\.(\w+)$/\.$1/;
11212: return $url;
1.210 www 11213: }
11214:
1.31 www 11215: # ------------------------------------------------------ Return symb list entry
11216:
11217: sub symbread {
1.1172.2.66 raeburn 11218: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11219: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11220: if (defined($env{$cache_str})) {
11221: if ($ignorecachednull) {
11222: return $env{$cache_str} unless ($env{$cache_str} eq '');
11223: } else {
11224: return $env{$cache_str};
11225: }
11226: }
1.242 www 11227: # no filename provided? try from environment
1.1172.2.54 raeburn 11228: unless ($thisfn) {
1.620 albertel 11229: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11230: return $env{$cache_str}=&symbclean($env{'request.symb'});
11231: }
11232: $thisfn=$env{'request.filename'};
1.44 www 11233: }
1.569 albertel 11234: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11235: # is that filename actually a symb? Verify, clean, and return
11236: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11237: if (&symbverify($thisfn,$1)) {
1.620 albertel 11238: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11239: }
1.242 www 11240: }
1.44 www 11241: $thisfn=declutter($thisfn);
1.31 www 11242: my %hash;
1.37 www 11243: my %bighash;
11244: my $syval='';
1.620 albertel 11245: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11246: my $targetfn = $thisfn;
1.609 banghart 11247: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11248: $targetfn = 'adm/wrapper/'.$thisfn;
11249: }
1.687 albertel 11250: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11251: $targetfn=$1;
11252: }
1.620 albertel 11253: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11254: &GDBM_READER(),0640)) {
1.481 raeburn 11255: $syval=$hash{$targetfn};
1.37 www 11256: untie(%hash);
11257: }
11258: # ---------------------------------------------------------- There was an entry
11259: if ($syval) {
1.601 albertel 11260: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11261: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11262: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11263: #return $env{$cache_str}='';
1.601 albertel 11264: #}
11265: #$syval.=$1;
11266: #}
1.37 www 11267: } else {
11268: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11269: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11270: &GDBM_READER(),0640)) {
1.37 www 11271: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11272: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11273: unless ($ids) {
11274: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11275: }
11276: unless ($ids) {
11277: # alias?
11278: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11279: }
1.37 www 11280: if ($ids) {
11281: # ------------------------------------------------------------------- Has ID(s)
11282: my @possibilities=split(/\,/,$ids);
1.39 www 11283: if ($#possibilities==0) {
11284: # ----------------------------------------------- There is only one possibility
1.37 www 11285: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11286: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11287: $resid,$thisfn);
1.1172.2.66 raeburn 11288: if (ref($possibles) eq 'HASH') {
11289: $possibles->{$syval} = 1;
11290: }
11291: if ($checkforblock) {
11292: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11293: if (@blockers) {
11294: $syval = '';
11295: return;
11296: }
11297: }
11298: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11299: # ------------------------------------------ There is more than one possibility
11300: my $realpossible=0;
1.800 albertel 11301: foreach my $id (@possibilities) {
11302: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11303: my $canaccess;
11304: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11305: $canaccess = 1;
11306: } else {
11307: $canaccess = &allowed('bre',$file);
11308: }
11309: if ($canaccess) {
11310: my ($mapid,$resid)=split(/\./,$id);
11311: if ($bighash{'map_type_'.$mapid} ne 'page') {
11312: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11313: $resid,$thisfn);
11314: if (ref($possibles) eq 'HASH') {
11315: $possibles->{$syval} = 1;
11316: }
11317: if ($checkforblock) {
11318: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11319: unless (@blockers > 0) {
11320: $syval = $poss_syval;
11321: $realpossible++;
11322: }
11323: } else {
11324: $syval = $poss_syval;
11325: $realpossible++;
11326: }
11327: }
1.39 www 11328: }
1.191 harris41 11329: }
1.39 www 11330: if ($realpossible!=1) { $syval=''; }
1.249 www 11331: } else {
11332: $syval='';
1.37 www 11333: }
11334: }
1.1172.2.66 raeburn 11335: untie(%bighash);
1.481 raeburn 11336: }
1.31 www 11337: }
1.62 www 11338: if ($syval) {
1.620 albertel 11339: return $env{$cache_str}=$syval;
1.62 www 11340: }
1.31 www 11341: }
1.949 raeburn 11342: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11343: return $env{$cache_str}='';
1.31 www 11344: }
11345:
11346: # ---------------------------------------------------------- Return random seed
11347:
1.32 www 11348: sub numval {
11349: my $txt=shift;
11350: $txt=~tr/A-J/0-9/;
11351: $txt=~tr/a-j/0-9/;
11352: $txt=~tr/K-T/0-9/;
11353: $txt=~tr/k-t/0-9/;
11354: $txt=~tr/U-Z/0-5/;
11355: $txt=~tr/u-z/0-5/;
11356: $txt=~s/\D//g;
1.564 albertel 11357: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11358: return int($txt);
1.368 albertel 11359: }
11360:
1.484 albertel 11361: sub numval2 {
11362: my $txt=shift;
11363: $txt=~tr/A-J/0-9/;
11364: $txt=~tr/a-j/0-9/;
11365: $txt=~tr/K-T/0-9/;
11366: $txt=~tr/k-t/0-9/;
11367: $txt=~tr/U-Z/0-5/;
11368: $txt=~tr/u-z/0-5/;
11369: $txt=~s/\D//g;
11370: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11371: my $total;
11372: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11373: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11374: return int($total);
11375: }
11376:
1.575 albertel 11377: sub numval3 {
11378: use integer;
11379: my $txt=shift;
11380: $txt=~tr/A-J/0-9/;
11381: $txt=~tr/a-j/0-9/;
11382: $txt=~tr/K-T/0-9/;
11383: $txt=~tr/k-t/0-9/;
11384: $txt=~tr/U-Z/0-5/;
11385: $txt=~tr/u-z/0-5/;
11386: $txt=~s/\D//g;
11387: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11388: my $total;
11389: foreach my $val (@txts) { $total+=$val; }
11390: if ($_64bit) { $total=(($total<<32)>>32); }
11391: return $total;
11392: }
11393:
1.675 albertel 11394: sub digest {
11395: my ($data)=@_;
11396: my $digest=&Digest::MD5::md5($data);
11397: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11398: my ($e,$f);
11399: {
11400: use integer;
11401: $e=($a+$b);
11402: $f=($c+$d);
11403: if ($_64bit) {
11404: $e=(($e<<32)>>32);
11405: $f=(($f<<32)>>32);
11406: }
11407: }
11408: if (wantarray) {
11409: return ($e,$f);
11410: } else {
11411: my $g;
11412: {
11413: use integer;
11414: $g=($e+$f);
11415: if ($_64bit) {
11416: $g=(($g<<32)>>32);
11417: }
11418: }
11419: return $g;
11420: }
11421: }
11422:
1.368 albertel 11423: sub latest_rnd_algorithm_id {
1.675 albertel 11424: return '64bit5';
1.366 albertel 11425: }
1.32 www 11426:
1.503 albertel 11427: sub get_rand_alg {
11428: my ($courseid)=@_;
1.790 albertel 11429: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11430: if ($courseid) {
1.620 albertel 11431: return $env{"course.$courseid.rndseed"};
1.503 albertel 11432: }
11433: return &latest_rnd_algorithm_id();
11434: }
11435:
1.562 albertel 11436: sub validCODE {
11437: my ($CODE)=@_;
11438: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11439: return 0;
11440: }
11441:
1.491 albertel 11442: sub getCODE {
1.620 albertel 11443: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11444: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11445: defined($Apache::lonhomework::parsing_a_task) ) &&
11446: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11447: return $Apache::lonhomework::history{'resource.CODE'};
11448: }
11449: return undef;
11450: }
1.1133 foxr 11451: #
11452: # Determines the random seed for a specific context:
11453: #
11454: # parameters:
11455: # symb - in course context the symb for the seed.
11456: # course_id - The course id of the form domain_coursenum.
11457: # domain - Domain for the user.
11458: # course - Course for the user.
11459: # cenv - environment of the course.
11460: #
11461: # NOTE:
11462: # All parameters are picked out of the environment if missing
11463: # or not defined.
11464: # If a symb cannot be determined the current time is used instead.
11465: #
11466: # For a given well defined symb, courside, domain, username,
11467: # and course environment, the seed is reproducible.
11468: #
1.31 www 11469: sub rndseed {
1.1133 foxr 11470: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11471: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11472: if (!defined($symb)) {
1.366 albertel 11473: unless ($symb=$wsymb) { return time; }
11474: }
1.1146 foxr 11475: if (!defined $courseid) {
11476: $courseid=$wcourseid;
11477: }
11478: if (!defined $domain) { $domain=$wdomain; }
11479: if (!defined $username) { $username=$wusername }
1.1133 foxr 11480:
11481: my $which;
11482: if (defined($cenv->{'rndseed'})) {
11483: $which = $cenv->{'rndseed'};
11484: } else {
11485: $which =&get_rand_alg($courseid);
11486: }
1.491 albertel 11487: if (defined(&getCODE())) {
1.675 albertel 11488: if ($which eq '64bit5') {
11489: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11490: } elsif ($which eq '64bit4') {
1.575 albertel 11491: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11492: } else {
11493: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11494: }
1.675 albertel 11495: } elsif ($which eq '64bit5') {
11496: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11497: } elsif ($which eq '64bit4') {
11498: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11499: } elsif ($which eq '64bit3') {
11500: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11501: } elsif ($which eq '64bit2') {
11502: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11503: } elsif ($which eq '64bit') {
11504: return &rndseed_64bit($symb,$courseid,$domain,$username);
11505: }
11506: return &rndseed_32bit($symb,$courseid,$domain,$username);
11507: }
11508:
11509: sub rndseed_32bit {
11510: my ($symb,$courseid,$domain,$username)=@_;
11511: {
11512: use integer;
11513: my $symbchck=unpack("%32C*",$symb) << 27;
11514: my $symbseed=numval($symb) << 22;
11515: my $namechck=unpack("%32C*",$username) << 17;
11516: my $nameseed=numval($username) << 12;
11517: my $domainseed=unpack("%32C*",$domain) << 7;
11518: my $courseseed=unpack("%32C*",$courseid);
11519: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11520: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11521: #&logthis("rndseed :$num:$symb");
1.564 albertel 11522: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11523: return $num;
11524: }
11525: }
11526:
11527: sub rndseed_64bit {
11528: my ($symb,$courseid,$domain,$username)=@_;
11529: {
11530: use integer;
11531: my $symbchck=unpack("%32S*",$symb) << 21;
11532: my $symbseed=numval($symb) << 10;
11533: my $namechck=unpack("%32S*",$username);
11534:
11535: my $nameseed=numval($username) << 21;
11536: my $domainseed=unpack("%32S*",$domain) << 10;
11537: my $courseseed=unpack("%32S*",$courseid);
11538:
11539: my $num1=$symbchck+$symbseed+$namechck;
11540: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11541: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11542: #&logthis("rndseed :$num:$symb");
1.564 albertel 11543: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11544: return "$num1,$num2";
1.155 albertel 11545: }
1.366 albertel 11546: }
11547:
1.443 albertel 11548: sub rndseed_64bit2 {
11549: my ($symb,$courseid,$domain,$username)=@_;
11550: {
11551: use integer;
11552: # strings need to be an even # of cahracters long, it it is odd the
11553: # last characters gets thrown away
11554: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11555: my $symbseed=numval($symb) << 10;
11556: my $namechck=unpack("%32S*",$username.' ');
11557:
11558: my $nameseed=numval($username) << 21;
1.501 albertel 11559: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11560: my $courseseed=unpack("%32S*",$courseid.' ');
11561:
11562: my $num1=$symbchck+$symbseed+$namechck;
11563: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11564: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11565: #&logthis("rndseed :$num:$symb");
1.803 albertel 11566: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11567: return "$num1,$num2";
11568: }
11569: }
11570:
11571: sub rndseed_64bit3 {
11572: my ($symb,$courseid,$domain,$username)=@_;
11573: {
11574: use integer;
11575: # strings need to be an even # of cahracters long, it it is odd the
11576: # last characters gets thrown away
11577: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11578: my $symbseed=numval2($symb) << 10;
11579: my $namechck=unpack("%32S*",$username.' ');
11580:
11581: my $nameseed=numval2($username) << 21;
1.443 albertel 11582: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11583: my $courseseed=unpack("%32S*",$courseid.' ');
11584:
11585: my $num1=$symbchck+$symbseed+$namechck;
11586: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11587: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11588: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11589: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11590:
1.503 albertel 11591: return "$num1:$num2";
1.443 albertel 11592: }
11593: }
11594:
1.575 albertel 11595: sub rndseed_64bit4 {
11596: my ($symb,$courseid,$domain,$username)=@_;
11597: {
11598: use integer;
11599: # strings need to be an even # of cahracters long, it it is odd the
11600: # last characters gets thrown away
11601: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11602: my $symbseed=numval3($symb) << 10;
11603: my $namechck=unpack("%32S*",$username.' ');
11604:
11605: my $nameseed=numval3($username) << 21;
11606: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11607: my $courseseed=unpack("%32S*",$courseid.' ');
11608:
11609: my $num1=$symbchck+$symbseed+$namechck;
11610: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11611: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11612: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11613: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11614:
1.575 albertel 11615: return "$num1:$num2";
11616: }
11617: }
11618:
1.675 albertel 11619: sub rndseed_64bit5 {
11620: my ($symb,$courseid,$domain,$username)=@_;
11621: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11622: return "$num1:$num2";
11623: }
11624:
1.366 albertel 11625: sub rndseed_CODE_64bit {
11626: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11627: {
1.366 albertel 11628: use integer;
1.443 albertel 11629: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11630: my $symbseed=numval2($symb);
1.491 albertel 11631: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11632: my $CODEseed=numval(&getCODE());
1.443 albertel 11633: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11634: my $num1=$symbseed+$CODEchck;
11635: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11636: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11637: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11638: if ($_64bit) { $num1=(($num1<<32)>>32); }
11639: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11640: return "$num1:$num2";
1.366 albertel 11641: }
11642: }
11643:
1.575 albertel 11644: sub rndseed_CODE_64bit4 {
11645: my ($symb,$courseid,$domain,$username)=@_;
11646: {
11647: use integer;
11648: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11649: my $symbseed=numval3($symb);
11650: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11651: my $CODEseed=numval3(&getCODE());
11652: my $courseseed=unpack("%32S*",$courseid.' ');
11653: my $num1=$symbseed+$CODEchck;
11654: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11655: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11656: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11657: if ($_64bit) { $num1=(($num1<<32)>>32); }
11658: if ($_64bit) { $num2=(($num2<<32)>>32); }
11659: return "$num1:$num2";
11660: }
11661: }
11662:
1.675 albertel 11663: sub rndseed_CODE_64bit5 {
11664: my ($symb,$courseid,$domain,$username)=@_;
11665: my $code = &getCODE();
11666: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11667: return "$num1:$num2";
11668: }
11669:
1.366 albertel 11670: sub setup_random_from_rndseed {
11671: my ($rndseed)=@_;
1.503 albertel 11672: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11673: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11674: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11675: &Math::Random::random_set_seed_from_phrase($rndseed);
11676: } else {
11677: &Math::Random::random_set_seed($num1,$num2);
11678: }
1.366 albertel 11679: } else {
11680: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11681: }
1.36 albertel 11682: }
11683:
1.474 albertel 11684: sub latest_receipt_algorithm_id {
1.835 albertel 11685: return 'receipt3';
1.474 albertel 11686: }
11687:
1.480 www 11688: sub recunique {
11689: my $fucourseid=shift;
11690: my $unique;
1.835 albertel 11691: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11692: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11693: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11694: } else {
11695: $unique=$perlvar{'lonReceipt'};
11696: }
11697: return unpack("%32C*",$unique);
11698: }
11699:
11700: sub recprefix {
11701: my $fucourseid=shift;
11702: my $prefix;
1.835 albertel 11703: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11704: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11705: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11706: } else {
11707: $prefix=$perlvar{'lonHostID'};
11708: }
11709: return unpack("%32C*",$prefix);
11710: }
11711:
1.76 www 11712: sub ireceipt {
1.474 albertel 11713: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11714:
11715: my $return =&recprefix($fucourseid).'-';
11716:
11717: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11718: $env{'request.state'} eq 'construct') {
11719: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11720: return $return;
11721: }
11722:
1.76 www 11723: my $cuname=unpack("%32C*",$funame);
11724: my $cudom=unpack("%32C*",$fudom);
11725: my $cucourseid=unpack("%32C*",$fucourseid);
11726: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11727: my $cunique=&recunique($fucourseid);
1.474 albertel 11728: my $cpart=unpack("%32S*",$part);
1.835 albertel 11729: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11730:
1.790 albertel 11731: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11732:
11733: $return.= ($cunique%$cuname+
11734: $cunique%$cudom+
11735: $cusymb%$cuname+
11736: $cusymb%$cudom+
11737: $cucourseid%$cuname+
11738: $cucourseid%$cudom+
11739: $cpart%$cuname+
11740: $cpart%$cudom);
11741: } else {
11742: $return.= ($cunique%$cuname+
11743: $cunique%$cudom+
11744: $cusymb%$cuname+
11745: $cusymb%$cudom+
11746: $cucourseid%$cuname+
11747: $cucourseid%$cudom);
11748: }
11749: return $return;
1.76 www 11750: }
11751:
11752: sub receipt {
1.474 albertel 11753: my ($part)=@_;
1.790 albertel 11754: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11755: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11756: }
1.260 ng 11757:
1.790 albertel 11758: sub whichuser {
11759: my ($passedsymb)=@_;
11760: my ($symb,$courseid,$domain,$name,$publicuser);
11761: if (defined($env{'form.grade_symb'})) {
11762: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11763: my $allowed=&allowed('vgr',$tmp_courseid);
11764: if (!$allowed &&
11765: exists($env{'request.course.sec'}) &&
11766: $env{'request.course.sec'} !~ /^\s*$/) {
11767: $allowed=&allowed('vgr',$tmp_courseid.
11768: '/'.$env{'request.course.sec'});
11769: }
11770: if ($allowed) {
11771: ($symb)=&get_env_multiple('form.grade_symb');
11772: $courseid=$tmp_courseid;
11773: ($domain)=&get_env_multiple('form.grade_domain');
11774: ($name)=&get_env_multiple('form.grade_username');
11775: return ($symb,$courseid,$domain,$name,$publicuser);
11776: }
11777: }
11778: if (!$passedsymb) {
11779: $symb=&symbread();
11780: } else {
11781: $symb=$passedsymb;
11782: }
11783: $courseid=$env{'request.course.id'};
11784: $domain=$env{'user.domain'};
11785: $name=$env{'user.name'};
11786: if ($name eq 'public' && $domain eq 'public') {
11787: if (!defined($env{'form.username'})) {
11788: $env{'form.username'}.=time.rand(10000000);
11789: }
11790: $name.=$env{'form.username'};
11791: }
11792: return ($symb,$courseid,$domain,$name,$publicuser);
11793:
11794: }
11795:
1.36 albertel 11796: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11797: # returns either the contents of the file or
11798: # -1 if the file doesn't exist
1.481 raeburn 11799: #
11800: # if the target is a file that was uploaded via DOCS,
11801: # a check will be made to see if a current copy exists on the local server,
11802: # if it does this will be served, otherwise a copy will be retrieved from
11803: # the home server for the course and stored in /home/httpd/html/userfiles on
11804: # the local server.
1.472 albertel 11805:
1.36 albertel 11806: sub getfile {
1.538 albertel 11807: my ($file) = @_;
1.609 banghart 11808: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11809: &repcopy($file);
11810: return &readfile($file);
11811: }
11812:
11813: sub repcopy_userfile {
11814: my ($file)=@_;
1.1142 raeburn 11815: my $londocroot = $perlvar{'lonDocRoot'};
11816: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11817: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11818: my ($cdom,$cnum,$filename) =
1.811 albertel 11819: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11820: my $uri="/uploaded/$cdom/$cnum/$filename";
11821: if (-e "$file") {
1.828 www 11822: # we already have a local copy, check it out
1.538 albertel 11823: my @fileinfo = stat($file);
1.828 www 11824: my $rtncode;
11825: my $info;
1.538 albertel 11826: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11827: if ($lwpresp ne 'ok') {
1.828 www 11828: # there is no such file anymore, even though we had a local copy
1.482 albertel 11829: if ($rtncode eq '404') {
1.538 albertel 11830: unlink($file);
1.482 albertel 11831: }
11832: return -1;
11833: }
11834: if ($info < $fileinfo[9]) {
1.828 www 11835: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11836: return 'ok';
1.828 www 11837: } else {
11838: # the file is outdated, get rid of it
11839: unlink($file);
1.482 albertel 11840: }
1.828 www 11841: }
11842: # one way or the other, at this point, we don't have the file
11843: # construct the correct path for the file
11844: my @parts = ($cdom,$cnum);
11845: if ($filename =~ m|^(.+)/[^/]+$|) {
11846: push @parts, split(/\//,$1);
11847: }
11848: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11849: foreach my $part (@parts) {
11850: $path .= '/'.$part;
11851: if (!-e $path) {
11852: mkdir($path,0770);
1.482 albertel 11853: }
11854: }
1.828 www 11855: # now the path exists for sure
11856: # get a user agent
11857: my $ua=new LWP::UserAgent;
11858: my $transferfile=$file.'.in.transfer';
11859: # FIXME: this should flock
11860: if (-e $transferfile) { return 'ok'; }
11861: my $request;
11862: $uri=~s/^\///;
1.980 raeburn 11863: my $homeserver = &homeserver($cnum,$cdom);
11864: my $protocol = $protocol{$homeserver};
11865: $protocol = 'http' if ($protocol ne 'https');
11866: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11867: my $response=$ua->request($request,$transferfile);
11868: # did it work?
11869: if ($response->is_error()) {
11870: unlink($transferfile);
11871: &logthis("Userfile repcopy failed for $uri");
11872: return -1;
11873: }
11874: # worked, rename the transfer file
11875: rename($transferfile,$file);
1.607 raeburn 11876: return 'ok';
1.481 raeburn 11877: }
11878:
1.517 albertel 11879: sub tokenwrapper {
11880: my $uri=shift;
1.980 raeburn 11881: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11882: $uri=~s|^/||;
1.620 albertel 11883: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11884: my $token=$1;
1.552 albertel 11885: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11886: if ($udom && $uname && $file) {
11887: $file=~s|(\?\.*)*$||;
1.949 raeburn 11888: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11889: my $homeserver = &homeserver($uname,$udom);
11890: my $protocol = $protocol{$homeserver};
11891: $protocol = 'http' if ($protocol ne 'https');
11892: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11893: (($uri=~/\?/)?'&':'?').'token='.$token.
11894: '&tokenissued='.$perlvar{'lonHostID'};
11895: } else {
11896: return '/adm/notfound.html';
11897: }
11898: }
11899:
1.828 www 11900: # call with reqtype HEAD: get last modification time
11901: # call with reqtype GET: get the file contents
11902: # Do not call this with reqtype GET for large files! It loads everything into memory
11903: #
1.481 raeburn 11904: sub getuploaded {
11905: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11906: $uri=~s/^\///;
1.980 raeburn 11907: my $homeserver = &homeserver($cnum,$cdom);
11908: my $protocol = $protocol{$homeserver};
11909: $protocol = 'http' if ($protocol ne 'https');
11910: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11911: my $ua=new LWP::UserAgent;
11912: my $request=new HTTP::Request($reqtype,$uri);
11913: my $response=$ua->request($request);
11914: $$rtncode = $response->code;
1.482 albertel 11915: if (! $response->is_success()) {
11916: return 'failed';
11917: }
11918: if ($reqtype eq 'HEAD') {
1.486 www 11919: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11920: } elsif ($reqtype eq 'GET') {
11921: $$info = $response->content;
1.472 albertel 11922: }
1.482 albertel 11923: return 'ok';
1.36 albertel 11924: }
11925:
1.481 raeburn 11926: sub readfile {
11927: my $file = shift;
11928: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11929: my $fh;
11930: open($fh,"<$file");
11931: my $a='';
1.800 albertel 11932: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11933: return $a;
11934: }
11935:
1.36 albertel 11936: sub filelocation {
1.590 banghart 11937: my ($dir,$file) = @_;
11938: my $location;
11939: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11940:
11941: if ($file =~ m-^/adm/-) {
11942: $file=~s-^/adm/wrapper/-/-;
11943: $file=~s-^/adm/coursedocs/showdoc/-/-;
11944: }
1.882 albertel 11945:
1.1139 www 11946: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11947: $location = $file;
1.609 banghart 11948: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11949: my ($udom,$uname,$filename)=
1.811 albertel 11950: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11951: my $home=&homeserver($uname,$udom);
11952: my $is_me=0;
11953: my @ids=¤t_machine_ids();
11954: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11955: if ($is_me) {
1.1117 foxr 11956: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11957: } else {
11958: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11959: $udom.'/'.$uname.'/'.$filename;
11960: }
1.882 albertel 11961: } elsif ($file =~ m-^/adm/-) {
11962: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11963: } else {
11964: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11965: $file=~s:^/(res|priv)/:/:;
11966: my $space=$1;
1.590 banghart 11967: if ( !( $file =~ m:^/:) ) {
11968: $location = $dir. '/'.$file;
11969: } else {
1.1142 raeburn 11970: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11971: }
1.59 albertel 11972: }
1.590 banghart 11973: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11974: while ($location=~m{/\.\./}) {
11975: if ($location =~ m{/[^/]+/\.\./}) {
11976: $location=~ s{/[^/]+/\.\./}{/}g;
11977: } else {
11978: $location=~ s{/\.\./}{/}g;
11979: }
11980: } #remove dir/..
1.590 banghart 11981: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11982: return $location;
1.46 www 11983: }
1.36 albertel 11984:
1.46 www 11985: sub hreflocation {
11986: my ($dir,$file)=@_;
1.980 raeburn 11987: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11988: $file=filelocation($dir,$file);
1.700 albertel 11989: } elsif ($file=~m-^/adm/-) {
11990: $file=~s-^/adm/wrapper/-/-;
11991: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11992: }
11993: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11994: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11995: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11996: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11997: {/uploaded/$1/$2/}x;
1.46 www 11998: }
1.913 albertel 11999: if ($file=~ m{^/userfiles/}) {
12000: $file =~ s{^/userfiles/}{/uploaded/};
12001: }
1.462 albertel 12002: return $file;
1.465 albertel 12003: }
12004:
1.1139 www 12005:
12006:
12007:
12008:
1.465 albertel 12009: sub current_machine_domains {
1.853 albertel 12010: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12011: }
12012:
12013: sub machine_domains {
12014: my ($hostname) = @_;
1.465 albertel 12015: my @domains;
1.838 albertel 12016: my %hostname = &all_hostnames();
1.465 albertel 12017: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12018: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12019: if ($hostname eq $name) {
1.844 albertel 12020: push(@domains,&host_domain($id));
1.465 albertel 12021: }
12022: }
12023: return @domains;
12024: }
12025:
12026: sub current_machine_ids {
1.853 albertel 12027: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12028: }
12029:
12030: sub machine_ids {
12031: my ($hostname) = @_;
12032: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12033: my @ids;
1.888 albertel 12034: my %name_to_host = &all_names();
1.889 albertel 12035: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12036: return @{ $name_to_host{$hostname} };
12037: }
12038: return;
1.31 www 12039: }
12040:
1.824 raeburn 12041: sub additional_machine_domains {
12042: my @domains;
12043: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12044: while( my $line = <$fh>) {
12045: $line =~ s/\s//g;
12046: push(@domains,$line);
12047: }
12048: return @domains;
12049: }
12050:
12051: sub default_login_domain {
12052: my $domain = $perlvar{'lonDefDomain'};
12053: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12054: foreach my $posdom (¤t_machine_domains(),
12055: &additional_machine_domains()) {
12056: if (lc($posdom) eq lc($testdomain)) {
12057: $domain=$posdom;
12058: last;
12059: }
12060: }
12061: return $domain;
12062: }
12063:
1.31 www 12064: # ------------------------------------------------------------- Declutters URLs
12065:
12066: sub declutter {
12067: my $thisfn=shift;
1.569 albertel 12068: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12069: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12070: $thisfn=~s{^/home/httpd/html}{};
12071: }
1.31 www 12072: $thisfn=~s/^\///;
1.697 albertel 12073: $thisfn=~s|^adm/wrapper/||;
12074: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12075: $thisfn=~s/^res\///;
1.1172 bisitz 12076: $thisfn=~s/^priv\///;
1.1032 raeburn 12077: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12078: $thisfn=~s/\?.+$//;
12079: }
1.268 www 12080: return $thisfn;
12081: }
12082:
12083: # ------------------------------------------------------------- Clutter up URLs
12084:
12085: sub clutter {
12086: my $thisfn='/'.&declutter(shift);
1.887 albertel 12087: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12088: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12089: $thisfn='/res'.$thisfn;
12090: }
1.1031 raeburn 12091: if ($thisfn !~m|^/adm|) {
12092: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12093: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12094: } else {
12095: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12096: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12097: if ($embstyle eq 'ssi'
12098: || ($embstyle eq 'hdn')
12099: || ($embstyle eq 'rat')
12100: || ($embstyle eq 'prv')
12101: || ($embstyle eq 'ign')) {
12102: #do nothing with these
12103: } elsif (($embstyle eq 'img')
1.695 albertel 12104: || ($embstyle eq 'emb')
12105: || ($embstyle eq 'wrp')) {
12106: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12107: } elsif ($embstyle eq 'unk'
12108: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12109: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12110: } else {
1.718 www 12111: # &logthis("Got a blank emb style");
1.695 albertel 12112: }
1.694 albertel 12113: }
12114: }
1.31 www 12115: return $thisfn;
1.12 www 12116: }
12117:
1.787 albertel 12118: sub clutter_with_no_wrapper {
12119: my $uri = &clutter(shift);
12120: if ($uri =~ m-^/adm/-) {
12121: $uri =~ s-^/adm/wrapper/-/-;
12122: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12123: }
12124: return $uri;
12125: }
12126:
1.557 albertel 12127: sub freeze_escape {
12128: my ($value)=@_;
12129: if (ref($value)) {
12130: $value=&nfreeze($value);
12131: return '__FROZEN__'.&escape($value);
12132: }
12133: return &escape($value);
12134: }
12135:
1.11 www 12136:
1.557 albertel 12137: sub thaw_unescape {
12138: my ($value)=@_;
12139: if ($value =~ /^__FROZEN__/) {
12140: substr($value,0,10,undef);
12141: $value=&unescape($value);
12142: return &thaw($value);
12143: }
12144: return &unescape($value);
12145: }
12146:
1.436 albertel 12147: sub correct_line_ends {
12148: my ($result)=@_;
12149: $$result =~s/\r\n/\n/mg;
12150: $$result =~s/\r/\n/mg;
1.415 albertel 12151: }
1.1 albertel 12152: # ================================================================ Main Program
12153:
1.184 www 12154: sub goodbye {
1.204 albertel 12155: &logthis("Starting Shut down");
1.443 albertel 12156: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12157: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12158: #converted
1.599 albertel 12159: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12160: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12161: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12162: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12163: #1.1 only
1.870 albertel 12164: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12165: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12166: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12167: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12168: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12169: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12170: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12171: &flushcourselogs();
12172: &logthis("Shutting down");
12173: }
12174:
1.852 albertel 12175: sub get_dns {
1.1172.2.17 raeburn 12176: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12177: if (!$ignore_cache) {
12178: my ($content,$cached)=
12179: &Apache::lonnet::is_cached_new('dns',$url);
12180: if ($cached) {
1.1172.2.17 raeburn 12181: &$func($content,$hashref);
1.869 albertel 12182: return;
12183: }
12184: }
12185:
12186: my %alldns;
1.852 albertel 12187: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12188: foreach my $dns (<$config>) {
12189: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12190: my $line = $1;
12191: my ($host,$protocol) = split(/:/,$line);
12192: if ($protocol ne 'https') {
12193: $protocol = 'http';
12194: }
12195: $alldns{$host} = $protocol;
1.869 albertel 12196: }
12197: while (%alldns) {
1.1172.2.52 raeburn 12198: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12199: my $ua=new LWP::UserAgent;
1.1134 raeburn 12200: $ua->timeout(30);
1.979 raeburn 12201: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12202: my $response=$ua->request($request);
1.979 raeburn 12203: delete($alldns{$dns});
1.852 albertel 12204: next if ($response->is_error());
12205: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12206: unless ($nocache) {
1.1172.2.23 raeburn 12207: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12208: }
12209: &$func(\@content,$hashref);
1.869 albertel 12210: return;
1.852 albertel 12211: }
12212: close($config);
1.871 albertel 12213: my $which = (split('/',$url))[3];
12214: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12215: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12216: my @content = <$config>;
1.1172.2.17 raeburn 12217: &$func(\@content,$hashref);
12218: return;
12219: }
12220:
12221: # ------------------------------------------------------Get DNS checksums file
12222: sub parse_dns_checksums_tab {
12223: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12224: my $lonhost = $perlvar{'lonHostID'};
12225: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12226: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12227: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12228: my $webconfdir = '/etc/httpd/conf';
12229: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12230: $webconfdir = '/etc/apache2';
12231: } elsif ($distro =~ /^sles(\d+)$/) {
12232: if ($1 >= 10) {
12233: $webconfdir = '/etc/apache2';
12234: }
12235: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12236: if ($1 >= 10.0) {
12237: $webconfdir = '/etc/apache2';
12238: }
12239: }
1.1172.2.17 raeburn 12240: my ($release,$timestamp) = split(/\-/,$loncaparev);
12241: my (%chksum,%revnum);
12242: if (ref($lines) eq 'ARRAY') {
12243: chomp(@{$lines});
1.1172.2.34 raeburn 12244: my $version = shift(@{$lines});
12245: if ($version eq $release) {
1.1172.2.17 raeburn 12246: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12247: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12248: if ($file =~ m{^/etc/httpd/conf}) {
12249: if ($webconfdir eq '/etc/apache2') {
12250: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12251: }
12252: }
1.1172.2.34 raeburn 12253: $chksum{$file} = $shasum;
12254: $revnum{$file} = $version;
1.1172.2.17 raeburn 12255: }
12256: if (ref($hashref) eq 'HASH') {
12257: %{$hashref} = (
12258: sums => \%chksum,
12259: versions => \%revnum,
12260: );
12261: }
12262: }
12263: }
1.869 albertel 12264: return;
1.852 albertel 12265: }
1.1172.2.17 raeburn 12266:
12267: sub fetch_dns_checksums {
12268: my %checksums;
1.1172.2.34 raeburn 12269: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12270: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12271: my ($release,$timestamp) = split(/\-/,$loncaparev);
12272: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12273: \%checksums);
12274: return \%checksums;
12275: }
12276:
1.327 albertel 12277: # ------------------------------------------------------------ Read domain file
12278: {
1.852 albertel 12279: my $loaded;
1.846 albertel 12280: my %domain;
12281:
1.852 albertel 12282: sub parse_domain_tab {
12283: my ($lines) = @_;
12284: foreach my $line (@$lines) {
12285: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12286:
1.846 albertel 12287: chomp($line);
1.852 albertel 12288: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12289: my %this_domain;
12290: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12291: 'lang_def', 'city', 'longi', 'lati',
12292: 'primary') {
12293: $this_domain{$field} = shift(@elements);
12294: }
12295: $domain{$name} = \%this_domain;
1.852 albertel 12296: }
12297: }
1.864 albertel 12298:
12299: sub reset_domain_info {
12300: undef($loaded);
12301: undef(%domain);
12302: }
12303:
1.852 albertel 12304: sub load_domain_tab {
1.1172.2.70 raeburn 12305: my ($ignore_cache,$nocache) = @_;
12306: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12307: my $fh;
12308: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12309: my @lines = <$fh>;
12310: &parse_domain_tab(\@lines);
1.448 albertel 12311: }
1.852 albertel 12312: close($fh);
12313: $loaded = 1;
1.327 albertel 12314: }
1.846 albertel 12315:
12316: sub domain {
1.852 albertel 12317: &load_domain_tab() if (!$loaded);
12318:
1.846 albertel 12319: my ($name,$what) = @_;
12320: return if ( !exists($domain{$name}) );
12321:
12322: if (!$what) {
12323: return $domain{$name}{'description'};
12324: }
12325: return $domain{$name}{$what};
12326: }
1.974 raeburn 12327:
12328: sub domain_info {
12329: &load_domain_tab() if (!$loaded);
12330: return %domain;
12331: }
12332:
1.327 albertel 12333: }
12334:
12335:
1.1 albertel 12336: # ------------------------------------------------------------- Read hosts file
12337: {
1.838 albertel 12338: my %hostname;
1.844 albertel 12339: my %hostdom;
1.845 albertel 12340: my %libserv;
1.852 albertel 12341: my $loaded;
1.888 albertel 12342: my %name_to_host;
1.1074 raeburn 12343: my %internetdom;
1.1107 raeburn 12344: my %LC_dns_serv;
1.852 albertel 12345:
12346: sub parse_hosts_tab {
12347: my ($file) = @_;
12348: foreach my $configline (@$file) {
12349: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12350: chomp($configline);
12351: if ($configline =~ /^\^/) {
12352: if ($configline =~ /^\^([\w.\-]+)/) {
12353: $LC_dns_serv{$1} = 1;
12354: }
12355: next;
12356: }
1.1074 raeburn 12357: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12358: $name=~s/\s//g;
12359: if ($id && $domain && $role && $name) {
12360: $hostname{$id}=$name;
1.888 albertel 12361: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12362: $hostdom{$id}=$domain;
12363: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12364: if (defined($protocol)) {
12365: if ($protocol eq 'https') {
12366: $protocol{$id} = $protocol;
12367: } else {
12368: $protocol{$id} = 'http';
12369: }
1.968 raeburn 12370: } else {
1.969 raeburn 12371: $protocol{$id} = 'http';
1.968 raeburn 12372: }
1.1074 raeburn 12373: if (defined($intdom)) {
12374: $internetdom{$id} = $intdom;
12375: }
1.852 albertel 12376: }
12377: }
12378: }
1.864 albertel 12379:
12380: sub reset_hosts_info {
1.897 albertel 12381: &purge_remembered();
1.864 albertel 12382: &reset_domain_info();
12383: &reset_hosts_ip_info();
1.892 albertel 12384: undef(%name_to_host);
1.864 albertel 12385: undef(%hostname);
12386: undef(%hostdom);
12387: undef(%libserv);
12388: undef($loaded);
12389: }
1.1 albertel 12390:
1.852 albertel 12391: sub load_hosts_tab {
1.1172.2.70 raeburn 12392: my ($ignore_cache,$nocache) = @_;
12393: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12394: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12395: my @config = <$config>;
12396: &parse_hosts_tab(\@config);
12397: close($config);
12398: $loaded=1;
1.1 albertel 12399: }
1.852 albertel 12400:
1.838 albertel 12401: sub hostname {
1.852 albertel 12402: &load_hosts_tab() if (!$loaded);
12403:
1.838 albertel 12404: my ($lonid) = @_;
12405: return $hostname{$lonid};
12406: }
1.845 albertel 12407:
1.838 albertel 12408: sub all_hostnames {
1.852 albertel 12409: &load_hosts_tab() if (!$loaded);
12410:
1.838 albertel 12411: return %hostname;
12412: }
1.845 albertel 12413:
1.888 albertel 12414: sub all_names {
1.1172.2.70 raeburn 12415: my ($ignore_cache,$nocache) = @_;
12416: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12417:
12418: return %name_to_host;
12419: }
12420:
1.974 raeburn 12421: sub all_host_domain {
12422: &load_hosts_tab() if (!$loaded);
12423: return %hostdom;
12424: }
12425:
1.845 albertel 12426: sub is_library {
1.852 albertel 12427: &load_hosts_tab() if (!$loaded);
12428:
1.845 albertel 12429: return exists($libserv{$_[0]});
12430: }
12431:
12432: sub all_library {
1.852 albertel 12433: &load_hosts_tab() if (!$loaded);
12434:
1.845 albertel 12435: return %libserv;
12436: }
12437:
1.1062 droeschl 12438: sub unique_library {
12439: #2x reverse removes all hostnames that appear more than once
12440: my %unique = reverse &all_library();
12441: return reverse %unique;
12442: }
12443:
1.841 albertel 12444: sub get_servers {
1.852 albertel 12445: &load_hosts_tab() if (!$loaded);
12446:
1.841 albertel 12447: my ($domain,$type) = @_;
12448: my %possible_hosts = ($type eq 'library') ? %libserv
12449: : %hostname;
12450: my %result;
1.842 albertel 12451: if (ref($domain) eq 'ARRAY') {
12452: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12453: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12454: $result{$host} = $hostname;
12455: }
12456: }
12457: } else {
12458: while ( my ($host,$hostname) = each(%possible_hosts)) {
12459: if ($hostdom{$host} eq $domain) {
12460: $result{$host} = $hostname;
12461: }
1.841 albertel 12462: }
12463: }
12464: return %result;
12465: }
1.845 albertel 12466:
1.1062 droeschl 12467: sub get_unique_servers {
12468: my %unique = reverse &get_servers(@_);
12469: return reverse %unique;
12470: }
12471:
1.844 albertel 12472: sub host_domain {
1.852 albertel 12473: &load_hosts_tab() if (!$loaded);
12474:
1.844 albertel 12475: my ($lonid) = @_;
12476: return $hostdom{$lonid};
12477: }
12478:
1.841 albertel 12479: sub all_domains {
1.852 albertel 12480: &load_hosts_tab() if (!$loaded);
12481:
1.841 albertel 12482: my %seen;
12483: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12484: return @uniq;
12485: }
1.1074 raeburn 12486:
12487: sub internet_dom {
12488: &load_hosts_tab() if (!$loaded);
12489:
12490: my ($lonid) = @_;
12491: return $internetdom{$lonid};
12492: }
1.1107 raeburn 12493:
12494: sub is_LC_dns {
12495: &load_hosts_tab() if (!$loaded);
12496:
12497: my ($hostname) = @_;
12498: return exists($LC_dns_serv{$hostname});
12499: }
12500:
1.1 albertel 12501: }
12502:
1.847 albertel 12503: {
12504: my %iphost;
1.856 albertel 12505: my %name_to_ip;
12506: my %lonid_to_ip;
1.869 albertel 12507:
1.847 albertel 12508: sub get_hosts_from_ip {
12509: my ($ip) = @_;
12510: my %iphosts = &get_iphost();
12511: if (ref($iphosts{$ip})) {
12512: return @{$iphosts{$ip}};
12513: }
12514: return;
1.839 albertel 12515: }
1.864 albertel 12516:
12517: sub reset_hosts_ip_info {
12518: undef(%iphost);
12519: undef(%name_to_ip);
12520: undef(%lonid_to_ip);
12521: }
1.856 albertel 12522:
12523: sub get_host_ip {
12524: my ($lonid) = @_;
12525: if (exists($lonid_to_ip{$lonid})) {
12526: return $lonid_to_ip{$lonid};
12527: }
12528: my $name=&hostname($lonid);
12529: my $ip = gethostbyname($name);
12530: return if (!$ip || length($ip) ne 4);
12531: $ip=inet_ntoa($ip);
12532: $name_to_ip{$name} = $ip;
12533: $lonid_to_ip{$lonid} = $ip;
12534: return $ip;
12535: }
1.847 albertel 12536:
12537: sub get_iphost {
1.1172.2.70 raeburn 12538: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12539:
1.869 albertel 12540: if (!$ignore_cache) {
12541: if (%iphost) {
12542: return %iphost;
12543: }
12544: my ($ip_info,$cached)=
12545: &Apache::lonnet::is_cached_new('iphost','iphost');
12546: if ($cached) {
12547: %iphost = %{$ip_info->[0]};
12548: %name_to_ip = %{$ip_info->[1]};
12549: %lonid_to_ip = %{$ip_info->[2]};
12550: return %iphost;
12551: }
12552: }
1.894 albertel 12553:
12554: # get yesterday's info for fallback
12555: my %old_name_to_ip;
12556: my ($ip_info,$cached)=
12557: &Apache::lonnet::is_cached_new('iphost','iphost');
12558: if ($cached) {
12559: %old_name_to_ip = %{$ip_info->[1]};
12560: }
12561:
1.1172.2.70 raeburn 12562: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12563: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12564: my $ip;
12565: if (!exists($name_to_ip{$name})) {
12566: $ip = gethostbyname($name);
12567: if (!$ip || length($ip) ne 4) {
1.894 albertel 12568: if (defined($old_name_to_ip{$name})) {
12569: $ip = $old_name_to_ip{$name};
12570: &logthis("Can't find $name defaulting to old $ip");
12571: } else {
12572: &logthis("Name $name no IP found");
12573: next;
12574: }
12575: } else {
12576: $ip=inet_ntoa($ip);
1.847 albertel 12577: }
12578: $name_to_ip{$name} = $ip;
12579: } else {
12580: $ip = $name_to_ip{$name};
1.653 albertel 12581: }
1.888 albertel 12582: foreach my $id (@{ $name_to_host{$name} }) {
12583: $lonid_to_ip{$id} = $ip;
12584: }
12585: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12586: }
1.1172.2.70 raeburn 12587: unless ($nocache) {
12588: &do_cache_new('iphost','iphost',
12589: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12590: 48*60*60);
12591: }
1.869 albertel 12592:
1.847 albertel 12593: return %iphost;
1.598 albertel 12594: }
12595:
1.992 raeburn 12596: #
12597: # Given a DNS returns the loncapa host name for that DNS
12598: #
12599: sub host_from_dns {
12600: my ($dns) = @_;
12601: my @hosts;
12602: my $ip;
12603:
1.993 raeburn 12604: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12605: $ip = $name_to_ip{$dns};
12606: }
12607: if (!$ip) {
12608: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12609: if (length($ip) == 4) {
12610: $ip = &IO::Socket::inet_ntoa($ip);
12611: }
12612: }
12613: if ($ip) {
12614: @hosts = get_hosts_from_ip($ip);
12615: return $hosts[0];
12616: }
12617: return undef;
1.986 foxr 12618: }
1.992 raeburn 12619:
1.1074 raeburn 12620: sub get_internet_names {
12621: my ($lonid) = @_;
12622: return if ($lonid eq '');
12623: my ($idnref,$cached)=
12624: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12625: if ($cached) {
12626: return $idnref;
12627: }
12628: my $ip = &get_host_ip($lonid);
12629: my @hosts = &get_hosts_from_ip($ip);
12630: my %iphost = &get_iphost();
12631: my (@idns,%seen);
12632: foreach my $id (@hosts) {
12633: my $dom = &host_domain($id);
12634: my $prim_id = &domain($dom,'primary');
12635: my $prim_ip = &get_host_ip($prim_id);
12636: next if ($seen{$prim_ip});
12637: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12638: foreach my $id (@{$iphost{$prim_ip}}) {
12639: my $intdom = &internet_dom($id);
12640: unless (grep(/^\Q$intdom\E$/,@idns)) {
12641: push(@idns,$intdom);
12642: }
12643: }
12644: }
12645: $seen{$prim_ip} = 1;
12646: }
1.1172.2.23 raeburn 12647: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12648: }
12649:
1.986 foxr 12650: }
12651:
1.1079 raeburn 12652: sub all_loncaparevs {
1.1172.2.39 raeburn 12653: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
1.1079 raeburn 12654: }
12655:
1.1172.2.27 raeburn 12656: # ------------------------------------------------------- Read loncaparev table
12657: {
12658: sub load_loncaparevs {
12659: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12660: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12661: while (my $configline=<$config>) {
12662: chomp($configline);
12663: my ($hostid,$loncaparev)=split(/:/,$configline);
12664: $loncaparevs{$hostid}=$loncaparev;
12665: }
12666: close($config);
12667: }
12668: }
12669: }
12670: }
12671:
12672: # ----------------------------------------------------- Read serverhostID table
12673: {
12674: sub load_serverhomeIDs {
12675: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12676: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12677: while (my $configline=<$config>) {
12678: chomp($configline);
12679: my ($name,$id)=split(/:/,$configline);
12680: $serverhomeIDs{$name}=$id;
12681: }
12682: close($config);
12683: }
12684: }
12685: }
12686: }
12687:
12688:
1.862 albertel 12689: BEGIN {
12690:
12691: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12692: unless ($readit) {
12693: {
12694: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12695: %perlvar = (%perlvar,%{$configvars});
12696: }
12697:
12698:
1.1 albertel 12699: # ------------------------------------------------------ Read spare server file
12700: {
1.448 albertel 12701: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12702:
12703: while (my $configline=<$config>) {
12704: chomp($configline);
1.284 matthew 12705: if ($configline) {
1.784 albertel 12706: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12707: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12708: push(@{ $spareid{$type} }, $host);
1.1 albertel 12709: }
12710: }
1.448 albertel 12711: close($config);
1.1 albertel 12712: }
1.11 www 12713: # ------------------------------------------------------------ Read permissions
12714: {
1.448 albertel 12715: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12716:
12717: while (my $configline=<$config>) {
1.448 albertel 12718: chomp($configline);
12719: if ($configline) {
12720: my ($role,$perm)=split(/ /,$configline);
12721: if ($perm ne '') { $pr{$role}=$perm; }
12722: }
1.11 www 12723: }
1.448 albertel 12724: close($config);
1.11 www 12725: }
12726:
12727: # -------------------------------------------- Read plain texts for permissions
12728: {
1.448 albertel 12729: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12730:
12731: while (my $configline=<$config>) {
1.448 albertel 12732: chomp($configline);
12733: if ($configline) {
1.742 raeburn 12734: my ($short,@plain)=split(/:/,$configline);
12735: %{$prp{$short}} = ();
12736: if (@plain > 0) {
12737: $prp{$short}{'std'} = $plain[0];
12738: for (my $i=1; $i<@plain; $i++) {
12739: $prp{$short}{'alt'.$i} = $plain[$i];
12740: }
12741: }
1.448 albertel 12742: }
1.135 www 12743: }
1.448 albertel 12744: close($config);
1.135 www 12745: }
12746:
12747: # ---------------------------------------------------------- Read package table
12748: {
1.448 albertel 12749: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12750:
12751: while (my $configline=<$config>) {
1.483 albertel 12752: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12753: chomp($configline);
12754: my ($short,$plain)=split(/:/,$configline);
12755: my ($pack,$name)=split(/\&/,$short);
12756: if ($plain ne '') {
12757: $packagetab{$pack.'&'.$name.'&name'}=$name;
12758: $packagetab{$short}=$plain;
12759: }
1.11 www 12760: }
1.448 albertel 12761: close($config);
1.329 matthew 12762: }
12763:
1.1172.2.27 raeburn 12764: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12765:
1.1172.2.27 raeburn 12766: &load_loncaparevs();
12767:
12768: # ------------------------------------------------------- Read serverhostID table
12769:
12770: &load_serverhomeIDs();
1.1074 raeburn 12771:
1.1172.2.27 raeburn 12772: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12773: {
12774: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12775: if (-e $file) {
12776: my $parser = HTML::LCParser->new($file);
12777: while (my $token = $parser->get_token()) {
12778: if ($token->[0] eq 'S') {
12779: my $item = $token->[1];
12780: my $name = $token->[2]{'name'};
12781: my $value = $token->[2]{'value'};
12782: if ($item ne '' && $name ne '' && $value ne '') {
12783: my $release = $parser->get_text();
12784: $release =~ s/(^\s*|\s*$ )//gx;
12785: $needsrelease{$item.':'.$name.':'.$value} = $release;
12786: }
12787: }
12788: }
12789: }
1.1073 raeburn 12790: }
12791:
1.1138 raeburn 12792: # ---------------------------------------------------------- Read managers table
12793: {
12794: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12795: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12796: while (my $configline=<$config>) {
12797: chomp($configline);
12798: next if ($configline =~ /^\#/);
12799: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12800: $managerstab{$configline} = 1;
12801: }
12802: }
12803: close($config);
12804: }
12805: }
12806: }
12807:
1.329 matthew 12808: # ------------- set up temporary directory
12809: {
1.1117 foxr 12810: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12811:
1.11 www 12812: }
12813:
1.794 albertel 12814: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12815: 'compress_threshold'=> 20_000,
12816: });
1.185 www 12817:
1.281 www 12818: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12819: $dumpcount=0;
1.958 www 12820: $locknum=0;
1.22 www 12821:
1.163 harris41 12822: &logtouch();
1.672 albertel 12823: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12824: $readit=1;
1.564 albertel 12825: {
12826: use integer;
12827: my $test=(2**32)+1;
1.568 albertel 12828: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12829: &logthis(" Detected 64bit platform ($_64bit)");
12830: }
1.195 www 12831: }
1.1 albertel 12832: }
1.179 www 12833:
1.1 albertel 12834: 1;
1.191 harris41 12835: __END__
12836:
1.243 albertel 12837: =pod
12838:
1.191 harris41 12839: =head1 NAME
12840:
1.243 albertel 12841: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12842:
12843: =head1 SYNOPSIS
12844:
1.243 albertel 12845: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12846:
12847: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12848:
1.243 albertel 12849: Common parameters:
12850:
12851: =over 4
12852:
12853: =item *
12854:
12855: $uname : an internal username (if $cname expecting a course Id specifically)
12856:
12857: =item *
12858:
12859: $udom : a domain (if $cdom expecting a course's domain specifically)
12860:
12861: =item *
12862:
12863: $symb : a resource instance identifier
12864:
12865: =item *
12866:
12867: $namespace : the name of a .db file that contains the data needed or
12868: being set.
12869:
12870: =back
12871:
1.394 bowersj2 12872: =head1 OVERVIEW
1.191 harris41 12873:
1.394 bowersj2 12874: lonnet provides subroutines which interact with the
12875: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12876: about classes, users, and resources.
1.243 albertel 12877:
12878: For many of these objects you can also use this to store data about
12879: them or modify them in various ways.
1.191 harris41 12880:
1.394 bowersj2 12881: =head2 Symbs
1.191 harris41 12882:
1.394 bowersj2 12883: To identify a specific instance of a resource, LON-CAPA uses symbols
12884: or "symbs"X<symb>. These identifiers are built from the URL of the
12885: map, the resource number of the resource in the map, and the URL of
12886: the resource itself. The latter is somewhat redundant, but might help
12887: if maps change.
12888:
12889: An example is
12890:
12891: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12892:
12893: The respective map entry is
12894:
12895: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12896: title="Problem 2">
12897: </resource>
12898:
12899: Symbs are used by the random number generator, as well as to store and
12900: restore data specific to a certain instance of for example a problem.
12901:
12902: =head2 Storing And Retrieving Data
12903:
12904: X<store()>X<cstore()>X<restore()>Three of the most important functions
12905: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12906: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12907: is is the non-critical message twin of cstore. These functions are for
12908: handlers to store a perl hash to a user's permanent data space in an
12909: easy manner, and to retrieve it again on another call. It is expected
12910: that a handler would use this once at the beginning to retrieve data,
12911: and then again once at the end to send only the new data back.
12912:
12913: The data is stored in the user's data directory on the user's
12914: homeserver under the ID of the course.
12915:
12916: The hash that is returned by restore will have all of the previous
12917: value for all of the elements of the hash.
12918:
12919: Example:
12920:
12921: #creating a hash
12922: my %hash;
12923: $hash{'foo'}='bar';
12924:
12925: #storing it
12926: &Apache::lonnet::cstore(\%hash);
12927:
12928: #changing a value
12929: $hash{'foo'}='notbar';
12930:
12931: #adding a new value
12932: $hash{'bar'}='foo';
12933: &Apache::lonnet::cstore(\%hash);
12934:
12935: #retrieving the hash
12936: my %history=&Apache::lonnet::restore();
12937:
12938: #print the hash
12939: foreach my $key (sort(keys(%history))) {
12940: print("\%history{$key} = $history{$key}");
12941: }
12942:
12943: Will print out:
1.191 harris41 12944:
1.394 bowersj2 12945: %history{1:foo} = bar
12946: %history{1:keys} = foo:timestamp
12947: %history{1:timestamp} = 990455579
12948: %history{2:bar} = foo
12949: %history{2:foo} = notbar
12950: %history{2:keys} = foo:bar:timestamp
12951: %history{2:timestamp} = 990455580
12952: %history{bar} = foo
12953: %history{foo} = notbar
12954: %history{timestamp} = 990455580
12955: %history{version} = 2
12956:
12957: Note that the special hash entries C<keys>, C<version> and
12958: C<timestamp> were added to the hash. C<version> will be equal to the
12959: total number of versions of the data that have been stored. The
12960: C<timestamp> attribute will be the UNIX time the hash was
12961: stored. C<keys> is available in every historical section to list which
12962: keys were added or changed at a specific historical revision of a
12963: hash.
12964:
12965: B<Warning>: do not store the hash that restore returns directly. This
12966: will cause a mess since it will restore the historical keys as if the
12967: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12968:
1.394 bowersj2 12969: Calling convention:
1.191 harris41 12970:
1.1172.2.27 raeburn 12971: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 12972: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12973:
1.394 bowersj2 12974: For more detailed information, see lonnet specific documentation.
1.191 harris41 12975:
1.394 bowersj2 12976: =head1 RETURN MESSAGES
1.191 harris41 12977:
1.394 bowersj2 12978: =over 4
1.191 harris41 12979:
1.394 bowersj2 12980: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12981:
1.394 bowersj2 12982: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12983: when the connection is brought back up
1.191 harris41 12984:
1.394 bowersj2 12985: =item * B<con_failed>: unable to contact remote host and unable to save message
12986: for later delivery
1.191 harris41 12987:
1.967 bisitz 12988: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12989:
1.394 bowersj2 12990: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12991: that was requested
1.191 harris41 12992:
1.243 albertel 12993: =back
1.191 harris41 12994:
1.243 albertel 12995: =head1 PUBLIC SUBROUTINES
1.191 harris41 12996:
1.243 albertel 12997: =head2 Session Environment Functions
1.191 harris41 12998:
1.243 albertel 12999: =over 4
1.191 harris41 13000:
1.394 bowersj2 13001: =item *
13002: X<appenv()>
1.949 raeburn 13003: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13004: the user envirnoment file, and will be restored for each access this
1.620 albertel 13005: user makes during this session, also modifies the %env for the current
1.949 raeburn 13006: process. Optional rolesarrayref - if defined contains a reference to an array
13007: of roles which are exempt from the restriction on modifying user.role entries
13008: in the user's environment.db and in %env.
1.191 harris41 13009:
13010: =item *
1.394 bowersj2 13011: X<delenv()>
1.987 raeburn 13012: B<delenv($delthis,$regexp)>: removes all items from the session
13013: environment file that begin with $delthis. If the
13014: optional second arg - $regexp - is true, $delthis is treated as a
13015: regular expression, otherwise \Q$delthis\E is used.
13016: The values are also deleted from the current processes %env.
1.191 harris41 13017:
1.795 albertel 13018: =item * get_env_multiple($name)
13019:
13020: gets $name from the %env hash, it seemlessly handles the cases where multiple
13021: values may be defined and end up as an array ref.
13022:
13023: returns an array of values
13024:
1.243 albertel 13025: =back
13026:
13027: =head2 User Information
1.191 harris41 13028:
1.243 albertel 13029: =over 4
1.191 harris41 13030:
13031: =item *
1.394 bowersj2 13032: X<queryauthenticate()>
13033: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13034: authentication scheme
13035:
13036: =item *
1.394 bowersj2 13037: X<authenticate()>
1.1073 raeburn 13038: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13039: authenticate user from domain's lib servers (first use the current
13040: one). C<$upass> should be the users password.
1.1073 raeburn 13041: $checkdefauth is optional (value is 1 if a check should be made to
13042: authenticate user using default authentication method, and allow
13043: account creation if username does not have account in the domain).
13044: $clientcancheckhost is optional (value is 1 if checking whether the
13045: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13046:
13047: =item *
1.394 bowersj2 13048: X<homeserver()>
13049: B<homeserver($uname,$udom)>: find the server which has
13050: the user's directory and files (there must be only one), this caches
13051: the answer, and also caches if there is a borken connection.
1.191 harris41 13052:
13053: =item *
1.394 bowersj2 13054: X<idget()>
13055: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13056: (IDs are a unique resource in a domain, there must be only 1 ID per
13057: username, and only 1 username per ID in a specific domain) (returns
13058: hash: id=>name,id=>name)
1.191 harris41 13059:
13060: =item *
1.394 bowersj2 13061: X<idrget()>
13062: B<idrget($udom,@unames)>: find the IDs behind a list of
13063: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13064:
13065: =item *
1.394 bowersj2 13066: X<idput()>
13067: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13068:
13069: =item *
1.394 bowersj2 13070: X<rolesinit()>
1.1169 droeschl 13071: B<rolesinit($udom,$username)>: get user privileges.
13072: returns user role, first access and timer interval hashes
1.243 albertel 13073:
13074: =item *
1.1171 droeschl 13075: X<privileged()>
13076: B<privileged($username,$domain)>: returns a true if user has a
13077: privileged and active role (i.e. su or dc), false otherwise.
13078:
13079: =item *
1.551 albertel 13080: X<getsection()>
13081: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13082: course $cname, return section name/number or '' for "not in course"
13083: and '-1' for "no section"
13084:
13085: =item *
1.394 bowersj2 13086: X<userenvironment()>
13087: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13088: passed in @what from the requested user's environment, returns a hash
13089:
1.858 raeburn 13090: =item *
13091: X<userlog_query()>
1.859 albertel 13092: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13093: activity.log file. %filters defines filters applied when parsing the
13094: log file. These can be start or end timestamps, or the type of action
13095: - log to look for Login or Logout events, check for Checkin or
13096: Checkout, role for role selection. The response is in the form
13097: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13098: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13099:
1.243 albertel 13100: =back
13101:
13102: =head2 User Roles
13103:
13104: =over 4
13105:
13106: =item *
13107:
1.1172.2.65 raeburn 13108: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13109: returns codes for allowed actions.
13110:
13111: The first argument is required, all others are optional.
13112:
13113: $priv is the privilege being checked.
13114: $uri contains additional information about what is being checked for access (e.g.,
13115: URL, course ID etc.).
13116: $symb is the unique resource instance identifier in a course; if needed,
13117: but not provided, it will be retrieved via a call to &symbread().
13118: $role is the role for which a priv is being checked (only used if priv is evb).
13119: $clientip is the user's IP address (only used when checking for access to portfolio
13120: files).
13121: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13122: prevents recursive calls to &allowed.
13123:
1.243 albertel 13124: F: full access
13125: U,I,K: authentication modes (cxx only)
13126: '': forbidden
13127: 1: user needs to choose course
13128: 2: browse allowed
1.766 albertel 13129: A: passphrase authentication needed
1.1172.2.65 raeburn 13130: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13131:
13132: =item *
13133:
1.1172.2.13 raeburn 13134: constructaccess($url,$setpriv) : check for access to construction space URL
13135:
13136: See if the owner domain and name in the URL match those in the
13137: expected environment. If so, return three element list
13138: ($ownername,$ownerdomain,$ownerhome).
13139:
13140: Otherwise return the null string.
13141:
13142: If second argument 'setpriv' is true, it assigns the privileges,
13143: and returns the same three element list, unless the owner has
13144: blocked "ad hoc" Domain Coordinator access to the Author Space,
13145: in which case the null string is returned.
13146:
13147: =item *
13148:
1.243 albertel 13149: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13150: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13151: and course level
13152:
13153: =item *
13154:
1.988 raeburn 13155: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13156: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13157: $type is Course (default) or Community.
1.988 raeburn 13158: If $forcedefault evaluates to true, text returned will be default
13159: text for $type. Otherwise, if this is a course, the text returned
13160: will be a custom name for the role (if defined in the course's
13161: environment). If no custom name is defined the default is returned.
13162:
1.832 raeburn 13163: =item *
13164:
1.1172.2.23 raeburn 13165: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13166: All arguments are optional. Returns a hash of a roles, either for
13167: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13168: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13169: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13170: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13171: For each key, value is set to colon-separated start and end times for
13172: the role. If no username and domain are specified, will default to
1.934 raeburn 13173: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13174: of role statuses (active, future or previous), roles
13175: (e.g., cc,in, st etc.) and domains of the roles which can be used
13176: to restrict the list of roles reported. If no array ref is
13177: provided for types, will default to return only active roles.
1.834 albertel 13178:
1.1172.2.13 raeburn 13179: =item *
13180:
13181: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13182: user: $uname:$udom has a role in the course: $cdom_$cnum.
13183:
13184: Additional optional arguments are: $type (if role checking is to be restricted
13185: to certain user status types -- previous (expired roles), active (currently
13186: available roles) or future (roles available in the future), and
13187: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13188: have active Domain Coordinator role in course's domain or in additional
13189: domains (specified in 'Domains to check for privileged users' in course
13190: environment -- set via: Course Settings -> Classlists and staff listing).
13191:
13192: =item *
13193:
13194: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13195: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13196: $possdomains and $possroles are optional array refs -- to domains to check and
13197: roles to check. If $possdomains is not specified, a dump will be done of the
13198: users' roles.db to check for a dc or su role in any domain. This can be
13199: time consuming if &privileged is called repeatedly (e.g., when displaying a
13200: classlist), so in such cases, supplying a $possdomains array is preferred, as
13201: this then allows &privileged_by_domain() to be used, which caches the identity
13202: of privileged users, eliminating the need for repeated calls to &dump().
13203:
13204: =item *
13205:
13206: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13207: where the outer hash keys are domains specified in the $possdomains array ref,
13208: next inner hash keys are privileged roles specified in the $roles array ref,
13209: and the innermost hash contains key = value pairs for username:domain = end:start
13210: for active or future "privileged" users with that role in that domain. To avoid
13211: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13212: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13213:
1.243 albertel 13214: =back
13215:
13216: =head2 User Modification
13217:
13218: =over 4
13219:
13220: =item *
13221:
1.957 raeburn 13222: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13223: user for the level given by URL. Optional start and end dates (leave empty
13224: string or zero for "no date")
1.191 harris41 13225:
13226: =item *
13227:
1.243 albertel 13228: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13229: change a users, password, possible return values are: ok,
13230: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13231: refused
1.191 harris41 13232:
13233: =item *
13234:
1.243 albertel 13235: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13236:
13237: =item *
13238:
1.1058 raeburn 13239: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13240: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13241:
13242: will update user information (firstname,middlename,lastname,generation,
13243: permanentemail), and if forceid is true, student/employee ID also.
13244: A user's institutional affiliation(s) can also be updated.
13245: User information fields will not be overwritten with empty entries
13246: unless the field is included in the $candelete array reference.
13247: This array is included when a single user is modified via "Manage Users",
13248: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13249:
13250: =item *
13251:
1.286 matthew 13252: modifystudent
13253:
1.957 raeburn 13254: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13255: The course id is resolved based on the current user's environment.
13256: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13257: associated with a course.
13258:
1.297 matthew 13259: This call is essentially a wrapper for lonnet::modifyuser and
13260: lonnet::modify_student_enrollment
1.286 matthew 13261:
13262: Inputs:
13263:
13264: =over 4
13265:
1.957 raeburn 13266: =item B<$udom> Student's loncapa domain
1.286 matthew 13267:
1.957 raeburn 13268: =item B<$uname> Student's loncapa login name
1.286 matthew 13269:
1.964 bisitz 13270: =item B<$uid> Student/Employee ID
1.286 matthew 13271:
1.957 raeburn 13272: =item B<$umode> Student's authentication mode
1.286 matthew 13273:
1.957 raeburn 13274: =item B<$upass> Student's password
1.286 matthew 13275:
1.957 raeburn 13276: =item B<$first> Student's first name
1.286 matthew 13277:
1.957 raeburn 13278: =item B<$middle> Student's middle name
1.286 matthew 13279:
1.957 raeburn 13280: =item B<$last> Student's last name
1.286 matthew 13281:
1.957 raeburn 13282: =item B<$gene> Student's generation
1.286 matthew 13283:
1.957 raeburn 13284: =item B<$usec> Student's section in course
1.286 matthew 13285:
13286: =item B<$end> Unix time of the roles expiration
13287:
13288: =item B<$start> Unix time of the roles start date
13289:
13290: =item B<$forceid> If defined, allow $uid to be changed
13291:
13292: =item B<$desiredhome> server to use as home server for student
13293:
1.957 raeburn 13294: =item B<$email> Student's permanent e-mail address
13295:
13296: =item B<$type> Type of enrollment (auto or manual)
13297:
1.963 raeburn 13298: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13299:
13300: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13301:
1.963 raeburn 13302: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13303:
1.963 raeburn 13304: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13305:
1.1172.2.19 raeburn 13306: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13307:
13308: =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 13309:
1.286 matthew 13310: =back
1.297 matthew 13311:
13312: =item *
13313:
13314: modify_student_enrollment
13315:
1.1172.2.31 raeburn 13316: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13317: 'role.request.course' must be defined for this function to proceed.
13318:
13319: Inputs:
13320:
13321: =over 4
13322:
1.1172.2.31 raeburn 13323: =item $udom, student's domain
1.297 matthew 13324:
1.1172.2.31 raeburn 13325: =item $uname, student's name
1.297 matthew 13326:
1.1172.2.31 raeburn 13327: =item $uid, student's user id
1.297 matthew 13328:
1.1172.2.31 raeburn 13329: =item $first, student's first name
1.297 matthew 13330:
13331: =item $middle
13332:
13333: =item $last
13334:
13335: =item $gene
13336:
13337: =item $usec
13338:
13339: =item $end
13340:
13341: =item $start
13342:
1.957 raeburn 13343: =item $type
13344:
13345: =item $locktype
13346:
13347: =item $cid
13348:
13349: =item $selfenroll
13350:
13351: =item $context
13352:
1.1172.2.19 raeburn 13353: =item $credits, number of credits student will earn from this class
13354:
1.1172.2.76! raeburn 13355: =item $instsec, institutional course section code for student
! 13356:
1.297 matthew 13357: =back
13358:
1.191 harris41 13359:
13360: =item *
13361:
1.243 albertel 13362: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13363: custom role; give a custom role to a user for the level given by URL. Specify
13364: name and domain of role author, and role name
1.191 harris41 13365:
13366: =item *
13367:
1.243 albertel 13368: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13369:
13370: =item *
13371:
1.243 albertel 13372: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13373:
13374: =back
13375:
13376: =head2 Course Infomation
13377:
13378: =over 4
1.191 harris41 13379:
13380: =item *
13381:
1.1118 foxr 13382: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13383: specified course id, including all environment settings for the
13384: course, the description of the course will be in the hash under the
13385: key 'description'
1.191 harris41 13386:
1.1118 foxr 13387: $options is an optional parameter that if supplied is a hash reference that controls
13388: what how this function works. It has the following key/values:
13389:
13390: =over 4
13391:
13392: =item freshen_cache
13393:
13394: If defined, and the environment cache for the course is valid, it is
13395: returned in the returned hash.
13396:
13397: =item one_time
13398:
13399: If defined, the last cache time is set to _now_
13400:
13401: =item user
13402:
13403: If defined, the supplied username is used instead of the current user.
13404:
13405:
13406: =back
13407:
1.191 harris41 13408: =item *
13409:
1.624 albertel 13410: resdata($name,$domain,$type,@which) : request for current parameter
13411: setting for a specific $type, where $type is either 'course' or 'user',
13412: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13413: answers for 10 minutes.
1.243 albertel 13414:
1.877 foxr 13415: =item *
13416:
13417: get_courseresdata($courseid, $domain) : dump the entire course resource
13418: data base, returning a hash that is keyed by the resource name and has
13419: values that are the resource value. I believe that the timestamps and
13420: versions are also returned.
13421:
1.1172.2.31 raeburn 13422: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13423: supplemental content area. This routine caches the number of files for
13424: 10 minutes.
13425:
1.243 albertel 13426: =back
13427:
13428: =head2 Course Modification
13429:
13430: =over 4
1.191 harris41 13431:
13432: =item *
13433:
1.243 albertel 13434: writecoursepref($courseid,%prefs) : write preferences (environment
13435: database) for a course
1.191 harris41 13436:
13437: =item *
13438:
1.1011 raeburn 13439: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13440:
13441: =item *
13442:
1.1038 raeburn 13443: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13444:
1.1167 droeschl 13445: =item *
13446:
13447: is_course($courseid), is_course($cdom, $cnum)
13448:
13449: Accepts either a combined $courseid (in the form of domain_courseid) or the
13450: two component version $cdom, $cnum. It checks if the specified course exists.
13451:
13452: Returns:
13453: undef if the course doesn't exist, otherwise
13454: in scalar context the combined courseid.
13455: in list context the two components of the course identifier, domain and
13456: courseid.
13457:
1.243 albertel 13458: =back
13459:
13460: =head2 Resource Subroutines
13461:
13462: =over 4
1.191 harris41 13463:
13464: =item *
13465:
1.243 albertel 13466: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13467:
13468: =item *
13469:
1.243 albertel 13470: repcopy($filename) : subscribes to the requested file, and attempts to
13471: replicate from the owning library server, Might return
1.607 raeburn 13472: 'unavailable', 'not_found', 'forbidden', 'ok', or
13473: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13474: resource. Expects the local filesystem pathname
13475: (/home/httpd/html/res/....)
13476:
13477: =back
13478:
13479: =head2 Resource Information
13480:
13481: =over 4
1.191 harris41 13482:
13483: =item *
13484:
1.1172.2.28 raeburn 13485: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13486: and returns the value of a variety of different possible values,
13487: $varname should be a request string, and the other parameters can be
13488: used to specify who and what one is asking about. Ordinarily, $cid
13489: does not need to be specified, as it is retrived from
13490: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13491: within lonuserstate::loadmap() when initializing a course, before
13492: $env{'request.course.id'} has been set, so it needs to be provided
13493: in that one case.
1.243 albertel 13494:
13495: Possible values for $varname are environment.lastname (or other item
13496: from the envirnment hash), user.name (or someother aspect about the
13497: user), resource.0.maxtries (or some other part and parameter of a
13498: resource)
1.204 albertel 13499:
13500: =item *
13501:
1.243 albertel 13502: directcondval($number) : get current value of a condition; reads from a state
13503: string
1.204 albertel 13504:
13505: =item *
13506:
1.243 albertel 13507: condval($condidx) : value of condition index based on state
1.204 albertel 13508:
13509: =item *
13510:
1.243 albertel 13511: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13512: resource's metadata, $what should be either a specific key, or either
13513: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13514: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13515:
13516: this function automatically caches all requests
1.191 harris41 13517:
13518: =item *
13519:
1.243 albertel 13520: metadata_query($query,$custom,$customshow) : make a metadata query against the
13521: network of library servers; returns file handle of where SQL and regex results
13522: will be stored for query
1.191 harris41 13523:
13524: =item *
13525:
1.1172.2.66 raeburn 13526: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13527: return symbolic list entry (all arguments optional).
13528:
13529: Args: filename is the filename (including path) for the file for which a symb
13530: is required; donotrecurse, if true will prevent calls to allowed() being made
13531: to check access status if more than one resource was found in the bighash
13532: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13533: a randompick); ignorecachednull, if true will prevent a symb of '' being
13534: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13535: cause possible symbs to be checked to determine if they are subject to content
13536: blocking, if so they will not be included as possible symbs; possibles is a
13537: ref to a hash, which, as a side effect, will be populated with all possible
13538: symbs (content blocking not tested).
13539:
1.243 albertel 13540: returns the data handle
1.191 harris41 13541:
13542: =item *
13543:
1.1172.2.17 raeburn 13544: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13545: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13546: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13547: on failure, user must be in a course, as it assumes the existence of
13548: the course initial hash, and uses $env('request.course.id'}. The third
13549: arg is an optional reference to a scalar. If this arg is passed in the
13550: call to symbverify, it will be set to 1 if the symb has been set to be
13551: encrypted; otherwise it will be null.
1.243 albertel 13552:
1.191 harris41 13553: =item *
13554:
1.243 albertel 13555: symbclean($symb) : removes versions numbers from a symb, returns the
13556: cleaned symb
1.191 harris41 13557:
13558: =item *
13559:
1.243 albertel 13560: is_on_map($uri) : checks if the $uri is somewhere on the current
13561: course map, user must be in a course for it to work.
1.191 harris41 13562:
13563: =item *
13564:
1.243 albertel 13565: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13566:
13567: =item *
13568:
1.243 albertel 13569: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13570: a random seed, all arguments are optional, if they aren't sent it uses the
13571: environment to derive them. Note: if symb isn't sent and it can't get one
13572: from &symbread it will use the current time as its return value
1.191 harris41 13573:
13574: =item *
13575:
1.243 albertel 13576: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13577: unfakeable, receipt
1.191 harris41 13578:
13579: =item *
13580:
1.620 albertel 13581: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13582:
13583: =item *
13584:
1.243 albertel 13585: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13586:
13587: =item *
13588:
1.243 albertel 13589: 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 13590:
13591: =item *
13592:
1.243 albertel 13593: 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 13594:
13595: =item *
13596:
1.243 albertel 13597: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13598:
13599: =item *
13600:
1.243 albertel 13601: devalidate($symb) : devalidate temporary spreadsheet calculations,
13602: forcing spreadsheet to reevaluate the resource scores next time.
13603:
1.1172.2.13 raeburn 13604: =item *
13605:
13606: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13607: when viewing in course context.
13608:
13609: input: six args -- filename (decluttered), course number, course domain,
13610: url, symb (if registered) and group (if this is a
13611: group item -- e.g., bulletin board, group page etc.).
13612:
13613: output: array of five scalars --
13614: $cfile -- url for file editing if editable on current server
13615: $home -- homeserver of resource (i.e., for author if published,
13616: or course if uploaded.).
13617: $switchserver -- 1 if server switch will be needed.
13618: $forceedit -- 1 if icon/link should be to go to edit mode
13619: $forceview -- 1 if icon/link should be to go to view mode
13620:
13621: =item *
13622:
13623: is_course_upload($file,$cnum,$cdom)
13624:
13625: Used in course context to determine if current file was uploaded to
13626: the course (i.e., would be found in /userfiles/docs on the course's
13627: homeserver.
13628:
13629: input: 3 args -- filename (decluttered), course number and course domain.
13630: output: boolean -- 1 if file was uploaded.
13631:
1.243 albertel 13632: =back
13633:
13634: =head2 Storing/Retreiving Data
13635:
13636: =over 4
1.191 harris41 13637:
13638: =item *
13639:
1.1172.2.64 raeburn 13640: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13641: permanently for this url; hashref needs to be given and should be a \%hashname;
13642: the remaining args aren't required and if they aren't passed or are '' they will
13643: be derived from the env (with the exception of $laststore, which is an
13644: optional arg used when a user's submission is stored in grading).
13645: $laststore is $version=$timestamp, where $version is the most recent version
13646: number retrieved for the corresponding $symb in the $namespace db file, and
13647: $timestamp is the timestamp for that transaction (UNIX time).
13648: $laststore is currently only passed when cstore() is called by
13649: structuretags::finalize_storage().
1.191 harris41 13650:
13651: =item *
13652:
1.1172.2.64 raeburn 13653: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13654: but uses critical subroutine
1.191 harris41 13655:
13656: =item *
13657:
1.243 albertel 13658: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13659: all args are optional
1.191 harris41 13660:
13661: =item *
13662:
1.717 albertel 13663: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13664: dumps the complete (or key matching regexp) namespace into a hash
13665: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13666: normally &store()ed into
13667:
13668: $range should be either an integer '100' (give me the first 100
13669: matching records)
13670: or be two integers sperated by a - with no spaces
13671: '30-50' (give me the 30th through the 50th matching
13672: records)
13673:
13674:
13675: =item *
13676:
1.1172.2.59 raeburn 13677: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13678: replaces a &store() version of data with a replacement set of data
13679: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13680: reference. If $tolog is true, the transaction is logged in the courselog
13681: with an action=PUTSTORE.
1.717 albertel 13682:
13683: =item *
13684:
1.243 albertel 13685: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13686: works very similar to store/cstore, but all data is stored in a
13687: temporary location and can be reset using tmpreset, $storehash should
13688: be a hash reference, returns nothing on success
1.191 harris41 13689:
13690: =item *
13691:
1.243 albertel 13692: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13693: similar to restore, but all data is stored in a temporary location and
13694: can be reset using tmpreset. Returns a hash of values on success,
13695: error string otherwise.
1.191 harris41 13696:
13697: =item *
13698:
1.243 albertel 13699: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13700: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13701:
13702: =item *
13703:
1.243 albertel 13704: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13705: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13706:
13707: =item *
13708:
1.243 albertel 13709: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13710: namesp ($udom and $uname are optional)
1.191 harris41 13711:
13712: =item *
13713:
1.702 albertel 13714: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13715: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13716: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13717:
1.702 albertel 13718: $range should be either an integer '100' (give me the first 100
13719: matching records)
13720: or be two integers sperated by a - with no spaces
13721: '30-50' (give me the 30th through the 50th matching
13722: records)
1.449 matthew 13723: =item *
13724:
13725: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13726: $store can be a scalar, an array reference, or if the amount to be
13727: incremented is > 1, a hash reference.
13728:
13729: ($udom and $uname are optional)
1.191 harris41 13730:
13731: =item *
13732:
1.243 albertel 13733: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13734: ($udom and $uname are optional)
1.191 harris41 13735:
13736: =item *
13737:
1.243 albertel 13738: cput($namespace,$storehash,$udom,$uname) : critical put
13739: ($udom and $uname are optional)
1.191 harris41 13740:
13741: =item *
13742:
1.748 albertel 13743: newput($namespace,$storehash,$udom,$uname) :
13744:
13745: Attempts to store the items in the $storehash, but only if they don't
13746: currently exist, if this succeeds you can be certain that you have
13747: successfully created a new key value pair in the $namespace db.
13748:
13749:
13750: Args:
13751: $namespace: name of database to store values to
13752: $storehash: hashref to store to the db
13753: $udom: (optional) domain of user containing the db
13754: $uname: (optional) name of user caontaining the db
13755:
13756: Returns:
13757: 'ok' -> succeeded in storing all keys of $storehash
13758: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13759: least <key> already existed in the db (other
13760: requested keys may also already exist)
1.967 bisitz 13761: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13762: 'con_lost' -> unable to contact request server
13763: 'refused' -> action was not allowed by remote machine
13764:
13765:
13766: =item *
13767:
1.243 albertel 13768: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13769: reference filled in from namesp (encrypts the return communication)
13770: ($udom and $uname are optional)
1.191 harris41 13771:
13772: =item *
13773:
1.243 albertel 13774: log($udom,$name,$home,$message) : write to permanent log for user; use
13775: critical subroutine
13776:
1.806 raeburn 13777: =item *
13778:
1.860 raeburn 13779: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13780: array reference filled in from namespace found in domain level on either
13781: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13782:
13783: =item *
13784:
1.860 raeburn 13785: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13786: domain level either on specified domain server ($uhome) or primary domain
13787: server ($udom and $uhome are optional)
1.806 raeburn 13788:
1.943 raeburn 13789: =item *
13790:
1.1172.2.35 raeburn 13791: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13792: for: authentication, language, quotas, timezone, date locale, and portal URL in
13793: the target domain.
13794:
13795: May also include additional key => value pairs for the following groups:
13796:
13797: =over
13798:
13799: =item
13800: disk quotas (MB allocated by default to portfolios and authoring spaces).
13801:
13802: =over
13803:
13804: =item defaultquota, authorquota
13805:
13806: =back
13807:
13808: =item
13809: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13810: portfolio for users).
13811:
13812: =over
13813:
13814: =item
13815: aboutme, blog, webdav, portfolio
13816:
13817: =back
13818:
13819: =item
13820: requestcourses: ability to request courses, and how requests are processed.
13821:
13822: =over
13823:
13824: =item
1.1172.2.37 raeburn 13825: official, unofficial, community, textbook
1.1172.2.35 raeburn 13826:
13827: =back
13828:
13829: =item
13830: inststatus: types of institutional affiliation, and order in which they are displayed.
13831:
13832: =over
13833:
13834: =item
1.1172.2.44 raeburn 13835: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13836:
13837: =back
13838:
13839: =item
13840: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13841: for course's uploaded content.
13842:
13843: =over
13844:
13845: =item
1.1172.2.68 raeburn 13846: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13847: communityquota, textbookquota
1.1172.2.35 raeburn 13848:
13849: =back
13850:
13851: =item
13852: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13853: on your servers.
13854:
13855: =over
13856:
13857: =item
13858: remotesessions, hostedsessions
13859:
13860: =back
13861:
13862: =back
13863:
13864: In cases where a domain coordinator has never used the "Set Domain Configuration"
13865: utility to create a configuration.db file on a domain's primary library server
13866: only the following domain defaults: auth_def, auth_arg_def, lang_def
13867: -- corresponding values are authentication type (internal, krb4, krb5,
13868: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13869: will be available. Values are retrieved from cache (if current), unless the
13870: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13871: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13872:
13873: Typical usage:
1.943 raeburn 13874:
1.1172.2.35 raeburn 13875: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13876:
1.243 albertel 13877: =back
13878:
13879: =head2 Network Status Functions
13880:
13881: =over 4
1.191 harris41 13882:
13883: =item *
13884:
1.1137 raeburn 13885: dirlist() : return directory list based on URI (first arg).
13886:
13887: Inputs: 1 required, 5 optional.
13888:
13889: =over
13890:
13891: =item
13892: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13893:
13894: =item
13895: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13896:
13897: =item
13898: $username - username of user/course to be listed. Extracted from $uri if absent.
13899:
13900: =item
13901: $getpropath - boolean: 1 if prepend path using &propath().
13902:
13903: =item
13904: $getuserdir - boolean: 1 if prepend path for "userfiles".
13905:
13906: =item
13907: $alternateRoot - path to prepend in place of path from $uri.
13908:
13909: =back
13910:
13911: Returns: Array of up to two items.
13912:
13913: =over
13914:
13915: a reference to an array of files/subdirectories
13916:
13917: =over
13918:
13919: Each element in the array of files/subdirectories is a & separated list of
13920: item name and the result of running stat on the item. If dirlist was requested
13921: for a file instead of a directory, the item name will be ''. For a directory
13922: listing, if the item is a metadata file, the element will end &N&M
13923: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13924: default copyright set (1).
13925:
13926: =back
13927:
13928: a scalar containing error condition (if encountered).
13929:
13930: =over
13931:
13932: =item
13933: no_host (no homeserver identified for $username:$domain).
13934:
13935: =item
13936: no_such_host (server contacted for listing not identified as valid host).
13937:
13938: =item
13939: con_lost (connection to remote server failed).
13940:
13941: =item
13942: refused (invalid $username:$domain received on lond side).
13943:
13944: =item
13945: no_such_dir (directory at specified path on lond side does not exist).
13946:
13947: =item
13948: empty (directory at specified path on lond side is empty).
13949:
13950: =over
13951:
13952: This is currently not encountered because the &ls3, &ls2,
13953: &ls (_handler) routines on the lond side do not filter out
13954: . and .. from a directory listing.
13955:
13956: =back
13957:
13958: =back
13959:
13960: =back
1.191 harris41 13961:
13962: =item *
13963:
1.243 albertel 13964: spareserver() : find server with least workload from spare.tab
13965:
1.986 foxr 13966:
13967: =item *
13968:
13969: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13970: if there is no corresponding loncapa host.
13971:
1.243 albertel 13972: =back
13973:
1.986 foxr 13974:
1.243 albertel 13975: =head2 Apache Request
13976:
13977: =over 4
1.191 harris41 13978:
13979: =item *
13980:
1.243 albertel 13981: ssi($url,%hash) : server side include, does a complete request cycle on url to
13982: localhost, posts hash
13983:
13984: =back
13985:
13986: =head2 Data to String to Data
13987:
13988: =over 4
1.191 harris41 13989:
13990: =item *
13991:
1.243 albertel 13992: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13993: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13994:
13995: =item *
13996:
1.243 albertel 13997: hashref2str($hashref) : convert a hashref into a string complete with
13998: escaping and '=' and '&' separators, supports elements that are
13999: arrayrefs and hashrefs
1.191 harris41 14000:
14001: =item *
14002:
1.243 albertel 14003: arrayref2str($arrayref) : convert an arrayref into a string complete
14004: with escaping and '&' separators, supports elements that are arrayrefs
14005: and hashrefs
1.191 harris41 14006:
14007: =item *
14008:
1.243 albertel 14009: str2hash($string) : convert string to hash using unescaping and
14010: splitting on '=' and '&', supports elements that are arrayrefs and
14011: hashrefs
1.191 harris41 14012:
14013: =item *
14014:
1.243 albertel 14015: str2array($string) : convert string to hash using unescaping and
14016: splitting on '&', supports elements that are arrayrefs and hashrefs
14017:
14018: =back
14019:
14020: =head2 Logging Routines
14021:
14022:
14023: These routines allow one to make log messages in the lonnet.log and
14024: lonnet.perm logfiles.
1.191 harris41 14025:
1.1119 foxr 14026: =over 4
14027:
1.191 harris41 14028: =item *
14029:
1.243 albertel 14030: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14031:
14032: =item *
14033:
1.243 albertel 14034: logthis() : append message to the normal lonnet.log file, it gets
14035: preiodically rolled over and deleted.
1.191 harris41 14036:
14037: =item *
14038:
1.243 albertel 14039: logperm() : append a permanent message to lonnet.perm.log, this log
14040: file never gets deleted by any automated portion of the system, only
14041: messages of critical importance should go in here.
14042:
1.1119 foxr 14043:
1.243 albertel 14044: =back
14045:
14046: =head2 General File Helper Routines
14047:
14048: =over 4
1.191 harris41 14049:
14050: =item *
14051:
1.481 raeburn 14052: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14053: (a) files in /uploaded
14054: (i) If a local copy of the file exists -
14055: compares modification date of local copy with last-modified date for
14056: definitive version stored on home server for course. If local copy is
14057: stale, requests a new version from the home server and stores it.
14058: If the original has been removed from the home server, then local copy
14059: is unlinked.
14060: (ii) If local copy does not exist -
14061: requests the file from the home server and stores it.
14062:
14063: If $caller is 'uploadrep':
14064: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14065: for request for files originally uploaded via DOCS.
14066: - returns 'ok' if fresh local copy now available, -1 otherwise.
14067:
14068: Otherwise:
14069: This indicates a call from the content generation phase of the request.
14070: - returns the entire contents of the file or -1.
14071:
14072: (b) files in /res
14073: - returns the entire contents of a file or -1;
14074: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14075:
1.712 albertel 14076:
14077: =item *
14078:
14079: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14080: reference
14081:
14082: returns either a stat() list of data about the file or an empty list
14083: if the file doesn't exist or couldn't find out about it (connection
14084: problems or user unknown)
14085:
1.191 harris41 14086: =item *
14087:
1.243 albertel 14088: filelocation($dir,$file) : returns file system location of a file
14089: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14090: directory that relative $file lookups are to looked in ($dir of /a/dir
14091: and a file of ../bob will become /a/bob)
1.191 harris41 14092:
14093: =item *
14094:
14095: hreflocation($dir,$file) : returns file system location or a URL; same as
14096: filelocation except for hrefs
14097:
14098: =item *
14099:
1.1172.2.49 raeburn 14100: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14101: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14102:
1.243 albertel 14103: =back
14104:
1.608 albertel 14105: =head2 Usererfile file routines (/uploaded*)
14106:
14107: =over 4
14108:
14109: =item *
14110:
14111: userfileupload(): main rotine for putting a file in a user or course's
14112: filespace, arguments are,
14113:
1.620 albertel 14114: formname - required - this is the name of the element in $env where the
1.608 albertel 14115: filename, and the contents of the file to create/modifed exist
1.620 albertel 14116: the filename is in $env{'form.'.$formname.'.filename'} and the
14117: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14118: context - if coursedoc, store the file in the course of the active role
14119: of the current user;
14120: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14121: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14122: subdir - required - subdirectory to put the file in under ../userfiles/
14123: if undefined, it will be placed in "unknown"
14124:
14125: (This routine calls clean_filename() to remove any dangerous
14126: characters from the filename, and then calls finuserfileupload() to
14127: complete the transaction)
14128:
14129: returns either the url of the uploaded file (/uploaded/....) if successful
14130: and /adm/notfound.html if unsuccessful
14131:
14132: =item *
14133:
14134: clean_filename(): routine for cleaing a filename up for storage in
14135: userfile space, argument is:
14136:
14137: filename - proposed filename
14138:
14139: returns: the new clean filename
14140:
14141: =item *
14142:
1.1090 raeburn 14143: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14144: userspace, probably shouldn't be called directly
14145:
14146: docuname: username or courseid of destination for the file
14147: docudom: domain of user/course of destination for the file
14148: formname: same as for userfileupload()
1.1090 raeburn 14149: fname: filename (including subdirectories) for the file
14150: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14151: allfiles: reference to hash used to store objects found by parser
14152: codebase: reference to hash used for codebases of java objects found by parser
14153: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14154: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14155: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14156: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14157: context: if 'overwrite', will move the uploaded file from its temporary location to
14158: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14159: mimetype: reference to scalar to accommodate mime type determined
14160: from File::MMagic if $parser = parse.
1.608 albertel 14161:
14162: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14163: and /adm/notfound.html if unsuccessful (or an error message if context
14164: was 'overwrite').
14165:
1.608 albertel 14166:
14167: =item *
14168:
14169: renameuserfile(): renames an existing userfile to a new name
14170:
14171: Args:
14172: docuname: username or courseid of destination for the file
14173: docudom: domain of user/course of destination for the file
14174: old: current file name (including any subdirs under userfiles)
14175: new: desired file name (including any subdirs under userfiles)
14176:
14177: =item *
14178:
14179: mkdiruserfile(): creates a directory is a userfiles dir
14180:
14181: Args:
14182: docuname: username or courseid of destination for the file
14183: docudom: domain of user/course of destination for the file
14184: dir: dir to create (including any subdirs under userfiles)
14185:
14186: =item *
14187:
14188: removeuserfile(): removes a file that exists in userfiles
14189:
14190: Args:
14191: docuname: username or courseid of destination for the file
14192: docudom: domain of user/course of destination for the file
14193: fname: filname to delete (including any subdirs under userfiles)
14194:
14195: =item *
14196:
14197: removeuploadedurl(): convience function for removeuserfile()
14198:
14199: Args:
14200: url: a full /uploaded/... url to delete
14201:
1.747 albertel 14202: =item *
14203:
14204: get_portfile_permissions():
14205: Args:
14206: domain: domain of user or course contain the portfolio files
14207: user: name of user or num of course contain the portfolio files
14208: Returns:
14209: hashref of a dump of the proper file_permissions.db
14210:
14211:
14212: =item *
14213:
14214: get_access_controls():
14215:
14216: Args:
14217: current_permissions: the hash ref returned from get_portfile_permissions()
14218: group: (optional) the group you want the files associated with
14219: file: (optional) the file you want access info on
14220:
14221: Returns:
1.749 raeburn 14222: a hash (keys are file names) of hashes containing
14223: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14224: values are XML containing access control settings (see below)
1.747 albertel 14225:
14226: Internal notes:
14227:
1.749 raeburn 14228: access controls are stored in file_permissions.db as key=value pairs.
14229: key -> path to file/file_name\0uniqueID:scope_end_start
14230: where scope -> public,guest,course,group,domains or users.
14231: end -> UNIX time for end of access (0 -> no end date)
14232: start -> UNIX time for start of access
14233:
14234: value -> XML description of access control
14235: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14236: <start></start>
14237: <end></end>
14238:
14239: <password></password> for scope type = guest
14240:
14241: <domain></domain> for scope type = course or group
14242: <number></number>
14243: <roles id="">
14244: <role></role>
14245: <access></access>
14246: <section></section>
14247: <group></group>
14248: </roles>
14249:
14250: <dom></dom> for scope type = domains
14251:
14252: <users> for scope type = users
14253: <user>
14254: <uname></uname>
14255: <udom></udom>
14256: </user>
14257: </users>
14258: </scope>
14259:
14260: Access data is also aggregated for each file in an additional key=value pair:
14261: key -> path to file/file_name\0accesscontrol
14262: value -> reference to hash
14263: hash contains key = value pairs
14264: where key = uniqueID:scope_end_start
14265: value = UNIX time record was last updated
14266:
14267: Used to improve speed of look-ups of access controls for each file.
14268:
14269: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14270:
1.1172.2.13 raeburn 14271: =item *
14272:
1.749 raeburn 14273: modify_access_controls():
14274:
14275: Modifies access controls for a portfolio file
14276: Args
14277: 1. file name
14278: 2. reference to hash of required changes,
14279: 3. domain
14280: 4. username
14281: where domain,username are the domain of the portfolio owner
14282: (either a user or a course)
14283:
14284: Returns:
14285: 1. result of additions or updates ('ok' or 'error', with error message).
14286: 2. result of deletions ('ok' or 'error', with error message).
14287: 3. reference to hash of any new or updated access controls.
14288: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14289: key = integer (inbound ID)
1.1172.2.13 raeburn 14290: value = uniqueID
14291:
14292: =item *
14293:
14294: get_timebased_id():
14295:
14296: Attempts to get a unique timestamp-based suffix for use with items added to a
14297: course via the Course Editor (e.g., folders, composite pages,
14298: group bulletin boards).
14299:
14300: Args: (first three required; six others optional)
14301:
14302: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14303: docssequence, or name of group
14304:
14305: 2. keyid (alphanumeric): name of temporary locking key in hash,
14306: e.g., num, boardids
14307:
14308: 3. namespace: name of gdbm file used to store suffixes already assigned;
14309: file will be named nohist_namespace.db
14310:
14311: 4. cdom: domain of course; default is current course domain from %env
14312:
14313: 5. cnum: course number; default is current course number from %env
14314:
14315: 6. idtype: set to concat if an additional digit is to be appended to the
14316: unix timestamp to form the suffix, if the plain timestamp is already
14317: in use. Default is to not do this, but simply increment the unix
14318: timestamp by 1 until a unique key is obtained.
14319:
14320: 7. who: holder of locking key; defaults to user:domain for user.
14321:
14322: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14323: retrying); default is 3.
14324:
14325: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14326:
14327: Returns:
14328:
14329: 1. suffix obtained (numeric)
14330:
14331: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14332:
14333: 3. error: contains (localized) error message if an error occurred.
14334:
1.747 albertel 14335:
1.608 albertel 14336: =back
14337:
1.243 albertel 14338: =head2 HTTP Helper Routines
14339:
14340: =over 4
14341:
1.191 harris41 14342: =item *
14343:
14344: escape() : unpack non-word characters into CGI-compatible hex codes
14345:
14346: =item *
14347:
14348: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14349:
1.243 albertel 14350: =back
14351:
14352: =head1 PRIVATE SUBROUTINES
14353:
14354: =head2 Underlying communication routines (Shouldn't call)
14355:
14356: =over 4
14357:
14358: =item *
14359:
14360: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14361:
14362: =item *
14363:
14364: reply() : uses subreply to send a message to remote machine, logs all failures
14365:
14366: =item *
14367:
14368: critical() : passes a critical message to another server; if cannot
14369: get through then place message in connection buffer directory and
14370: returns con_delayed, if incapable of saving message, returns
14371: con_failed
14372:
14373: =item *
14374:
14375: reconlonc() : tries to reconnect lonc client processes.
14376:
14377: =back
14378:
14379: =head2 Resource Access Logging
14380:
14381: =over 4
14382:
14383: =item *
14384:
14385: flushcourselogs() : flush (save) buffer logs and access logs
14386:
14387: =item *
14388:
14389: courselog($what) : save message for course in hash
14390:
14391: =item *
14392:
14393: courseacclog($what) : save message for course using &courselog(). Perform
14394: special processing for specific resource types (problems, exams, quizzes, etc).
14395:
1.191 harris41 14396: =item *
14397:
14398: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14399: as a PerlChildExitHandler
1.243 albertel 14400:
14401: =back
14402:
14403: =head2 Other
14404:
14405: =over 4
14406:
14407: =item *
14408:
14409: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14410:
14411: =back
14412:
14413: =cut
1.877 foxr 14414:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>