Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.89
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.89! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.88 2017/01/21 22:03:06 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.1172.2.79 raeburn 105: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 373: sleep(0.1);
1.549 foxr 374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.1172.2.79 raeburn 391: sleep(0.1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
1.1172.2.79 raeburn 484: sleep 1;
1.1 albertel 485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 847: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
848: $try_server));
1.1123 raeburn 849: ($spare_server, $lowest_load) =
850: &compare_server_load($try_server, $spare_server, $lowest_load);
851: }
1.1083 raeburn 852: }
1.784 albertel 853:
1.1123 raeburn 854: my $found_server = ($spare_server ne '' && $lowest_load < 100);
855:
856: if (!$found_server) {
857: if (ref($spareshash->{'default'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,
860: $remotesessions,$try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
1.1172.2.41 raeburn 884: my ($try_server, $spare_server, $lowest_load, $required) = @_;
885:
886: if ($required) {
887: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
888: my $remoterev = &get_server_loncaparev(undef,$try_server);
889: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
890: if (($major eq '' && $minor eq '') ||
891: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
892: return ($spare_server,$lowest_load);
893: }
894: }
1.784 albertel 895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1172.2.47 raeburn 955: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1172.2.47 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
960: if ($skiploadbal) {
961: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
962: unless (defined($cached)) {
963: my $cachetime = 60*60*24;
964: my %domconfig =
965: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
966: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
967: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
968: $cachetime);
969: }
970: }
971: }
1.1076 raeburn 972: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 973: my $loginvia;
1.1172.2.47 raeburn 974: if ($skiploadbal) {
975: if (ref($balancers) eq 'HASH') {
976: next if (exists($balancers->{$lonhost}));
977: }
978: }
1.1115 raeburn 979: if ($checkloginvia) {
980: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 981: if ($loginvia) {
982: my ($server,$path) = split(/:/,$loginvia);
983: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 984: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 985: if ($login_host eq $server) {
986: $portal_path = $path;
1.1151 raeburn 987: $isredirect = 1;
1.1116 raeburn 988: }
989: } else {
990: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 992: if ($login_host eq $lonhost) {
993: $portal_path = '';
1.1151 raeburn 994: $isredirect = '';
1.1116 raeburn 995: }
996: }
997: } else {
1.1076 raeburn 998: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 999: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1000: }
1001: }
1002: if ($login_host ne '') {
1.1116 raeburn 1003: $hostname = &hostname($login_host);
1.1076 raeburn 1004: }
1.1172.2.88 raeburn 1005: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
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 {
1.1172.2.88 raeburn 1277: my ($uname,$udom,$caller) = @_;
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.88 raeburn 1428: unless ($caller eq 'login') {
1429: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1430: $is_balancer = 0;
1431: if ($uname ne '' && $udom ne '') {
1432: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5 raeburn 1433:
1.1172.2.88 raeburn 1434: &appenv({'user.loadbalexempt' => $lonhost,
1435: 'user.loadbalcheck.time' => time});
1436: }
1.1172.2.5 raeburn 1437: }
1.1129 raeburn 1438: }
1439: }
1440: }
1441: return ($is_balancer,$otherserver);
1442: }
1443:
1.1172.2.12 raeburn 1444: sub check_balancer_result {
1445: my ($result,@hosts) = @_;
1446: my ($is_balancer,$currtargets,$currrules);
1447: if (ref($result) eq 'HASH') {
1448: if ($result->{'lonhost'} ne '') {
1449: my $currbalancer = $result->{'lonhost'};
1450: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1451: $is_balancer = 1;
1452: $currtargets = $result->{'targets'};
1453: $currrules = $result->{'rules'};
1454: }
1455: } else {
1456: foreach my $key (keys(%{$result})) {
1457: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1458: (ref($result->{$key}) eq 'HASH')) {
1459: $is_balancer = 1;
1460: $currrules = $result->{$key}{'rules'};
1461: $currtargets = $result->{$key}{'targets'};
1462: last;
1463: }
1464: }
1465: }
1466: }
1467: return ($is_balancer,$currtargets,$currrules);
1468: }
1469:
1.1129 raeburn 1470: sub get_loadbalancer_targets {
1471: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1472: my $offloadto;
1.1172.2.4 raeburn 1473: if ($rule_in_effect eq 'none') {
1474: return [$perlvar{'lonHostID'}];
1475: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1476: $offloadto = $currtargets;
1477: } else {
1478: if ($rule_in_effect eq 'homeserver') {
1479: my $homeserver = &homeserver($uname,$udom);
1480: if ($homeserver ne 'no_host') {
1481: $offloadto = [$homeserver];
1482: }
1483: } elsif ($rule_in_effect eq 'externalbalancer') {
1484: my %domconfig =
1485: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1486: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1487: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1488: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1489: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1490: }
1491: }
1492: } else {
1.1172.2.7 raeburn 1493: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1494: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1495: if (&hostname($remotebalancer) ne '') {
1496: $offloadto = [$remotebalancer];
1497: }
1498: }
1499: } elsif (&hostname($rule_in_effect) ne '') {
1500: $offloadto = [$rule_in_effect];
1501: }
1502: }
1503: return $offloadto;
1504: }
1505:
1.1127 raeburn 1506: sub internet_dom_servers {
1507: my ($dom) = @_;
1508: my (%uniqservers,%servers);
1509: my $primaryserver = &hostname(&domain($dom,'primary'));
1510: my @machinedoms = &machine_domains($primaryserver);
1511: foreach my $mdom (@machinedoms) {
1512: my %currservers = %servers;
1513: my %server = &get_servers($mdom);
1514: %servers = (%currservers,%server);
1515: }
1516: my %by_hostname;
1517: foreach my $id (keys(%servers)) {
1518: push(@{$by_hostname{$servers{$id}}},$id);
1519: }
1520: foreach my $hostname (sort(keys(%by_hostname))) {
1521: if (@{$by_hostname{$hostname}} > 1) {
1522: my $match = 0;
1523: foreach my $id (@{$by_hostname{$hostname}}) {
1524: if (&host_domain($id) eq $dom) {
1525: $uniqservers{$id} = $hostname;
1526: $match = 1;
1527: }
1528: }
1529: unless ($match) {
1530: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1531: }
1532: } else {
1533: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1534: }
1535: }
1536: return %uniqservers;
1537: }
1538:
1.1 albertel 1539: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1540:
1.599 albertel 1541: my %homecache;
1.1 albertel 1542: sub homeserver {
1.230 stredwic 1543: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1544: my $index="$uname:$udom";
1.426 albertel 1545:
1.599 albertel 1546: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1547:
1548: my %servers = &get_servers($udom,'library');
1549: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1550: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1551: exists($badServerCache{$tryserver}));
1.841 albertel 1552:
1553: my $answer=reply("home:$udom:$uname",$tryserver);
1554: if ($answer eq 'found') {
1555: delete($badServerCache{$tryserver});
1556: return $homecache{$index}=$tryserver;
1557: } elsif ($answer eq 'no_host') {
1558: $badServerCache{$tryserver}=1;
1559: }
1.1 albertel 1560: }
1561: return 'no_host';
1.70 www 1562: }
1563:
1564: # ------------------------------------- Find the usernames behind a list of IDs
1565:
1566: sub idget {
1567: my ($udom,@ids)=@_;
1568: my %returnhash=();
1569:
1.841 albertel 1570: my %servers = &get_servers($udom,'library');
1571: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1572: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1573: $idlist=~tr/A-Z/a-z/;
1574: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1575: my @answer=();
1576: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1577: @answer=split(/\&/,$reply);
1578: } ;
1579: my $i;
1580: for ($i=0;$i<=$#ids;$i++) {
1581: if ($answer[$i]) {
1.1172.2.73 raeburn 1582: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1583: }
1584: }
1585: }
1.70 www 1586: return %returnhash;
1587: }
1588:
1589: # ------------------------------------- Find the IDs behind a list of usernames
1590:
1591: sub idrget {
1592: my ($udom,@unames)=@_;
1593: my %returnhash=();
1.800 albertel 1594: foreach my $uname (@unames) {
1595: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1596: }
1.70 www 1597: return %returnhash;
1598: }
1599:
1600: # ------------------------------- Store away a list of names and associated IDs
1601:
1602: sub idput {
1603: my ($udom,%ids)=@_;
1604: my %servers=();
1.800 albertel 1605: foreach my $uname (keys(%ids)) {
1606: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1607: my $uhom=&homeserver($uname,$udom);
1.70 www 1608: if ($uhom ne 'no_host') {
1.800 albertel 1609: my $id=&escape($ids{$uname});
1.70 www 1610: $id=~tr/A-Z/a-z/;
1.800 albertel 1611: my $esc_unam=&escape($uname);
1.70 www 1612: if ($servers{$uhom}) {
1.800 albertel 1613: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1614: } else {
1.800 albertel 1615: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1616: }
1617: }
1.191 harris41 1618: }
1.800 albertel 1619: foreach my $server (keys(%servers)) {
1620: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1621: }
1.344 www 1622: }
1623:
1.1172.2.30 raeburn 1624: # ---------------------------------------- Delete unwanted IDs from ids.db file
1625:
1626: sub iddel {
1627: my ($udom,$idshashref,$uhome)=@_;
1628: my %result=();
1629: unless (ref($idshashref) eq 'HASH') {
1630: return %result;
1631: }
1632: my %servers=();
1633: while (my ($id,$uname) = each(%{$idshashref})) {
1634: my $uhom;
1635: if ($uhome) {
1636: $uhom = $uhome;
1637: } else {
1638: $uhom=&homeserver($uname,$udom);
1639: }
1640: if ($uhom ne 'no_host') {
1641: if ($servers{$uhom}) {
1642: $servers{$uhom}.='&'.&escape($id);
1643: } else {
1644: $servers{$uhom}=&escape($id);
1645: }
1646: }
1647: }
1648: foreach my $server (keys(%servers)) {
1649: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1650: }
1651: return %result;
1652: }
1653:
1.1023 raeburn 1654: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1655: sub dump_dom {
1.1165 droeschl 1656: my ($namespace, $udom, $regexp) = @_;
1657:
1658: $udom ||= $env{'user.domain'};
1659:
1660: return () unless $udom;
1661:
1662: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1663: }
1664:
1.1023 raeburn 1665: # ------------------------------------------ get items from domain db files
1.806 raeburn 1666:
1667: sub get_dom {
1.860 raeburn 1668: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1669: return if ($udom eq 'public');
1.806 raeburn 1670: my $items='';
1671: foreach my $item (@$storearr) {
1672: $items.=&escape($item).'&';
1673: }
1674: $items=~s/\&$//;
1.860 raeburn 1675: if (!$udom) {
1676: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1677: return if ($udom eq 'public');
1.860 raeburn 1678: if (defined(&domain($udom,'primary'))) {
1679: $uhome=&domain($udom,'primary');
1680: } else {
1.874 albertel 1681: undef($uhome);
1.860 raeburn 1682: }
1683: } else {
1684: if (!$uhome) {
1685: if (defined(&domain($udom,'primary'))) {
1686: $uhome=&domain($udom,'primary');
1687: }
1688: }
1689: }
1690: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1691: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1692: my %returnhash;
1.875 albertel 1693: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1694: return %returnhash;
1695: }
1.806 raeburn 1696: my @pairs=split(/\&/,$rep);
1697: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1698: return @pairs;
1699: }
1700: my $i=0;
1701: foreach my $item (@$storearr) {
1702: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1703: $i++;
1704: }
1705: return %returnhash;
1706: } else {
1.880 banghart 1707: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1708: }
1709: }
1710:
1711: # -------------------------------------------- put items in domain db files
1712:
1713: sub put_dom {
1.860 raeburn 1714: my ($namespace,$storehash,$udom,$uhome)=@_;
1715: if (!$udom) {
1716: $udom=$env{'user.domain'};
1717: if (defined(&domain($udom,'primary'))) {
1718: $uhome=&domain($udom,'primary');
1719: } else {
1.874 albertel 1720: undef($uhome);
1.860 raeburn 1721: }
1722: } else {
1723: if (!$uhome) {
1724: if (defined(&domain($udom,'primary'))) {
1725: $uhome=&domain($udom,'primary');
1726: }
1727: }
1728: }
1729: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1730: my $items='';
1731: foreach my $item (keys(%$storehash)) {
1732: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1733: }
1734: $items=~s/\&$//;
1735: return &reply("putdom:$udom:$namespace:$items",$uhome);
1736: } else {
1.860 raeburn 1737: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1738: }
1739: }
1740:
1.1023 raeburn 1741: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1742: sub newput_dom {
1.1023 raeburn 1743: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1744: my $result;
1745: if (!$udom) {
1746: $udom=$env{'user.domain'};
1747: }
1.1023 raeburn 1748: if ($udom) {
1749: my $uname = &get_domainconfiguser($udom);
1750: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1751: }
1752: return $result;
1753: }
1754:
1.1023 raeburn 1755: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1756: sub del_dom {
1.1023 raeburn 1757: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1758: if (ref($storearr) eq 'ARRAY') {
1759: if (!$udom) {
1760: $udom=$env{'user.domain'};
1761: }
1.1023 raeburn 1762: if ($udom) {
1763: my $uname = &get_domainconfiguser($udom);
1764: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1765: }
1766: }
1767: }
1768:
1.1023 raeburn 1769: # ----------------------------------construct domainconfig user for a domain
1770: sub get_domainconfiguser {
1771: my ($udom) = @_;
1772: return $udom.'-domainconfig';
1773: }
1774:
1.837 raeburn 1775: sub retrieve_inst_usertypes {
1776: my ($udom) = @_;
1777: my (%returnhash,@order);
1.989 raeburn 1778: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1779: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1780: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1781: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1782: } else {
1783: if (defined(&domain($udom,'primary'))) {
1784: my $uhome=&domain($udom,'primary');
1785: my $rep=&reply("inst_usertypes:$udom",$uhome);
1786: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1787: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1788: return (\%returnhash,\@order);
1789: }
1790: my ($hashitems,$orderitems) = split(/:/,$rep);
1791: my @pairs=split(/\&/,$hashitems);
1792: foreach my $item (@pairs) {
1793: my ($key,$value)=split(/=/,$item,2);
1794: $key = &unescape($key);
1795: next if ($key =~ /^error: 2 /);
1796: $returnhash{$key}=&thaw_unescape($value);
1797: }
1798: my @esc_order = split(/\&/,$orderitems);
1799: foreach my $item (@esc_order) {
1800: push(@order,&unescape($item));
1801: }
1802: } else {
1.1172.2.44 raeburn 1803: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1804: }
1.1172.2.44 raeburn 1805: return (\%returnhash,\@order);
1.837 raeburn 1806: }
1807: }
1808:
1.868 raeburn 1809: sub is_domainimage {
1810: my ($url) = @_;
1.1172.2.74 raeburn 1811: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1812: if (&domain($1) ne '') {
1813: return '1';
1814: }
1815: }
1816: return;
1817: }
1818:
1.899 raeburn 1819: sub inst_directory_query {
1820: my ($srch) = @_;
1821: my $udom = $srch->{'srchdomain'};
1822: my %results;
1823: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1824: my $outcome;
1.899 raeburn 1825: if ($homeserver ne '') {
1.904 albertel 1826: my $queryid=&reply("querysend:instdirsearch:".
1827: &escape($srch->{'srchby'}).':'.
1828: &escape($srch->{'srchterm'}).':'.
1829: &escape($srch->{'srchtype'}),$homeserver);
1830: my $host=&hostname($homeserver);
1831: if ($queryid !~/^\Q$host\E\_/) {
1832: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1833: return;
1834: }
1835: my $response = &get_query_reply($queryid);
1836: my $maxtries = 5;
1837: my $tries = 1;
1838: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1839: $response = &get_query_reply($queryid);
1840: $tries ++;
1841: }
1842:
1843: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1844: if ($response eq 'unavailable') {
1845: $outcome = $response;
1846: } else {
1847: $outcome = 'ok';
1848: my @matches = split(/\n/,$response);
1849: foreach my $match (@matches) {
1850: my ($key,$value) = split(/=/,$match);
1851: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1852: }
1.899 raeburn 1853: }
1854: }
1855: }
1.909 raeburn 1856: return ($outcome,%results);
1.899 raeburn 1857: }
1858:
1859: sub usersearch {
1860: my ($srch) = @_;
1861: my $dom = $srch->{'srchdomain'};
1862: my %results;
1863: my %libserv = &all_library();
1864: my $query = 'usersearch';
1865: foreach my $tryserver (keys(%libserv)) {
1866: if (&host_domain($tryserver) eq $dom) {
1867: my $host=&hostname($tryserver);
1868: my $queryid=
1.911 raeburn 1869: &reply("querysend:".&escape($query).':'.
1870: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1871: &escape($srch->{'srchtype'}).':'.
1872: &escape($srch->{'srchterm'}),$tryserver);
1873: if ($queryid !~/^\Q$host\E\_/) {
1874: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1875: next;
1.899 raeburn 1876: }
1877: my $reply = &get_query_reply($queryid);
1878: my $maxtries = 1;
1879: my $tries = 1;
1880: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1881: $reply = &get_query_reply($queryid);
1882: $tries ++;
1883: }
1884: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1885: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1886: } else {
1.911 raeburn 1887: my @matches;
1888: if ($reply =~ /\n/) {
1889: @matches = split(/\n/,$reply);
1890: } else {
1891: @matches = split(/\&/,$reply);
1892: }
1.899 raeburn 1893: foreach my $match (@matches) {
1894: my ($uname,$udom,%userhash);
1.911 raeburn 1895: foreach my $entry (split(/:/,$match)) {
1896: my ($key,$value) =
1897: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1898: $userhash{$key} = $value;
1899: if ($key eq 'username') {
1900: $uname = $value;
1901: } elsif ($key eq 'domain') {
1902: $udom = $value;
1.911 raeburn 1903: }
1.899 raeburn 1904: }
1905: $results{$uname.':'.$udom} = \%userhash;
1906: }
1907: }
1908: }
1909: }
1910: return %results;
1911: }
1912:
1.912 raeburn 1913: sub get_instuser {
1914: my ($udom,$uname,$id) = @_;
1915: my $homeserver = &domain($udom,'primary');
1916: my ($outcome,%results);
1917: if ($homeserver ne '') {
1918: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1919: &escape($id).':'.&escape($udom),$homeserver);
1920: my $host=&hostname($homeserver);
1921: if ($queryid !~/^\Q$host\E\_/) {
1922: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1923: return;
1924: }
1925: my $response = &get_query_reply($queryid);
1926: my $maxtries = 5;
1927: my $tries = 1;
1928: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1929: $response = &get_query_reply($queryid);
1930: $tries ++;
1931: }
1932: if (!&error($response) && $response ne 'refused') {
1933: if ($response eq 'unavailable') {
1934: $outcome = $response;
1935: } else {
1936: $outcome = 'ok';
1937: my @matches = split(/\n/,$response);
1938: foreach my $match (@matches) {
1939: my ($key,$value) = split(/=/,$match);
1940: $results{&unescape($key)} = &thaw_unescape($value);
1941: }
1942: }
1943: }
1944: }
1945: my %userinfo;
1946: if (ref($results{$uname}) eq 'HASH') {
1947: %userinfo = %{$results{$uname}};
1948: }
1949: return ($outcome,%userinfo);
1950: }
1951:
1.1172.2.69 raeburn 1952: sub get_multiple_instusers {
1953: my ($udom,$users,$caller) = @_;
1954: my ($outcome,$results);
1955: if (ref($users) eq 'HASH') {
1956: my $count = keys(%{$users});
1957: my $requested = &freeze_escape($users);
1958: my $homeserver = &domain($udom,'primary');
1959: if ($homeserver ne '') {
1960: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1961: my $host=&hostname($homeserver);
1962: if ($queryid !~/^\Q$host\E\_/) {
1963: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1964: ' for host: '.$homeserver.'in domain '.$udom);
1965: return ($outcome,$results);
1966: }
1967: my $response = &get_query_reply($queryid);
1968: my $maxtries = 5;
1969: if ($count > 100) {
1970: $maxtries = 1+int($count/20);
1971: }
1972: my $tries = 1;
1973: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1974: $response = &get_query_reply($queryid);
1975: $tries ++;
1976: }
1977: if ($response eq '') {
1978: $results = {};
1979: foreach my $key (keys(%{$users})) {
1980: my ($uname,$id);
1981: if ($caller eq 'id') {
1982: $id = $key;
1983: } else {
1984: $uname = $key;
1985: }
1986: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1987: $outcome = $resp;
1988: if ($resp eq 'ok') {
1989: %{$results} = (%{$results}, %info);
1990: } else {
1991: last;
1992: }
1993: }
1994: } elsif(!&error($response) && ($response ne 'refused')) {
1995: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
1996: $outcome = $response;
1997: } else {
1998: ($outcome,my $userdata) = split(/=/,$response,2);
1999: if ($outcome eq 'ok') {
2000: $results = &thaw_unescape($userdata);
2001: }
2002: }
2003: }
2004: }
2005: }
2006: return ($outcome,$results);
2007: }
2008:
1.912 raeburn 2009: sub inst_rulecheck {
1.923 raeburn 2010: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2011: my %returnhash;
2012: if ($udom ne '') {
2013: if (ref($rules) eq 'ARRAY') {
2014: @{$rules} = map {&escape($_);} (@{$rules});
2015: my $rulestr = join(':',@{$rules});
2016: my $homeserver=&domain($udom,'primary');
2017: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2018: my $response;
2019: if ($item eq 'username') {
2020: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2021: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2022: $homeserver));
1.923 raeburn 2023: } elsif ($item eq 'id') {
2024: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2025: ':'.&escape($id).':'.$rulestr,
2026: $homeserver));
1.945 raeburn 2027: } elsif ($item eq 'selfcreate') {
2028: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2029: &escape($udom).':'.&escape($uname).
2030: ':'.$rulestr,$homeserver));
1.923 raeburn 2031: }
1.912 raeburn 2032: if ($response ne 'refused') {
2033: my @pairs=split(/\&/,$response);
2034: foreach my $item (@pairs) {
2035: my ($key,$value)=split(/=/,$item,2);
2036: $key = &unescape($key);
2037: next if ($key =~ /^error: 2 /);
2038: $returnhash{$key}=&thaw_unescape($value);
2039: }
2040: }
2041: }
2042: }
2043: }
2044: return %returnhash;
2045: }
2046:
2047: sub inst_userrules {
1.923 raeburn 2048: my ($udom,$check) = @_;
1.912 raeburn 2049: my (%ruleshash,@ruleorder);
2050: if ($udom ne '') {
2051: my $homeserver=&domain($udom,'primary');
2052: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2053: my $response;
2054: if ($check eq 'id') {
2055: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2056: $homeserver);
1.943 raeburn 2057: } elsif ($check eq 'email') {
2058: $response=&reply('instemailrules:'.&escape($udom),
2059: $homeserver);
1.923 raeburn 2060: } else {
2061: $response=&reply('instuserrules:'.&escape($udom),
2062: $homeserver);
2063: }
1.912 raeburn 2064: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2065: ($response ne 'unknown_cmd') &&
1.912 raeburn 2066: ($response ne 'no_such_host')) {
2067: my ($hashitems,$orderitems) = split(/:/,$response);
2068: my @pairs=split(/\&/,$hashitems);
2069: foreach my $item (@pairs) {
2070: my ($key,$value)=split(/=/,$item,2);
2071: $key = &unescape($key);
2072: next if ($key =~ /^error: 2 /);
2073: $ruleshash{$key}=&thaw_unescape($value);
2074: }
2075: my @esc_order = split(/\&/,$orderitems);
2076: foreach my $item (@esc_order) {
2077: push(@ruleorder,&unescape($item));
2078: }
2079: }
2080: }
2081: }
2082: return (\%ruleshash,\@ruleorder);
2083: }
2084:
1.976 raeburn 2085: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2086:
2087: sub get_domain_defaults {
1.1172.2.35 raeburn 2088: my ($domain,$ignore_cache) = @_;
2089: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2090: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2091: unless ($ignore_cache) {
2092: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2093: if (defined($cached)) {
2094: if (ref($result) eq 'HASH') {
2095: return %{$result};
2096: }
1.943 raeburn 2097: }
2098: }
2099: my %domdefaults;
2100: my %domconfig =
1.989 raeburn 2101: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2102: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2103: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2104: 'requestauthor','selfenrollment',
1.1172.2.89! raeburn 2105: 'coursecategories','autoenroll',
! 2106: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2107: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2108: if (ref($domconfig{'defaults'}) eq 'HASH') {
2109: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2110: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2111: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2112: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2113: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2114: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2115: } else {
2116: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2117: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2118: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2119: }
1.976 raeburn 2120: if (ref($domconfig{'quotas'}) eq 'HASH') {
2121: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2122: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2123: } else {
2124: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2125: }
1.1172.2.6 raeburn 2126: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2127: foreach my $item (@usertools) {
2128: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2129: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2130: }
2131: }
1.1172.2.29 raeburn 2132: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2133: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2134: }
1.976 raeburn 2135: }
1.985 raeburn 2136: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2137: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2138: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2139: }
2140: }
1.1172.2.9 raeburn 2141: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2142: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2143: }
1.989 raeburn 2144: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2145: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2146: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2147: }
2148: }
1.1047 raeburn 2149: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2150: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2151: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2152: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2153: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2154: }
1.1172.2.41 raeburn 2155: foreach my $type (@coursetypes) {
2156: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2157: unless ($type eq 'community') {
2158: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2159: }
2160: }
2161: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2162: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2163: }
1.1172.2.60 raeburn 2164: if ($domdefaults{'postsubmit'} eq 'on') {
2165: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2166: $domdefaults{$type.'postsubtimeout'} =
2167: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2168: }
2169: }
1.1172.2.30 raeburn 2170: }
1.1172.2.67 raeburn 2171: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2172: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2173: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2174: if (@clonecodes) {
2175: $domdefaults{'canclone'} = join('+',@clonecodes);
2176: }
2177: }
2178: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2179: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2180: }
1.1047 raeburn 2181: }
1.1073 raeburn 2182: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2183: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2184: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2185: }
2186: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2187: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2188: }
1.1172.2.62 raeburn 2189: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2190: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2191: }
1.1073 raeburn 2192: }
1.1172.2.41 raeburn 2193: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2194: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2195: my @settings = ('types','registered','enroll_dates','access_dates','section',
2196: 'approval','limit');
2197: foreach my $type (@coursetypes) {
2198: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2199: my @mgrdc = ();
2200: foreach my $item (@settings) {
2201: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2202: push(@mgrdc,$item);
2203: }
2204: }
2205: if (@mgrdc) {
2206: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2207: }
2208: }
2209: }
2210: }
2211: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2212: foreach my $type (@coursetypes) {
2213: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2214: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2215: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2216: }
2217: }
2218: }
2219: }
2220: }
1.1172.2.46 raeburn 2221: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2222: $domdefaults{'catauth'} = 'std';
2223: $domdefaults{'catunauth'} = 'std';
2224: if ($domconfig{'coursecategories'}{'auth'}) {
2225: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2226: }
2227: if ($domconfig{'coursecategories'}{'unauth'}) {
2228: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2229: }
2230: }
1.1172.2.76 raeburn 2231: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2232: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2233: }
1.1172.2.89! raeburn 2234: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
! 2235: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
! 2236: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
! 2237: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
! 2238: }
! 2239: }
1.1172.2.23 raeburn 2240: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2241: return %domdefaults;
2242: }
2243:
1.344 www 2244: # --------------------------------------------------- Assign a key to a student
2245:
2246: sub assign_access_key {
1.364 www 2247: #
2248: # a valid key looks like uname:udom#comments
2249: # comments are being appended
2250: #
1.498 www 2251: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2252: $kdom=
1.620 albertel 2253: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2254: $knum=
1.620 albertel 2255: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2256: $cdom=
1.620 albertel 2257: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2258: $cnum=
1.620 albertel 2259: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2260: $udom=$env{'user.name'} unless (defined($udom));
2261: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2262: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2263: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2264: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2265: # assigned to this person
2266: # - this should not happen,
1.345 www 2267: # unless something went wrong
2268: # the first time around
2269: # ready to assign
1.364 www 2270: $logentry=$1.'; '.$logentry;
1.496 www 2271: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2272: $kdom,$knum) eq 'ok') {
1.345 www 2273: # key now belongs to user
1.346 www 2274: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2275: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2276: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2277: return 'ok';
2278: } else {
2279: return
2280: 'error: Count not permanently assign key, will need to be re-entered later.';
2281: }
2282: } else {
2283: return 'error: Could not assign key, try again later.';
2284: }
1.364 www 2285: } elsif (!$existing{$ckey}) {
1.345 www 2286: # the key does not exist
2287: return 'error: The key does not exist';
2288: } else {
2289: # the key is somebody else's
2290: return 'error: The key is already in use';
2291: }
1.344 www 2292: }
2293:
1.364 www 2294: # ------------------------------------------ put an additional comment on a key
2295:
2296: sub comment_access_key {
2297: #
2298: # a valid key looks like uname:udom#comments
2299: # comments are being appended
2300: #
2301: my ($ckey,$cdom,$cnum,$logentry)=@_;
2302: $cdom=
1.620 albertel 2303: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2304: $cnum=
1.620 albertel 2305: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2306: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2307: if ($existing{$ckey}) {
2308: $existing{$ckey}.='; '.$logentry;
2309: # ready to assign
1.367 www 2310: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2311: $cdom,$cnum) eq 'ok') {
2312: return 'ok';
2313: } else {
2314: return 'error: Count not store comment.';
2315: }
2316: } else {
2317: # the key does not exist
2318: return 'error: The key does not exist';
2319: }
2320: }
2321:
1.344 www 2322: # ------------------------------------------------------ Generate a set of keys
2323:
2324: sub generate_access_keys {
1.364 www 2325: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2326: $cdom=
1.620 albertel 2327: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2328: $cnum=
1.620 albertel 2329: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2330: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2331: unless (($cdom) && ($cnum)) { return 0; }
2332: if ($number>10000) { return 0; }
2333: sleep(2); # make sure don't get same seed twice
2334: srand(time()^($$+($$<<15))); # from "Programming Perl"
2335: my $total=0;
2336: for (my $i=1;$i<=$number;$i++) {
2337: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2338: sprintf("%lx",int(100000*rand)).'-'.
2339: sprintf("%lx",int(100000*rand));
2340: $newkey=~s/1/g/g; # folks mix up 1 and l
2341: $newkey=~s/0/h/g; # and also 0 and O
2342: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2343: if ($existing{$newkey}) {
2344: $i--;
2345: } else {
1.364 www 2346: if (&put('accesskeys',
2347: { $newkey => '# generated '.localtime().
1.620 albertel 2348: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2349: '; '.$logentry },
2350: $cdom,$cnum) eq 'ok') {
1.344 www 2351: $total++;
2352: }
2353: }
2354: }
1.620 albertel 2355: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2356: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2357: return $total;
2358: }
2359:
2360: # ------------------------------------------------------- Validate an accesskey
2361:
2362: sub validate_access_key {
2363: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2364: $cdom=
1.620 albertel 2365: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2366: $cnum=
1.620 albertel 2367: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2368: $udom=$env{'user.domain'} unless (defined($udom));
2369: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2370: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2371: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2372: }
2373:
2374: # ------------------------------------- Find the section of student in a course
1.652 albertel 2375: sub devalidate_getsection_cache {
2376: my ($udom,$unam,$courseid)=@_;
2377: my $hashid="$udom:$unam:$courseid";
2378: &devalidate_cache_new('getsection',$hashid);
2379: }
1.298 matthew 2380:
1.815 albertel 2381: sub courseid_to_courseurl {
2382: my ($courseid) = @_;
2383: #already url style courseid
2384: return $courseid if ($courseid =~ m{^/});
2385:
2386: if (exists($env{'course.'.$courseid.'.num'})) {
2387: my $cnum = $env{'course.'.$courseid.'.num'};
2388: my $cdom = $env{'course.'.$courseid.'.domain'};
2389: return "/$cdom/$cnum";
2390: }
2391:
2392: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2393: if (exists($courseinfo{'num'})) {
2394: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2395: }
2396:
2397: return undef;
2398: }
2399:
1.298 matthew 2400: sub getsection {
2401: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2402: my $cachetime=1800;
1.551 albertel 2403:
2404: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2405: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2406: if (defined($cached)) { return $result; }
2407:
1.298 matthew 2408: my %Pending;
2409: my %Expired;
2410: #
2411: # Each role can either have not started yet (pending), be active,
2412: # or have expired.
2413: #
2414: # If there is an active role, we are done.
2415: #
2416: # If there is more than one role which has not started yet,
2417: # choose the one which will start sooner
2418: # If there is one role which has not started yet, return it.
2419: #
2420: # If there is more than one expired role, choose the one which ended last.
2421: # If there is a role which has expired, return it.
2422: #
1.815 albertel 2423: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2424: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2425: foreach my $key (keys(%roleshash)) {
1.479 albertel 2426: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2427: my $section=$1;
2428: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2429: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2430: my $now=time;
1.548 albertel 2431: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2432: $Expired{$end}=$section;
2433: next;
2434: }
1.548 albertel 2435: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2436: $Pending{$start}=$section;
2437: next;
2438: }
1.599 albertel 2439: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2440: }
2441: #
2442: # Presumedly there will be few matching roles from the above
2443: # loop and the sorting time will be negligible.
2444: if (scalar(keys(%Pending))) {
2445: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2446: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2447: }
2448: if (scalar(keys(%Expired))) {
2449: my @sorted = sort {$a <=> $b} keys(%Expired);
2450: my $time = pop(@sorted);
1.599 albertel 2451: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2452: }
1.599 albertel 2453: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2454: }
1.70 www 2455:
1.599 albertel 2456: sub save_cache {
2457: &purge_remembered();
1.722 albertel 2458: #&Apache::loncommon::validate_page();
1.620 albertel 2459: undef(%env);
1.780 albertel 2460: undef($env_loaded);
1.599 albertel 2461: }
1.452 albertel 2462:
1.599 albertel 2463: my $to_remember=-1;
2464: my %remembered;
2465: my %accessed;
2466: my $kicks=0;
2467: my $hits=0;
1.849 albertel 2468: sub make_key {
2469: my ($name,$id) = @_;
1.872 albertel 2470: if (length($id) > 65
2471: && length(&escape($id)) > 200) {
2472: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2473: }
1.849 albertel 2474: return &escape($name.':'.$id);
2475: }
2476:
1.599 albertel 2477: sub devalidate_cache_new {
2478: my ($name,$id,$debug) = @_;
2479: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2480: my $remembered_id=$name.':'.$id;
1.849 albertel 2481: $id=&make_key($name,$id);
1.599 albertel 2482: $memcache->delete($id);
1.1172.2.81 raeburn 2483: delete($remembered{$remembered_id});
2484: delete($accessed{$remembered_id});
1.599 albertel 2485: }
2486:
2487: sub is_cached_new {
2488: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2489: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2490: # keys in %remembered hash, which persists for
2491: # duration of request (no restriction on key length).
2492: if (exists($remembered{$remembered_id})) {
2493: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2494: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2495: $hits++;
1.1172.2.81 raeburn 2496: return ($remembered{$remembered_id},1);
1.599 albertel 2497: }
1.1172.2.81 raeburn 2498: $id=&make_key($name,$id);
1.599 albertel 2499: my $value = $memcache->get($id);
2500: if (!(defined($value))) {
2501: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2502: return (undef,undef);
1.416 albertel 2503: }
1.599 albertel 2504: if ($value eq '__undef__') {
2505: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2506: $value=undef;
2507: }
1.1172.2.81 raeburn 2508: &make_room($remembered_id,$value,$debug);
1.599 albertel 2509: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2510: return ($value,1);
2511: }
2512:
2513: sub do_cache_new {
2514: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2515: my $remembered_id=$name.':'.$id;
1.849 albertel 2516: $id=&make_key($name,$id);
1.599 albertel 2517: my $setvalue=$value;
2518: if (!defined($setvalue)) {
2519: $setvalue='__undef__';
2520: }
1.623 albertel 2521: if (!defined($time) ) {
2522: $time=600;
2523: }
1.599 albertel 2524: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2525: my $result = $memcache->set($id,$setvalue,$time);
2526: if (! $result) {
1.872 albertel 2527: &logthis("caching of id -> $id failed");
1.910 albertel 2528: $memcache->disconnect_all();
1.872 albertel 2529: }
1.600 albertel 2530: # need to make a copy of $value
1.1172.2.81 raeburn 2531: &make_room($remembered_id,$value,$debug);
1.599 albertel 2532: return $value;
2533: }
2534:
2535: sub make_room {
1.1172.2.81 raeburn 2536: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2537:
1.1172.2.81 raeburn 2538: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2539: : $value;
1.599 albertel 2540: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2541: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2542: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2543: my $to_kick;
2544: my $max_time=0;
2545: foreach my $other (keys(%accessed)) {
2546: if (&tv_interval($accessed{$other}) > $max_time) {
2547: $to_kick=$other;
2548: $max_time=&tv_interval($accessed{$other});
2549: }
2550: }
2551: delete($remembered{$to_kick});
2552: delete($accessed{$to_kick});
2553: $kicks++;
2554: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2555: return;
2556: }
2557:
1.599 albertel 2558: sub purge_remembered {
1.604 albertel 2559: #&logthis("Tossing ".scalar(keys(%remembered)));
2560: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2561: undef(%remembered);
2562: undef(%accessed);
1.428 albertel 2563: }
1.70 www 2564: # ------------------------------------- Read an entry from a user's environment
2565:
2566: sub userenvironment {
2567: my ($udom,$unam,@what)=@_;
1.976 raeburn 2568: my $items;
2569: foreach my $item (@what) {
2570: $items.=&escape($item).'&';
2571: }
2572: $items=~s/\&$//;
1.70 www 2573: my %returnhash=();
1.1009 raeburn 2574: my $uhome = &homeserver($unam,$udom);
2575: unless ($uhome eq 'no_host') {
2576: my @answer=split(/\&/,
2577: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2578: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2579: return %returnhash;
2580: }
1.1009 raeburn 2581: my $i;
2582: for ($i=0;$i<=$#what;$i++) {
2583: $returnhash{$what[$i]}=&unescape($answer[$i]);
2584: }
1.70 www 2585: }
2586: return %returnhash;
1.1 albertel 2587: }
2588:
1.617 albertel 2589: # ---------------------------------------------------------- Get a studentphoto
2590: sub studentphoto {
2591: my ($udom,$unam,$ext) = @_;
2592: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2593: if (defined($env{'request.course.id'})) {
1.708 raeburn 2594: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2595: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2596: return(&retrievestudentphoto($udom,$unam,$ext));
2597: } else {
2598: my ($result,$perm_reqd)=
1.707 albertel 2599: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2600: if ($result eq 'ok') {
2601: if (!($perm_reqd eq 'yes')) {
2602: return(&retrievestudentphoto($udom,$unam,$ext));
2603: }
2604: }
2605: }
2606: }
2607: } else {
2608: my ($result,$perm_reqd) =
1.707 albertel 2609: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2610: if ($result eq 'ok') {
2611: if (!($perm_reqd eq 'yes')) {
2612: return(&retrievestudentphoto($udom,$unam,$ext));
2613: }
2614: }
2615: }
2616: return '/adm/lonKaputt/lonlogo_broken.gif';
2617: }
2618:
2619: sub retrievestudentphoto {
2620: my ($udom,$unam,$ext,$type) = @_;
2621: my $home=&Apache::lonnet::homeserver($unam,$udom);
2622: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2623: if ($ret eq 'ok') {
2624: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2625: if ($type eq 'thumbnail') {
2626: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2627: }
2628: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2629: return $tokenurl;
2630: } else {
2631: if ($type eq 'thumbnail') {
2632: return '/adm/lonKaputt/genericstudent_tn.gif';
2633: } else {
2634: return '/adm/lonKaputt/lonlogo_broken.gif';
2635: }
1.617 albertel 2636: }
2637: }
2638:
1.263 www 2639: # -------------------------------------------------------------------- New chat
2640:
2641: sub chatsend {
1.724 raeburn 2642: my ($newentry,$anon,$group)=@_;
1.620 albertel 2643: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2644: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2645: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2646: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2647: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2648: &escape($newentry)).':'.$group,$chome);
1.292 www 2649: }
2650:
2651: # ------------------------------------------ Find current version of a resource
2652:
2653: sub getversion {
2654: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2655: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2656: return ¤tversion(&filelocation('',$fname));
2657: }
2658:
2659: sub currentversion {
2660: my $fname=shift;
2661: my $author=$fname;
2662: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2663: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2664: my $home=&homeserver($uname,$udom);
1.292 www 2665: if ($home eq 'no_host') {
2666: return -1;
2667: }
1.1112 www 2668: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2669: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2670: return -1;
2671: }
1.1112 www 2672: return $answer;
1.263 www 2673: }
2674:
1.1111 www 2675: #
2676: # Return special version number of resource if set by override, empty otherwise
2677: #
2678: sub usedversion {
2679: my $fname=shift;
2680: unless ($fname) { $fname=$env{'request.uri'}; }
2681: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2682: if ($urlversion) { return $urlversion; }
2683: return '';
2684: }
2685:
1.1 albertel 2686: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2687:
1.1 albertel 2688: sub subscribe {
2689: my $fname=shift;
1.761 raeburn 2690: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2691: $fname=~s/[\n\r]//g;
1.1 albertel 2692: my $author=$fname;
2693: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2694: my ($udom,$uname)=split(/\//,$author);
2695: my $home=homeserver($uname,$udom);
1.335 albertel 2696: if ($home eq 'no_host') {
2697: return 'not_found';
1.1 albertel 2698: }
2699: my $answer=reply("sub:$fname",$home);
1.64 www 2700: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2701: $answer.=' by '.$home;
2702: }
1.1 albertel 2703: return $answer;
2704: }
2705:
1.8 www 2706: # -------------------------------------------------------------- Replicate file
2707:
2708: sub repcopy {
2709: my $filename=shift;
1.23 www 2710: $filename=~s/\/+/\//g;
1.1142 raeburn 2711: my $londocroot = $perlvar{'lonDocRoot'};
2712: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2713: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2714: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2715: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2716: return &repcopy_userfile($filename);
2717: }
1.532 albertel 2718: $filename=~s/[\n\r]//g;
1.8 www 2719: my $transname="$filename.in.transfer";
1.828 www 2720: # FIXME: this should flock
1.607 raeburn 2721: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2722: my $remoteurl=subscribe($filename);
1.64 www 2723: if ($remoteurl =~ /^con_lost by/) {
2724: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2725: return 'unavailable';
1.8 www 2726: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2727: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2728: return 'not_found';
1.64 www 2729: } elsif ($remoteurl =~ /^rejected by/) {
2730: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2731: return 'forbidden';
1.20 www 2732: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2733: return 'ok';
1.8 www 2734: } else {
1.290 www 2735: my $author=$filename;
2736: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2737: my ($udom,$uname)=split(/\//,$author);
2738: my $home=homeserver($uname,$udom);
2739: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2740: my @parts=split(/\//,$filename);
2741: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2742: if ($path ne "$londocroot/res") {
1.8 www 2743: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2744: return 'bad_request';
1.8 www 2745: }
2746: my $count;
2747: for ($count=5;$count<$#parts;$count++) {
2748: $path.="/$parts[$count]";
2749: if ((-e $path)!=1) {
2750: mkdir($path,0777);
2751: }
2752: }
2753: my $ua=new LWP::UserAgent;
2754: my $request=new HTTP::Request('GET',"$remoteurl");
2755: my $response=$ua->request($request,$transname);
2756: if ($response->is_error()) {
2757: unlink($transname);
2758: my $message=$response->status_line;
1.672 albertel 2759: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2760: ." LWP get: $message: $filename</font>");
1.607 raeburn 2761: return 'unavailable';
1.8 www 2762: } else {
1.16 www 2763: if ($remoteurl!~/\.meta$/) {
2764: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2765: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2766: if ($mresponse->is_error()) {
2767: unlink($filename.'.meta');
2768: &logthis(
1.672 albertel 2769: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2770: }
2771: }
1.8 www 2772: rename($transname,$filename);
1.607 raeburn 2773: return 'ok';
1.8 www 2774: }
1.290 www 2775: }
1.8 www 2776: }
1.330 www 2777: }
2778:
2779: # ------------------------------------------------ Get server side include body
2780: sub ssi_body {
1.381 albertel 2781: my ($filelink,%form)=@_;
1.606 matthew 2782: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2783: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2784: }
1.953 www 2785: my $output='';
2786: my $response;
1.980 raeburn 2787: if ($filelink=~/^https?\:/) {
1.954 raeburn 2788: ($output,$response)=&externalssi($filelink);
1.953 www 2789: } else {
1.1004 droeschl 2790: $filelink .= $filelink=~/\?/ ? '&' : '?';
2791: $filelink .= 'inhibitmenu=yes';
1.953 www 2792: ($output,$response)=&ssi($filelink,%form);
2793: }
1.778 albertel 2794: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2795: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2796: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2797: if (wantarray) {
2798: return ($output, $response);
2799: } else {
2800: return $output;
2801: }
1.8 www 2802: }
2803:
1.15 www 2804: # --------------------------------------------------------- Server Side Include
2805:
1.782 albertel 2806: sub absolute_url {
2807: my ($host_name) = @_;
2808: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2809: if ($host_name eq '') {
2810: $host_name = $ENV{'SERVER_NAME'};
2811: }
2812: return $protocol.$host_name;
2813: }
2814:
1.942 foxr 2815: #
2816: # Server side include.
2817: # Parameters:
2818: # fn Possibly encrypted resource name/id.
2819: # form Hash that describes how the rendering should be done
2820: # and other things.
1.944 foxr 2821: # Returns:
1.950 raeburn 2822: # Scalar context: The content of the response.
2823: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2824: #
1.15 www 2825: sub ssi {
2826:
1.944 foxr 2827: my ($fn,%form)=@_;
1.15 www 2828: my $ua=new LWP::UserAgent;
1.23 www 2829: my $request;
1.711 albertel 2830:
2831: $form{'no_update_last_known'}=1;
1.895 albertel 2832: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2833: if (%form) {
1.782 albertel 2834: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2835: $request->content(join('&',map {
2836: my $name = escape($_);
2837: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2838: ? join("&$name=", map {escape($_) } @{$form{$_}})
2839: : &escape($form{$_}) );
2840: } keys(%form)));
1.23 www 2841: } else {
1.782 albertel 2842: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2843: }
2844:
1.15 www 2845: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2846: my $response= $ua->request($request);
1.944 foxr 2847: if (wantarray) {
1.1172.2.3 raeburn 2848: return ($response->content, $response);
1.944 foxr 2849: } else {
1.1172.2.3 raeburn 2850: return $response->content;
1.942 foxr 2851: }
1.324 www 2852: }
2853:
2854: sub externalssi {
2855: my ($url)=@_;
2856: my $ua=new LWP::UserAgent;
2857: my $request=new HTTP::Request('GET',$url);
2858: my $response=$ua->request($request);
1.954 raeburn 2859: if (wantarray) {
2860: return ($response->content, $response);
2861: } else {
2862: return $response->content;
2863: }
1.15 www 2864: }
1.254 www 2865:
1.492 albertel 2866: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2867:
2868: sub allowuploaded {
2869: my ($srcurl,$url)=@_;
2870: $url=&clutter(&declutter($url));
2871: my $dir=$url;
2872: $dir=~s/\/[^\/]+$//;
2873: my %httpref=();
2874: my $httpurl=&hreflocation('',$url);
2875: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2876: &Apache::lonnet::appenv(\%httpref);
1.254 www 2877: }
1.477 raeburn 2878:
1.1172.2.13 raeburn 2879: #
2880: # Determine if the current user should be able to edit a particular resource,
2881: # when viewing in course context.
2882: # (a) When viewing resource used to determine if "Edit" item is included in
2883: # Functions.
2884: # (b) When displaying folder contents in course editor, used to determine if
2885: # "Edit" link will be displayed alongside resource.
2886: #
2887: # input: six args -- filename (decluttered), course number, course domain,
2888: # url, symb (if registered) and group (if this is a group
2889: # item -- e.g., bulletin board, group page etc.).
2890: # output: array of five scalars --
2891: # $cfile -- url for file editing if editable on current server
2892: # $home -- homeserver of resource (i.e., for author if published,
2893: # or course if uploaded.).
2894: # $switchserver -- 1 if server switch will be needed.
2895: # $forceedit -- 1 if icon/link should be to go to edit mode
2896: # $forceview -- 1 if icon/link should be to go to view mode
2897: #
2898:
2899: sub can_edit_resource {
2900: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2901: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2902: #
2903: # For aboutme pages user can only edit his/her own.
2904: #
2905: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2906: my ($sdom,$sname) = ($1,$2);
2907: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2908: $home = $env{'user.home'};
2909: $cfile = $resurl;
2910: if ($env{'form.forceedit'}) {
2911: $forceview = 1;
2912: } else {
2913: $forceedit = 1;
2914: }
2915: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2916: } else {
2917: return;
2918: }
2919: }
2920:
2921: if ($env{'request.course.id'}) {
2922: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2923: if ($group ne '') {
2924: # if this is a group homepage or group bulletin board, check group privs
2925: my $allowed = 0;
2926: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2927: if ((&allowed('mdg',$env{'request.course.id'}.
2928: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2929: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2930: $allowed = 1;
2931: }
2932: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2933: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2934: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2935: $allowed = 1;
2936: }
2937: }
2938: if ($allowed) {
2939: $home=&homeserver($cnum,$cdom);
2940: if ($env{'form.forceedit'}) {
2941: $forceview = 1;
2942: } else {
2943: $forceedit = 1;
2944: }
2945: $cfile = $resurl;
2946: } else {
2947: return;
2948: }
2949: } else {
1.1172.2.15 raeburn 2950: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2951: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2952: return;
2953: }
2954: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2955: #
2956: # No edit allowed where CC has switched to student role.
2957: #
2958: return;
2959: }
2960: }
2961: }
2962:
2963: if ($file ne '') {
2964: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2965: if (&is_course_upload($file,$cnum,$cdom)) {
2966: $uploaded = 1;
2967: $incourse = 1;
2968: if ($file =~/\.(htm|html|css|js|txt)$/) {
2969: $cfile = &hreflocation('',$file);
2970: if ($env{'form.forceedit'}) {
2971: $forceview = 1;
2972: } else {
2973: $forceedit = 1;
2974: }
2975: }
2976: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2977: $incourse = 1;
2978: if ($env{'form.forceedit'}) {
2979: $forceview = 1;
2980: } else {
2981: $forceedit = 1;
2982: }
2983: $cfile = $resurl;
2984: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2985: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2986: $incourse = 1;
2987: if ($env{'form.forceedit'}) {
2988: $forceview = 1;
2989: } else {
2990: $forceedit = 1;
2991: }
2992: $cfile = $resurl;
2993: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2994: $incourse = 1;
2995: $cfile = $resurl.'/smpedit';
2996: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2997: $incourse = 1;
2998: if ($env{'form.forceedit'}) {
2999: $forceview = 1;
3000: } else {
3001: $forceedit = 1;
3002: }
3003: $cfile = $resurl;
1.1172.2.15 raeburn 3004: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3005: $incourse = 1;
3006: if ($env{'form.forceedit'}) {
3007: $forceview = 1;
3008: } else {
3009: $forceedit = 1;
3010: }
3011: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3012: }
3013: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3014: my $template = '/res/lib/templates/simpleproblem.problem';
3015: if (&is_on_map($template)) {
3016: $incourse = 1;
3017: $forceview = 1;
3018: $cfile = $template;
3019: }
3020: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3021: $incourse = 1;
3022: if ($env{'form.forceedit'}) {
3023: $forceview = 1;
3024: } else {
3025: $forceedit = 1;
3026: }
3027: $cfile = $resurl;
3028: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3029: $incourse = 1;
3030: $forceview = 1;
3031: if ($symb) {
3032: my ($map,$id,$res)=&decode_symb($symb);
3033: $env{'request.symb'} = $symb;
3034: $cfile = &clutter($res);
3035: } else {
3036: $cfile = $env{'form.suppurl'};
3037: $cfile =~ s{^http://}{};
3038: $cfile = '/adm/wrapper/ext/'.$cfile;
3039: }
1.1172.2.31 raeburn 3040: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3041: if ($env{'form.forceedit'}) {
3042: $forceview = 1;
3043: } else {
3044: $forceedit = 1;
3045: }
3046: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3047: }
3048: }
3049: if ($uploaded || $incourse) {
3050: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3051: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3052: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3053: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3054: # Check that the user has permission to edit this resource
3055: my $setpriv = 1;
3056: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3057: if (defined($cfudom)) {
3058: $home=&homeserver($cfuname,$cfudom);
3059: $cfile=$file;
3060: }
3061: }
3062: if (($cfile ne '') && (!$incourse || $uploaded) &&
3063: (($home ne '') && ($home ne 'no_host'))) {
3064: my @ids=¤t_machine_ids();
3065: unless (grep(/^\Q$home\E$/,@ids)) {
3066: $switchserver=1;
3067: }
3068: }
3069: }
3070: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3071: }
3072:
3073: sub is_course_upload {
3074: my ($file,$cnum,$cdom) = @_;
3075: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3076: $uploadpath =~ s{^\/}{};
3077: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3078: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3079: return 1;
3080: }
3081: return;
3082: }
3083:
3084: sub in_course {
3085: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3086: if ($hideprivileged) {
3087: my $skipuser;
1.1172.2.23 raeburn 3088: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3089: my @possdoms = ($cdom);
3090: if ($coursehash{'checkforpriv'}) {
3091: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3092: }
3093: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3094: $skipuser = 1;
3095: if ($coursehash{'nothideprivileged'}) {
3096: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3097: my $user;
3098: if ($item =~ /:/) {
3099: $user = $item;
3100: } else {
3101: $user = join(':',split(/[\@]/,$item));
3102: }
3103: if ($user eq $uname.':'.$udom) {
3104: undef($skipuser);
3105: last;
3106: }
3107: }
3108: }
3109: if ($skipuser) {
3110: return 0;
3111: }
3112: }
3113: }
3114: $type ||= 'any';
3115: if (!defined($cdom) || !defined($cnum)) {
3116: my $cid = $env{'request.course.id'};
3117: $cdom = $env{'course.'.$cid.'.domain'};
3118: $cnum = $env{'course.'.$cid.'.num'};
3119: }
3120: my $typesref;
3121: if (($type eq 'any') || ($type eq 'all')) {
3122: $typesref = ['active','previous','future'];
3123: } elsif ($type eq 'previous' || $type eq 'future') {
3124: $typesref = [$type];
3125: }
3126: my %roles = &get_my_roles($uname,$udom,'userroles',
3127: $typesref,undef,[$cdom]);
3128: my ($tmp) = keys(%roles);
3129: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3130: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3131: if (@course_roles > 0) {
3132: return 1;
3133: }
3134: return 0;
3135: }
3136:
1.478 albertel 3137: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3138: # input: action, courseID, current domain, intended
1.637 raeburn 3139: # path to file, source of file, instruction to parse file for objects,
3140: # ref to hash for embedded objects,
3141: # ref to hash for codebase of java objects.
1.1095 raeburn 3142: # reference to scalar to accommodate mime type determined
3143: # from File::MMagic if $parser = parse.
1.637 raeburn 3144: #
1.485 raeburn 3145: # output: url to file (if action was uploaddoc),
3146: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3147: #
1.478 albertel 3148: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3149: # course.
1.477 raeburn 3150: #
1.478 albertel 3151: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3152: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3153: # course's home server.
1.477 raeburn 3154: #
1.478 albertel 3155: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3156: # be copied from $source (current location) to
3157: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3158: # and will then be copied to
3159: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3160: # course's home server.
1.485 raeburn 3161: #
1.481 raeburn 3162: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3163: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3164: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3165: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3166: # in course's home server.
1.637 raeburn 3167: #
1.477 raeburn 3168:
3169: sub process_coursefile {
1.1095 raeburn 3170: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3171: $mimetype)=@_;
1.477 raeburn 3172: my $fetchresult;
1.638 albertel 3173: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3174: if ($action eq 'propagate') {
1.638 albertel 3175: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3176: $home);
1.481 raeburn 3177: } else {
1.477 raeburn 3178: my $fpath = '';
3179: my $fname = $file;
1.478 albertel 3180: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3181: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3182: my $filepath = &build_filepath($fpath);
1.481 raeburn 3183: if ($action eq 'copy') {
3184: if ($source eq '') {
3185: $fetchresult = 'no source file';
3186: return $fetchresult;
3187: } else {
3188: my $destination = $filepath.'/'.$fname;
3189: rename($source,$destination);
3190: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3191: $home);
1.481 raeburn 3192: }
3193: } elsif ($action eq 'uploaddoc') {
3194: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3195: print $fh $env{'form.'.$source};
1.481 raeburn 3196: close($fh);
1.637 raeburn 3197: if ($parser eq 'parse') {
1.1024 raeburn 3198: my $mm = new File::MMagic;
1.1095 raeburn 3199: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3200: if ($type eq 'text/html') {
1.1024 raeburn 3201: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3202: unless ($parse_result eq 'ok') {
3203: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3204: }
1.637 raeburn 3205: }
1.1095 raeburn 3206: if (ref($mimetype)) {
3207: $$mimetype = $type;
3208: }
1.637 raeburn 3209: }
1.477 raeburn 3210: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3211: $home);
1.481 raeburn 3212: if ($fetchresult eq 'ok') {
3213: return '/uploaded/'.$fpath.'/'.$fname;
3214: } else {
3215: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3216: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3217: return '/adm/notfound.html';
3218: }
1.477 raeburn 3219: }
3220: }
1.485 raeburn 3221: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3222: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3223: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3224: }
3225: return $fetchresult;
3226: }
3227:
1.637 raeburn 3228: sub build_filepath {
3229: my ($fpath) = @_;
3230: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3231: unless ($fpath eq '') {
3232: my @parts=split('/',$fpath);
3233: foreach my $part (@parts) {
3234: $filepath.= '/'.$part;
3235: if ((-e $filepath)!=1) {
3236: mkdir($filepath,0777);
3237: }
3238: }
3239: }
3240: return $filepath;
3241: }
3242:
3243: sub store_edited_file {
1.638 albertel 3244: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3245: my $file = $primary_url;
3246: $file =~ s#^/uploaded/$docudom/$docuname/##;
3247: my $fpath = '';
3248: my $fname = $file;
3249: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3250: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3251: my $filepath = &build_filepath($fpath);
3252: open(my $fh,'>'.$filepath.'/'.$fname);
3253: print $fh $content;
3254: close($fh);
1.638 albertel 3255: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3256: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3257: $home);
1.637 raeburn 3258: if ($$fetchresult eq 'ok') {
3259: return '/uploaded/'.$fpath.'/'.$fname;
3260: } else {
1.638 albertel 3261: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3262: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3263: return '/adm/notfound.html';
3264: }
3265: }
3266:
1.531 albertel 3267: sub clean_filename {
1.831 albertel 3268: my ($fname,$args)=@_;
1.315 www 3269: # Replace Windows backslashes by forward slashes
1.257 www 3270: $fname=~s/\\/\//g;
1.831 albertel 3271: if (!$args->{'keep_path'}) {
3272: # Get rid of everything but the actual filename
3273: $fname=~s/^.*\/([^\/]+)$/$1/;
3274: }
1.315 www 3275: # Replace spaces by underscores
3276: $fname=~s/\s+/\_/g;
3277: # Replace all other weird characters by nothing
1.831 albertel 3278: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3279: # Replace all .\d. sequences with _\d. so they no longer look like version
3280: # numbers
3281: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3282: return $fname;
3283: }
1.1051 raeburn 3284: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3285: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3286: # image with the same aspect ratio as the original, but with dimensions which do
3287: # not exceed $resizewidth and $resizeheight.
3288:
1.984 neumanie 3289: sub resizeImage {
1.1051 raeburn 3290: my ($img_path,$resizewidth,$resizeheight) = @_;
3291: my $ima = Image::Magick->new;
3292: my $resized;
3293: if (-e $img_path) {
3294: $ima->Read($img_path);
3295: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3296: my $width = $ima->Get('width');
3297: my $height = $ima->Get('height');
3298: if ($width > $resizewidth) {
3299: my $factor = $width/$resizewidth;
3300: my $newheight = $height/$factor;
3301: $ima->Scale(width=>$resizewidth,height=>$newheight);
3302: $resized = 1;
3303: }
3304: }
3305: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3306: my $width = $ima->Get('width');
3307: my $height = $ima->Get('height');
3308: if ($height > $resizeheight) {
3309: my $factor = $height/$resizeheight;
3310: my $newwidth = $width/$factor;
3311: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3312: $resized = 1;
3313: }
3314: }
3315: if ($resized) {
3316: $ima->Write($img_path);
3317: }
3318: }
3319: return;
1.977 amueller 3320: }
3321:
1.608 albertel 3322: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3323: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3324: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3325: # $context - possible values: coursedoc, existingfile, overwrite,
3326: # canceloverwrite, or ''.
3327: # if 'coursedoc': upload to the current course
3328: # if 'existingfile': write file to tmp/overwrites directory
3329: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3330: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3331: # $subdir - directory in userfile to store the file into
1.858 raeburn 3332: # $parser - instruction to parse file for objects ($parser = parse)
3333: # $allfiles - reference to hash for embedded objects
3334: # $codebase - reference to hash for codebase of java objects
3335: # $desuname - username for permanent storage of uploaded file
3336: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3337: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3338: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3339: # $resizewidth - width (pixels) to which to resize uploaded image
3340: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3341: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3342: # from File::MMagic.
1.858 raeburn 3343: #
1.686 albertel 3344: # output: url of file in userspace, or error: <message>
3345: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3346:
1.531 albertel 3347: sub userfileupload {
1.1090 raeburn 3348: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3349: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3350: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3351: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3352: $fname=&clean_filename($fname);
1.1090 raeburn 3353: # See if there is anything left
1.257 www 3354: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3355: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3356: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3357: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3358: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3359: my $now = time;
1.1090 raeburn 3360: my $filepath;
1.1095 raeburn 3361: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3362: $filepath = 'tmp/helprequests/'.$now;
3363: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3364: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3365: '_'.$env{'user.domain'}.'/pending';
3366: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3367: my ($docuname,$docudom);
3368: if ($destudom) {
3369: $docudom = $destudom;
3370: } else {
3371: $docudom = $env{'user.domain'};
3372: }
3373: if ($destuname) {
3374: $docuname = $destuname;
3375: } else {
3376: $docuname = $env{'user.name'};
3377: }
3378: if (exists($env{'form.group'})) {
3379: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3380: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3381: }
3382: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3383: if ($context eq 'canceloverwrite') {
3384: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3385: if (-e $tempfile) {
3386: my @info = stat($tempfile);
3387: if ($info[9] eq $env{'form.timestamp'}) {
3388: unlink($tempfile);
3389: }
3390: }
3391: return;
1.523 raeburn 3392: }
3393: }
1.1090 raeburn 3394: # Create the directory if not present
1.741 raeburn 3395: my @parts=split(/\//,$filepath);
3396: my $fullpath = $perlvar{'lonDaemons'};
3397: for (my $i=0;$i<@parts;$i++) {
3398: $fullpath .= '/'.$parts[$i];
3399: if ((-e $fullpath)!=1) {
3400: mkdir($fullpath,0777);
3401: }
3402: }
3403: open(my $fh,'>'.$fullpath.'/'.$fname);
3404: print $fh $env{'form.'.$formname};
3405: close($fh);
1.1090 raeburn 3406: if ($context eq 'existingfile') {
3407: my @info = stat($fullpath.'/'.$fname);
3408: return ($fullpath.'/'.$fname,$info[9]);
3409: } else {
3410: return $fullpath.'/'.$fname;
3411: }
1.523 raeburn 3412: }
1.995 raeburn 3413: if ($subdir eq 'scantron') {
3414: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3415: } else {
1.995 raeburn 3416: $fname="$subdir/$fname";
3417: }
1.1090 raeburn 3418: if ($context eq 'coursedoc') {
1.638 albertel 3419: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3420: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3421: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3422: return &finishuserfileupload($docuname,$docudom,
3423: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3424: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3425: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3426: } else {
1.1172.2.21 raeburn 3427: if ($env{'form.folder'}) {
3428: $fname=$env{'form.folder'}.'/'.$fname;
3429: }
1.638 albertel 3430: return &process_coursefile('uploaddoc',$docuname,$docudom,
3431: $fname,$formname,$parser,
1.1095 raeburn 3432: $allfiles,$codebase,$mimetype);
1.481 raeburn 3433: }
1.719 banghart 3434: } elsif (defined($destuname)) {
3435: my $docuname=$destuname;
3436: my $docudom=$destudom;
1.860 raeburn 3437: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3438: $parser,$allfiles,$codebase,
1.1051 raeburn 3439: $thumbwidth,$thumbheight,
1.1095 raeburn 3440: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3441: } else {
1.638 albertel 3442: my $docuname=$env{'user.name'};
3443: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3444: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3445: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3446: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3447: }
1.860 raeburn 3448: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3449: $parser,$allfiles,$codebase,
1.1051 raeburn 3450: $thumbwidth,$thumbheight,
1.1095 raeburn 3451: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3452: }
1.271 www 3453: }
3454:
3455: sub finishuserfileupload {
1.860 raeburn 3456: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3457: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3458: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3459: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3460:
1.860 raeburn 3461: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3462: $file=$fname;
3463: if ($fname=~m|/|) {
3464: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3465: $path.=$fnamepath.'/';
3466: }
1.259 www 3467: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3468: my $count;
3469: for ($count=4;$count<=$#parts;$count++) {
3470: $filepath.="/$parts[$count]";
3471: if ((-e $filepath)!=1) {
3472: mkdir($filepath,0777);
3473: }
3474: }
1.984 neumanie 3475:
1.258 www 3476: # Save the file
3477: {
1.701 albertel 3478: if (!open(FH,'>'.$filepath.'/'.$file)) {
3479: &logthis('Failed to create '.$filepath.'/'.$file);
3480: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3481: return '/adm/notfound.html';
3482: }
1.1090 raeburn 3483: if ($context eq 'overwrite') {
1.1117 foxr 3484: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3485: my $target = $filepath.'/'.$file;
3486: if (-e $source) {
3487: my @info = stat($source);
3488: if ($info[9] eq $env{'form.timestamp'}) {
3489: unless (&File::Copy::move($source,$target)) {
3490: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3491: return "Moving from $source failed";
3492: }
3493: } else {
3494: return "Temporary file: $source had unexpected date/time for last modification";
3495: }
3496: } else {
3497: return "Temporary file: $source missing";
3498: }
3499: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3500: &logthis('Failed to write to '.$filepath.'/'.$file);
3501: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3502: return '/adm/notfound.html';
3503: }
1.570 albertel 3504: close(FH);
1.1051 raeburn 3505: if ($resizewidth && $resizeheight) {
3506: my $mm = new File::MMagic;
3507: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3508: if ($mime_type =~ m{^image/}) {
3509: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3510: }
1.977 amueller 3511: }
1.258 www 3512: }
1.1152 raeburn 3513: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3514: if (ref($mimetype)) {
3515: if ($$mimetype eq '') {
3516: my $mm = new File::MMagic;
3517: my $type = $mm->checktype_filename($filepath.'/'.$file);
3518: $$mimetype = $type;
3519: }
3520: }
3521: }
1.637 raeburn 3522: if ($parser eq 'parse') {
1.1152 raeburn 3523: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3524: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3525: $allfiles,$codebase);
3526: unless ($parse_result eq 'ok') {
3527: &logthis('Failed to parse '.$filepath.$file.
3528: ' for embedded media: '.$parse_result);
3529: }
1.637 raeburn 3530: }
3531: }
1.860 raeburn 3532: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3533: my $input = $filepath.'/'.$file;
3534: my $output = $filepath.'/'.'tn-'.$file;
3535: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3536: system("convert -sample $thumbsize $input $output");
3537: if (-e $filepath.'/'.'tn-'.$file) {
3538: $fetchthumb = 1;
3539: }
3540: }
1.858 raeburn 3541:
1.259 www 3542: # Notify homeserver to grep it
3543: #
1.984 neumanie 3544: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3545: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3546: if ($fetchresult eq 'ok') {
1.860 raeburn 3547: if ($fetchthumb) {
3548: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3549: if ($thumbresult ne 'ok') {
3550: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3551: $docuhome.': '.$thumbresult);
3552: }
3553: }
1.259 www 3554: #
1.258 www 3555: # Return the URL to it
1.494 albertel 3556: return '/uploaded/'.$path.$file;
1.263 www 3557: } else {
1.494 albertel 3558: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3559: ': '.$fetchresult);
1.263 www 3560: return '/adm/notfound.html';
1.858 raeburn 3561: }
1.493 albertel 3562: }
3563:
1.637 raeburn 3564: sub extract_embedded_items {
1.961 raeburn 3565: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3566: my @state = ();
1.1164 raeburn 3567: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3568: my %javafiles = (
3569: codebase => '',
3570: code => '',
3571: archive => ''
3572: );
3573: my %mediafiles = (
3574: src => '',
3575: movie => '',
3576: );
1.648 raeburn 3577: my $p;
3578: if ($content) {
3579: $p = HTML::LCParser->new($content);
3580: } else {
1.961 raeburn 3581: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3582: }
1.641 albertel 3583: while (my $t=$p->get_token()) {
1.640 albertel 3584: if ($t->[0] eq 'S') {
3585: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3586: push(@state, $tagname);
1.648 raeburn 3587: if (lc($tagname) eq 'allow') {
3588: &add_filetype($allfiles,$attr->{'src'},'src');
3589: }
1.640 albertel 3590: if (lc($tagname) eq 'img') {
3591: &add_filetype($allfiles,$attr->{'src'},'src');
3592: }
1.886 albertel 3593: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3594: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3595: &add_filetype($allfiles,$attr->{'href'},'href');
3596: }
1.886 albertel 3597: }
1.645 raeburn 3598: if (lc($tagname) eq 'script') {
1.1164 raeburn 3599: my $src;
1.645 raeburn 3600: if ($attr->{'archive'} =~ /\.jar$/i) {
3601: &add_filetype($allfiles,$attr->{'archive'},'archive');
3602: } else {
1.1164 raeburn 3603: if ($attr->{'src'} ne '') {
3604: $src = $attr->{'src'};
3605: &add_filetype($allfiles,$src,'src');
3606: }
3607: }
3608: my $text = $p->get_trimmed_text();
3609: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3610: my @swfargs = split(/,/,$1);
3611: foreach my $item (@swfargs) {
3612: $item =~ s/["']//g;
3613: $item =~ s/^\s+//;
3614: $item =~ s/\s+$//;
3615: }
3616: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3617: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3618: push(@{$related{$swfargs[0]}},$swfargs[2]);
3619: } else {
3620: $related{$swfargs[0]} = [$swfargs[2]];
3621: }
3622: }
1.645 raeburn 3623: }
3624: }
3625: if (lc($tagname) eq 'link') {
3626: if (lc($attr->{'rel'}) eq 'stylesheet') {
3627: &add_filetype($allfiles,$attr->{'href'},'href');
3628: }
3629: }
1.640 albertel 3630: if (lc($tagname) eq 'object' ||
3631: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3632: foreach my $item (keys(%javafiles)) {
3633: $javafiles{$item} = '';
3634: }
1.1164 raeburn 3635: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3636: $lastids{lc($tagname)} = $attr->{'id'};
3637: }
1.640 albertel 3638: }
3639: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3640: my $name = lc($attr->{'name'});
3641: foreach my $item (keys(%javafiles)) {
3642: if ($name eq $item) {
3643: $javafiles{$item} = $attr->{'value'};
3644: last;
3645: }
3646: }
1.1164 raeburn 3647: my $pathfrom;
1.640 albertel 3648: foreach my $item (keys(%mediafiles)) {
3649: if ($name eq $item) {
1.1164 raeburn 3650: $pathfrom = $attr->{'value'};
3651: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3652: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3653: last;
3654: }
3655: }
1.1164 raeburn 3656: if ($name eq 'flashvars') {
3657: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3658: }
3659: if ($pathfrom ne '') {
3660: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3661: $pathfrom);
3662: }
1.640 albertel 3663: }
3664: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3665: foreach my $item (keys(%javafiles)) {
3666: if ($attr->{$item}) {
3667: $javafiles{$item} = $attr->{$item};
3668: last;
3669: }
3670: }
3671: foreach my $item (keys(%mediafiles)) {
3672: if ($attr->{$item}) {
3673: &add_filetype($allfiles,$attr->{$item},$item);
3674: last;
3675: }
3676: }
1.1164 raeburn 3677: if (lc($tagname) eq 'embed') {
3678: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3679: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3680: $attr->{'src'});
3681: }
3682: }
1.640 albertel 3683: }
1.1172.2.35 raeburn 3684: if (lc($tagname) eq 'iframe') {
3685: my $src = $attr->{'src'} ;
3686: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3687: &add_filetype($allfiles,$src,'src');
3688: } elsif ($src =~ m{^/}) {
3689: if ($env{'request.course.id'}) {
3690: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3691: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3692: my $url = &hreflocation('',$fullpath);
3693: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3694: my $relpath = $1;
3695: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3696: &add_filetype($allfiles,$1,'src');
3697: }
3698: }
3699: }
3700: }
3701: }
1.1164 raeburn 3702: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3703: pop(@state);
1.1164 raeburn 3704: }
1.640 albertel 3705: } elsif ($t->[0] eq 'E') {
3706: my ($tagname) = ($t->[1]);
3707: if ($javafiles{'codebase'} ne '') {
3708: $javafiles{'codebase'} .= '/';
3709: }
3710: if (lc($tagname) eq 'applet' ||
3711: lc($tagname) eq 'object' ||
3712: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3713: ) {
3714: foreach my $item (keys(%javafiles)) {
3715: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3716: my $file=$javafiles{'codebase'}.$javafiles{$item};
3717: &add_filetype($allfiles,$file,$item);
3718: }
3719: }
3720: }
3721: pop @state;
3722: }
3723: }
1.1164 raeburn 3724: foreach my $id (sort(keys(%flashvars))) {
3725: if ($shockwave{$id} ne '') {
3726: my @pairs = split(/\&/,$flashvars{$id});
3727: foreach my $pair (@pairs) {
3728: my ($key,$value) = split(/\=/,$pair);
3729: if ($key eq 'thumb') {
3730: &add_filetype($allfiles,$value,$key);
3731: } elsif ($key eq 'content') {
3732: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3733: my ($ext) = ($value =~ /\.([^.]+)$/);
3734: if ($ext ne '') {
3735: &add_filetype($allfiles,$path.$value,$ext);
3736: }
3737: }
3738: }
3739: }
3740: }
1.637 raeburn 3741: return 'ok';
3742: }
3743:
1.639 albertel 3744: sub add_filetype {
3745: my ($allfiles,$file,$type)=@_;
3746: if (exists($allfiles->{$file})) {
3747: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3748: push(@{$allfiles->{$file}}, &escape($type));
3749: }
3750: } else {
3751: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3752: }
3753: }
3754:
1.1164 raeburn 3755: sub embedded_dependency {
3756: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3757: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3758: if (($identifier ne '') &&
3759: (ref($related->{$identifier}) eq 'ARRAY') &&
3760: ($pathfrom ne '')) {
3761: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3762: foreach my $dep (@{$related->{$identifier}}) {
3763: &add_filetype($allfiles,$path.$dep,'object');
3764: }
3765: }
3766: }
3767: return;
3768: }
3769:
1.493 albertel 3770: sub removeuploadedurl {
1.984 neumanie 3771: my ($url)=@_;
3772: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3773: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3774: }
3775:
3776: sub removeuserfile {
3777: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3778: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3779: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3780: if ($result eq 'ok') {
1.798 raeburn 3781: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3782: my $metafile = $fname.'.meta';
3783: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3784: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3785: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3786: my $sqlresult =
1.823 albertel 3787: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3788: 'portfolio_metadata',$group,
3789: 'delete');
1.798 raeburn 3790: }
3791: }
3792: return $result;
1.257 www 3793: }
1.15 www 3794:
1.530 albertel 3795: sub mkdiruserfile {
3796: my ($docuname,$docudom,$dir)=@_;
3797: my $home=&homeserver($docuname,$docudom);
3798: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3799: }
3800:
1.531 albertel 3801: sub renameuserfile {
3802: my ($docuname,$docudom,$old,$new)=@_;
3803: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3804: my $result = &reply("renameuserfile:$docudom:$docuname:".
3805: &escape("$old").':'.&escape("$new"),$home);
3806: if ($result eq 'ok') {
3807: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3808: my $oldmeta = $old.'.meta';
3809: my $newmeta = $new.'.meta';
3810: my $metaresult =
3811: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3812: my $url = "/uploaded/$docudom/$docuname/$old";
3813: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3814: my $sqlresult =
1.823 albertel 3815: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3816: 'portfolio_metadata',$group,
3817: 'delete');
1.798 raeburn 3818: }
3819: }
3820: return $result;
1.531 albertel 3821: }
3822:
1.14 www 3823: # ------------------------------------------------------------------------- Log
3824:
3825: sub log {
3826: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3827: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3828: }
3829:
3830: # ------------------------------------------------------------------ Course Log
1.352 www 3831: #
3832: # This routine flushes several buffers of non-mission-critical nature
3833: #
1.157 www 3834:
3835: sub flushcourselogs {
1.352 www 3836: &logthis('Flushing log buffers');
3837: #
3838: # course logs
3839: # This is a log of all transactions in a course, which can be used
3840: # for data mining purposes
3841: #
3842: # It also collects the courseid database, which lists last transaction
3843: # times and course titles for all courseids
3844: #
3845: my %courseidbuffer=();
1.921 raeburn 3846: foreach my $crsid (keys(%courselogs)) {
1.352 www 3847: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3848: &escape($courselogs{$crsid}),
3849: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3850: delete $courselogs{$crsid};
3851: } else {
3852: &logthis('Failed to flush log buffer for '.$crsid);
3853: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3854: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3855: " exceeded maximum size, deleting.</font>");
3856: delete $courselogs{$crsid};
3857: }
1.352 www 3858: }
1.920 raeburn 3859: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3860: 'description' => $coursedescrbuf{$crsid},
3861: 'inst_code' => $courseinstcodebuf{$crsid},
3862: 'type' => $coursetypebuf{$crsid},
3863: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3864: };
1.191 harris41 3865: }
1.352 www 3866: #
3867: # Write course id database (reverse lookup) to homeserver of courses
3868: # Is used in pickcourse
3869: #
1.840 albertel 3870: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3871: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3872: $courseidbuffer{$crs_home},
3873: $crs_home,'timeonly');
1.352 www 3874: }
3875: #
3876: # File accesses
3877: # Writes to the dynamic metadata of resources to get hit counts, etc.
3878: #
1.449 matthew 3879: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3880: if ($entry =~ /___count$/) {
3881: my ($dom,$name);
1.807 albertel 3882: ($dom,$name,undef)=
1.811 albertel 3883: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3884: if (! defined($dom) || $dom eq '' ||
3885: ! defined($name) || $name eq '') {
1.620 albertel 3886: my $cid = $env{'request.course.id'};
3887: $dom = $env{'request.'.$cid.'.domain'};
3888: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3889: }
1.450 matthew 3890: my $value = $accesshash{$entry};
3891: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3892: my %temphash=($url => $value);
1.449 matthew 3893: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3894: if ($result eq 'ok') {
3895: delete $accesshash{$entry};
3896: }
3897: } else {
1.811 albertel 3898: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3899: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3900: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3901: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3902: delete $accesshash{$entry};
3903: }
1.185 www 3904: }
1.191 harris41 3905: }
1.352 www 3906: #
3907: # Roles
3908: # Reverse lookup of user roles for course faculty/staff and co-authorship
3909: #
1.800 albertel 3910: foreach my $entry (keys(%userrolehash)) {
1.351 www 3911: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3912: split(/\:/,$entry);
3913: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3914: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3915: $rudom,$runame) eq 'ok') {
3916: delete $userrolehash{$entry};
3917: }
3918: }
1.662 raeburn 3919: #
1.1172.2.84 raeburn 3920: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662 raeburn 3921: #
3922: my %domrolebuffer = ();
1.1000 raeburn 3923: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3924: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3925: if ($domrolebuffer{$rudom}) {
3926: $domrolebuffer{$rudom}.='&'.&escape($entry).
3927: '='.&escape($domainrolehash{$entry});
3928: } else {
3929: $domrolebuffer{$rudom}.=&escape($entry).
3930: '='.&escape($domainrolehash{$entry});
3931: }
3932: delete $domainrolehash{$entry};
3933: }
3934: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 3935: my %servers;
3936: if (defined(&domain($dom,'primary'))) {
3937: my $primary=&domain($dom,'primary');
3938: my $hostname=&hostname($primary);
3939: $servers{$primary} = $hostname;
3940: } else {
3941: %servers = &get_servers($dom,'library');
3942: }
1.841 albertel 3943: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 3944: if (&reply('domroleput:'.$dom.':'.
3945: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3946: last;
3947: } else {
1.841 albertel 3948: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3949: }
1.662 raeburn 3950: }
3951: }
1.186 www 3952: $dumpcount++;
1.157 www 3953: }
3954:
3955: sub courselog {
3956: my $what=shift;
1.158 www 3957: $what=time.':'.$what;
1.620 albertel 3958: unless ($env{'request.course.id'}) { return ''; }
3959: $coursedombuf{$env{'request.course.id'}}=
3960: $env{'course.'.$env{'request.course.id'}.'.domain'};
3961: $coursenumbuf{$env{'request.course.id'}}=
3962: $env{'course.'.$env{'request.course.id'}.'.num'};
3963: $coursehombuf{$env{'request.course.id'}}=
3964: $env{'course.'.$env{'request.course.id'}.'.home'};
3965: $coursedescrbuf{$env{'request.course.id'}}=
3966: $env{'course.'.$env{'request.course.id'}.'.description'};
3967: $courseinstcodebuf{$env{'request.course.id'}}=
3968: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3969: $courseownerbuf{$env{'request.course.id'}}=
3970: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3971: $coursetypebuf{$env{'request.course.id'}}=
3972: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3973: if (defined $courselogs{$env{'request.course.id'}}) {
3974: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3975: } else {
1.620 albertel 3976: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3977: }
1.620 albertel 3978: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3979: &flushcourselogs();
3980: }
1.158 www 3981: }
3982:
3983: sub courseacclog {
3984: my $fnsymb=shift;
1.620 albertel 3985: unless ($env{'request.course.id'}) { return ''; }
3986: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3987: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3988: $what.=':POST';
1.583 matthew 3989: # FIXME: Probably ought to escape things....
1.800 albertel 3990: foreach my $key (keys(%env)) {
3991: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3992: my $formitem = $1;
3993: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3994: $what.=':'.$formitem.'='.$env{$key};
3995: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3996: $what.=':'.$formitem.'='.$env{$key};
3997: }
1.158 www 3998: }
1.191 harris41 3999: }
1.583 matthew 4000: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4001: # FIXME: We should not be depending on a form parameter that someone
4002: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4003: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4004: $what.= ':POST';
4005: # FIXME: Probably ought to escape things....
4006: foreach my $element ('courseexp','crsfulltext','crsrelated',
4007: 'crsdiscuss') {
1.620 albertel 4008: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4009: }
4010: }
1.158 www 4011: }
4012: &courselog($what);
1.149 www 4013: }
4014:
1.185 www 4015: sub countacc {
4016: my $url=&declutter(shift);
1.458 matthew 4017: return if (! defined($url) || $url eq '');
1.620 albertel 4018: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4019: #
4020: # Mark that this url was used in this course
4021: #
1.620 albertel 4022: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4023: #
4024: # Increase the access count for this resource in this child process
4025: #
1.281 www 4026: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4027: $accesshash{$key}++;
1.185 www 4028: }
1.349 www 4029:
1.361 www 4030: sub linklog {
4031: my ($from,$to)=@_;
4032: $from=&declutter($from);
4033: $to=&declutter($to);
4034: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4035: $accesshash{$to.'___'.$from.'___goto'}=1;
4036: }
1.1160 www 4037:
4038: sub statslog {
4039: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4040: if ($users<2) { return; }
4041: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4042: 'course' => $env{'request.course.id'},
4043: 'sections' => '"all"',
4044: 'num_students' => $users,
4045: 'part' => $part,
4046: 'symb' => $symb,
4047: 'mean_tries' => $av_attempts,
4048: 'deg_of_diff' => $degdiff});
4049: foreach my $key (keys(%dynstore)) {
4050: $accesshash{$key}=$dynstore{$key};
4051: }
4052: }
1.361 www 4053:
1.349 www 4054: sub userrolelog {
4055: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4056: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4057: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4058: $userrolehash
4059: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4060: =$tend.':'.$tstart;
1.662 raeburn 4061: }
1.1169 droeschl 4062: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4063: $userrolehash
4064: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4065: =$tend.':'.$tstart;
4066: }
1.1172.2.84 raeburn 4067: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662 raeburn 4068: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4069: $domainrolehash
4070: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4071: = $tend.':'.$tstart;
4072: }
1.351 www 4073: }
4074:
1.957 raeburn 4075: sub courserolelog {
4076: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4077: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4078: my $cdom = $1;
4079: my $cnum = $2;
4080: my $sec = $3;
4081: my $namespace = 'rolelog';
4082: my %storehash = (
4083: role => $trole,
4084: start => $tstart,
4085: end => $tend,
4086: selfenroll => $selfenroll,
4087: context => $context,
4088: );
4089: if ($trole eq 'gr') {
4090: $namespace = 'groupslog';
4091: $storehash{'group'} = $sec;
4092: } else {
4093: $storehash{'section'} = $sec;
4094: }
4095: &write_log('course',$namespace,\%storehash,$delflag,$username,
4096: $domain,$cnum,$cdom);
4097: if (($trole ne 'st') || ($sec ne '')) {
4098: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4099: }
4100: }
4101: return;
4102: }
4103:
1.1172.2.9 raeburn 4104: sub domainrolelog {
4105: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4106: if ($area =~ m{^/($match_domain)/$}) {
4107: my $cdom = $1;
4108: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4109: my $namespace = 'rolelog';
4110: my %storehash = (
4111: role => $trole,
4112: start => $tstart,
4113: end => $tend,
4114: context => $context,
4115: );
4116: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4117: $domain,$domconfiguser,$cdom);
4118: }
4119: return;
4120:
4121: }
4122:
4123: sub coauthorrolelog {
4124: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4125: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4126: my $audom = $1;
4127: my $auname = $2;
4128: my $namespace = 'rolelog';
4129: my %storehash = (
4130: role => $trole,
4131: start => $tstart,
4132: end => $tend,
4133: context => $context,
4134: );
4135: &write_log('author',$namespace,\%storehash,$delflag,$username,
4136: $domain,$auname,$audom);
4137: }
4138: return;
4139: }
4140:
1.351 www 4141: sub get_course_adv_roles {
1.948 raeburn 4142: my ($cid,$codes) = @_;
1.620 albertel 4143: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4144: my %coursehash=&coursedescription($cid);
1.988 raeburn 4145: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4146: my %nothide=();
1.800 albertel 4147: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4148: if ($user !~ /:/) {
4149: $nothide{join(':',split(/[\@]/,$user))}=1;
4150: } else {
4151: $nothide{$user}=1;
4152: }
1.470 www 4153: }
1.1172.2.23 raeburn 4154: my @possdoms = ($coursehash{'domain'});
4155: if ($coursehash{'checkforpriv'}) {
4156: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4157: }
1.351 www 4158: my %returnhash=();
4159: my %dumphash=
4160: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4161: my $now=time;
1.997 raeburn 4162: my %privileged;
1.1000 raeburn 4163: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4164: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4165: if (($tstart) && ($tstart<0)) { next; }
4166: if (($tend) && ($tend<$now)) { next; }
4167: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4168: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4169: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4170: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4171: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4172: if ($role eq 'cr') { next; }
1.948 raeburn 4173: if ($codes) {
4174: if ($section) { $role .= ':'.$section; }
4175: if ($returnhash{$role}) {
4176: $returnhash{$role}.=','.$username.':'.$domain;
4177: } else {
4178: $returnhash{$role}=$username.':'.$domain;
4179: }
1.351 www 4180: } else {
1.988 raeburn 4181: my $key=&plaintext($role,$crstype);
1.973 bisitz 4182: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4183: if ($returnhash{$key}) {
4184: $returnhash{$key}.=','.$username.':'.$domain;
4185: } else {
4186: $returnhash{$key}=$username.':'.$domain;
4187: }
1.351 www 4188: }
1.948 raeburn 4189: }
1.400 www 4190: return %returnhash;
4191: }
4192:
4193: sub get_my_roles {
1.937 raeburn 4194: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4195: unless (defined($uname)) { $uname=$env{'user.name'}; }
4196: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4197: my (%dumphash,%nothide);
1.1086 raeburn 4198: if ($context eq 'userroles') {
1.1166 raeburn 4199: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4200: } else {
1.1172.2.23 raeburn 4201: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4202: if ($hidepriv) {
4203: my %coursehash=&coursedescription($udom.'_'.$uname);
4204: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4205: if ($user !~ /:/) {
4206: $nothide{join(':',split(/[\@]/,$user))} = 1;
4207: } else {
4208: $nothide{$user} = 1;
4209: }
4210: }
4211: }
1.858 raeburn 4212: }
1.400 www 4213: my %returnhash=();
4214: my $now=time;
1.999 raeburn 4215: my %privileged;
1.800 albertel 4216: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4217: my ($role,$tend,$tstart);
4218: if ($context eq 'userroles') {
1.1149 raeburn 4219: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4220: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4221: } else {
4222: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4223: }
1.400 www 4224: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4225: my $status = 'active';
1.939 raeburn 4226: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4227: $status = 'previous';
4228: }
4229: if (($tstart) && ($now<$tstart)) {
4230: $status = 'future';
4231: }
4232: if (ref($types) eq 'ARRAY') {
4233: if (!grep(/^\Q$status\E$/,@{$types})) {
4234: next;
4235: }
4236: } else {
4237: if ($status ne 'active') {
4238: next;
4239: }
4240: }
1.867 raeburn 4241: my ($rolecode,$username,$domain,$section,$area);
4242: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4243: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4244: (undef,$domain,$username,$section) = split(/\//,$area);
4245: } else {
4246: ($role,$username,$domain,$section) = split(/\:/,$entry);
4247: }
1.832 raeburn 4248: if (ref($roledoms) eq 'ARRAY') {
4249: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4250: next;
4251: }
4252: }
4253: if (ref($roles) eq 'ARRAY') {
4254: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4255: if ($role =~ /^cr\//) {
4256: if (!grep(/^cr$/,@{$roles})) {
4257: next;
4258: }
1.1104 raeburn 4259: } elsif ($role =~ /^gr\//) {
4260: if (!grep(/^gr$/,@{$roles})) {
4261: next;
4262: }
1.922 raeburn 4263: } else {
4264: next;
4265: }
1.832 raeburn 4266: }
1.867 raeburn 4267: }
1.937 raeburn 4268: if ($hidepriv) {
1.1172.2.23 raeburn 4269: my @privroles = ('dc','su');
1.999 raeburn 4270: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4271: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4272: } else {
1.1172.2.23 raeburn 4273: my $possdoms = [$domain];
4274: if (ref($roledoms) eq 'ARRAY') {
4275: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4276: }
1.1172.2.23 raeburn 4277: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4278: if (!$nothide{$username.':'.$domain}) {
4279: next;
4280: }
4281: }
1.937 raeburn 4282: }
4283: }
1.933 raeburn 4284: if ($withsec) {
4285: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4286: $tstart.':'.$tend;
4287: } else {
4288: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4289: }
1.832 raeburn 4290: }
1.373 www 4291: return %returnhash;
1.399 www 4292: }
4293:
1.1172.2.89! raeburn 4294: sub get_all_adhocroles {
! 4295: my ($dom) = @_;
! 4296: my @roles_by_num = ();
! 4297: my %domdefaults = &get_domain_defaults($dom);
! 4298: my (%description,%access_in_dom,%access_info);
! 4299: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
! 4300: my $count = 0;
! 4301: my %domcurrent = %{$domdefaults{'adhocroles'}};
! 4302: my %ordered;
! 4303: foreach my $role (sort(keys(%domcurrent))) {
! 4304: my ($order,$desc,$access_in_dom);
! 4305: if (ref($domcurrent{$role}) eq 'HASH') {
! 4306: $order = $domcurrent{$role}{'order'};
! 4307: $desc = $domcurrent{$role}{'desc'};
! 4308: $access_in_dom{$role} = $domcurrent{$role}{'access'};
! 4309: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
! 4310: }
! 4311: if ($order eq '') {
! 4312: $order = $count;
! 4313: }
! 4314: $ordered{$order} = $role;
! 4315: if ($desc ne '') {
! 4316: $description{$role} = $desc;
! 4317: } else {
! 4318: $description{$role}= $role;
! 4319: }
! 4320: $count++;
! 4321: }
! 4322: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
! 4323: push(@roles_by_num,$ordered{$item});
! 4324: }
! 4325: }
! 4326: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
! 4327: }
! 4328:
! 4329: sub get_my_adhocroles {
! 4330: my ($cid,$checkreg) = @_;
! 4331: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
! 4332: if ($env{'request.course.id'} eq $cid) {
! 4333: $cdom = $env{'course.'.$cid.'.domain'};
! 4334: $cnum = $env{'course.'.$cid.'.num'};
! 4335: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
! 4336: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
! 4337: $cdom = $1;
! 4338: $cnum = $2;
! 4339: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
! 4340: $cdom,$cnum);
! 4341: }
! 4342: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
! 4343: my $user = $env{'user.name'}.':'.$env{'user.domain'};
! 4344: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
! 4345: if ($rosterhash{$user} ne '') {
! 4346: my $type = (split(/:/,$rosterhash{$user}))[5];
! 4347: return ([],{}) if ($type eq 'auto');
! 4348: }
! 4349: }
! 4350: if (($cdom ne '') && ($cnum ne '')) {
! 4351: if ($env{"user.role.dh./$cdom/"}) {
! 4352: my $then=$env{'user.login.time'};
! 4353: my $update=$env{'user.update.time'};
! 4354: my $liverole = 1;
! 4355: my ($tstart,$tend)=split(/\./,$env{'user.role.dh./'.$cdom});
! 4356: my $limit = $update;
! 4357: if ($env{'request.role'} eq 'dh./'.$cdom.'/') {
! 4358: $limit = $then;
! 4359: }
! 4360: if ($tstart && $tstart>$limit) { $liverole = 0; }
! 4361: if ($tend && $tend <$limit) { $liverole = 0; }
! 4362: if ($liverole) {
! 4363: if (&homeserver($cnum,$cdom) ne 'no_host') {
! 4364: my ($accessref,$accessinfo,%access_in_dom);
! 4365: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
! 4366: if (ref($roles_by_num) eq 'ARRAY') {
! 4367: if (@{$roles_by_num}) {
! 4368: my %settings;
! 4369: if ($env{'request.course.id'} eq $cid) {
! 4370: foreach my $envkey (keys(%env)) {
! 4371: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
! 4372: $settings{$1} = $env{$envkey};
! 4373: }
! 4374: }
! 4375: } else {
! 4376: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
! 4377: }
! 4378: my %setincrs;
! 4379: if ($settings{'internal.adhocaccess'}) {
! 4380: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
! 4381: }
! 4382: my @statuses;
! 4383: if ($env{'environment.inststatus'}) {
! 4384: @statuses = split(/,/,$env{'environment.inststatus'});
! 4385: }
! 4386: my $user = $env{'user.name'}.':'.$env{'user.domain'};
! 4387: if (ref($accessref) eq 'HASH') {
! 4388: %access_in_dom = %{$accessref};
! 4389: }
! 4390: foreach my $role (@{$roles_by_num}) {
! 4391: my ($curraccess,@okstatus,@personnel);
! 4392: if ($setincrs{$role}) {
! 4393: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
! 4394: if ($curraccess eq 'status') {
! 4395: @okstatus = split(/\&/,$rest);
! 4396: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
! 4397: @personnel = split(/\&/,$rest);
! 4398: }
! 4399: } else {
! 4400: $curraccess = $access_in_dom{$role};
! 4401: if (ref($accessinfo) eq 'HASH') {
! 4402: if ($curraccess eq 'status') {
! 4403: if (ref($accessinfo->{$role}) eq 'ARRAY') {
! 4404: @okstatus = @{$accessinfo->{$role}};
! 4405: }
! 4406: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
! 4407: if (ref($accessinfo->{$role}) eq 'ARRAY') {
! 4408: @personnel = @{$accessinfo->{$role}};
! 4409: }
! 4410: }
! 4411: }
! 4412: }
! 4413: if ($curraccess eq 'none') {
! 4414: next;
! 4415: } elsif ($curraccess eq 'all') {
! 4416: push(@possroles,$role);
! 4417: } elsif ($curraccess eq 'status') {
! 4418: if (@okstatus) {
! 4419: if (!@statuses) {
! 4420: if (grep(/^default$/,@okstatus)) {
! 4421: push(@possroles,$role);
! 4422: }
! 4423: } else {
! 4424: foreach my $status (@okstatus) {
! 4425: if (grep(/^\Q$status\E$/,@statuses)) {
! 4426: push(@possroles,$role);
! 4427: last;
! 4428: }
! 4429: }
! 4430: }
! 4431: }
! 4432: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
! 4433: if (grep(/^\Q$user\E$/,@personnel)) {
! 4434: if ($curraccess eq 'exc') {
! 4435: push(@possroles,$role);
! 4436: }
! 4437: } elsif ($curraccess eq 'inc') {
! 4438: push(@possroles,$role);
! 4439: }
! 4440: }
! 4441: }
! 4442: }
! 4443: }
! 4444: }
! 4445: }
! 4446: }
! 4447: }
! 4448: unless (ref($description) eq 'HASH') {
! 4449: if (ref($roles_by_num) eq 'ARRAY') {
! 4450: my %desc;
! 4451: map { $desc{$_} = $_; } (@{$roles_by_num});
! 4452: $description = \%desc;
! 4453: } else {
! 4454: $description = {};
! 4455: }
! 4456: }
! 4457: return (\@possroles,$description);
! 4458: }
! 4459:
1.399 www 4460: # ----------------------------------------------------- Frontpage Announcements
4461: #
4462: #
4463:
4464: sub postannounce {
4465: my ($server,$text)=@_;
1.844 albertel 4466: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4467: unless ($text=~/\w/) { $text=''; }
4468: return &reply('setannounce:'.&escape($text),$server);
4469: }
4470:
4471: sub getannounce {
1.448 albertel 4472:
4473: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4474: my $announcement='';
1.800 albertel 4475: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4476: close($fh);
1.399 www 4477: if ($announcement=~/\w/) {
4478: return
4479: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4480: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4481: } else {
4482: return '';
4483: }
4484: } else {
4485: return '';
4486: }
1.351 www 4487: }
1.353 www 4488:
4489: # ---------------------------------------------------------- Course ID routines
4490: # Deal with domain's nohist_courseid.db files
4491: #
4492:
4493: sub courseidput {
1.921 raeburn 4494: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4495: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4496: my $outcome;
4497: if ($caller eq 'timeonly') {
4498: my $cids = '';
4499: foreach my $item (keys(%$storehash)) {
4500: $cids.=&escape($item).'&';
4501: }
4502: $cids=~s/\&$//;
4503: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4504: $coursehome);
4505: } else {
4506: my $items = '';
4507: foreach my $item (keys(%$storehash)) {
4508: $items.= &escape($item).'='.
4509: &freeze_escape($$storehash{$item}).'&';
4510: }
4511: $items=~s/\&$//;
4512: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4513: $coursehome);
1.918 raeburn 4514: }
4515: if ($outcome eq 'unknown_cmd') {
4516: my $what;
4517: foreach my $cid (keys(%$storehash)) {
4518: $what .= &escape($cid).'=';
1.921 raeburn 4519: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4520: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4521: }
4522: $what =~ s/\:$/&/;
4523: }
4524: $what =~ s/\&$//;
4525: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4526: } else {
4527: return $outcome;
4528: }
1.353 www 4529: }
4530:
4531: sub courseiddump {
1.921 raeburn 4532: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4533: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4534: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4535: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4536: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4537: my $as_hash = 1;
4538: my %returnhash;
4539: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4540: my %libserv = &all_library();
4541: foreach my $tryserver (keys(%libserv)) {
4542: if ( ( $hostidflag == 1
4543: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4544: || (!defined($hostidflag)) ) {
4545:
1.918 raeburn 4546: if (($domfilter eq '') ||
4547: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4548: my $rep;
4549: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4550: $rep = &LONCAPA::Lond::dump_course_id_handler(
4551: join(":", (&host_domain($tryserver), $sincefilter,
4552: &escape($descfilter), &escape($instcodefilter),
4553: &escape($ownerfilter), &escape($coursefilter),
4554: &escape($typefilter), &escape($regexp_ok),
4555: $as_hash, &escape($selfenrollonly),
4556: &escape($catfilter), $showhidden, $caller,
4557: &escape($cloner), &escape($cc_clone), $cloneonly,
4558: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4559: &escape($creationcontext),$domcloner,$hasuniquecode,
4560: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4561: } else {
4562: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4563: $sincefilter.':'.&escape($descfilter).':'.
4564: &escape($instcodefilter).':'.&escape($ownerfilter).
4565: ':'.&escape($coursefilter).':'.&escape($typefilter).
4566: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4567: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4568: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4569: &escape($cc_clone).':'.$cloneonly.':'.
4570: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4571: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4572: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4573: }
4574:
1.918 raeburn 4575: my @pairs=split(/\&/,$rep);
4576: foreach my $item (@pairs) {
4577: my ($key,$value)=split(/\=/,$item,2);
4578: $key = &unescape($key);
4579: next if ($key =~ /^error: 2 /);
4580: my $result = &thaw_unescape($value);
4581: if (ref($result) eq 'HASH') {
4582: $returnhash{$key}=$result;
4583: } else {
1.921 raeburn 4584: my @responses = split(/:/,$value);
4585: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4586: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4587: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4588: }
1.1008 raeburn 4589: }
1.353 www 4590: }
4591: }
4592: }
4593: }
4594: return %returnhash;
4595: }
4596:
1.1055 raeburn 4597: sub courselastaccess {
4598: my ($cdom,$cnum,$hostidref) = @_;
4599: my %returnhash;
4600: if ($cdom && $cnum) {
4601: my $chome = &homeserver($cnum,$cdom);
4602: if ($chome ne 'no_host') {
4603: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4604: &extract_lastaccess(\%returnhash,$rep);
4605: }
4606: } else {
4607: if (!$cdom) { $cdom=''; }
4608: my %libserv = &all_library();
4609: foreach my $tryserver (keys(%libserv)) {
4610: if (ref($hostidref) eq 'ARRAY') {
4611: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4612: }
4613: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4614: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4615: &extract_lastaccess(\%returnhash,$rep);
4616: }
4617: }
4618: }
4619: return %returnhash;
4620: }
4621:
4622: sub extract_lastaccess {
4623: my ($returnhash,$rep) = @_;
4624: if (ref($returnhash) eq 'HASH') {
4625: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4626: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4627: $rep eq '') {
4628: my @pairs=split(/\&/,$rep);
4629: foreach my $item (@pairs) {
4630: my ($key,$value)=split(/\=/,$item,2);
4631: $key = &unescape($key);
4632: next if ($key =~ /^error: 2 /);
4633: $returnhash->{$key} = &thaw_unescape($value);
4634: }
4635: }
4636: }
4637: return;
4638: }
4639:
1.658 raeburn 4640: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4641:
4642: sub dcmailput {
1.685 raeburn 4643: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4644: my $status = &Apache::lonnet::critical(
1.740 www 4645: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4646: &escape($message),$server);
1.662 raeburn 4647: return $status;
4648: }
4649:
1.658 raeburn 4650: sub dcmaildump {
4651: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4652: my %returnhash=();
1.846 albertel 4653:
4654: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4655: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4656: &escape($enddate).':';
4657: my @esc_senders=map { &escape($_)} @$senders;
4658: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4659: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4660: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4661: if (($key) && ($value)) {
4662: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4663: }
4664: }
4665: }
4666: return %returnhash;
4667: }
1.662 raeburn 4668: # ---------------------------------------------------------- Domain roles
4669:
4670: sub get_domain_roles {
4671: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4672: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4673: $startdate = '.';
4674: }
1.1018 raeburn 4675: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4676: $enddate = '.';
4677: }
1.922 raeburn 4678: my $rolelist;
4679: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4680: $rolelist = join('&',@{$roles});
1.922 raeburn 4681: }
1.662 raeburn 4682: my %personnel = ();
1.841 albertel 4683:
4684: my %servers = &get_servers($dom,'library');
4685: foreach my $tryserver (keys(%servers)) {
4686: %{$personnel{$tryserver}}=();
4687: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4688: &escape($startdate).':'.
4689: &escape($enddate).':'.
4690: &escape($rolelist), $tryserver))) {
4691: my ($key,$value) = split(/\=/,$line,2);
4692: if (($key) && ($value)) {
4693: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4694: }
4695: }
1.662 raeburn 4696: }
4697: return %personnel;
4698: }
1.658 raeburn 4699:
1.1172.2.89! raeburn 4700: sub get_active_domroles {
! 4701: my ($dom,$roles) = @_;
! 4702: return () unless (ref($roles) eq 'ARRAY');
! 4703: my $now = time;
! 4704: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
! 4705: my %domroles;
! 4706: foreach my $server (keys(%dompersonnel)) {
! 4707: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
! 4708: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
! 4709: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
! 4710: }
! 4711: }
! 4712: return %domroles;
! 4713: }
! 4714:
1.1057 www 4715: # ----------------------------------------------------------- Interval timing
1.149 www 4716:
1.1153 www 4717: {
4718: # Caches needed for speedup of navmaps
4719: # We don't want to cache this for very long at all (5 seconds at most)
4720: #
4721: # The user for whom we cache
4722: my $cachedkey='';
4723: # The cached times for this user
4724: my %cachedtimes=();
4725: # When this was last done
1.1172.2.66 raeburn 4726: my $cachedtime='';
1.1153 www 4727:
4728: sub load_all_first_access {
1.1154 raeburn 4729: my ($uname,$udom)=@_;
1.1156 www 4730: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4731: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4732: return;
4733: }
4734: $cachedtime=time;
4735: $cachedkey=$uname.':'.$udom;
4736: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4737: }
4738:
1.504 albertel 4739: sub get_first_access {
1.1162 raeburn 4740: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4741: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4742: if ($argsymb) { $symb=$argsymb; }
4743: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4744: if ($argmap) { $map = $argmap; }
1.926 albertel 4745: if ($type eq 'course') {
4746: $res='course';
4747: } elsif ($type eq 'map') {
1.588 albertel 4748: $res=&symbread($map);
4749: } else {
4750: $res=$symb;
4751: }
1.1153 www 4752: &load_all_first_access($uname,$udom);
4753: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4754: }
4755:
4756: sub set_first_access {
1.1162 raeburn 4757: my ($type,$interval)=@_;
1.790 albertel 4758: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4759: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4760: if ($type eq 'course') {
4761: $res='course';
4762: } elsif ($type eq 'map') {
1.588 albertel 4763: $res=&symbread($map);
4764: } else {
4765: $res=$symb;
4766: }
1.1153 www 4767: $cachedkey='';
1.1162 raeburn 4768: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4769: if (!$firstaccess) {
1.1162 raeburn 4770: my $start = time;
4771: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4772: $udom,$uname);
4773: if ($putres eq 'ok') {
4774: &put('timerinterval',{"$courseid\0$res"=>$interval},
4775: $udom,$uname);
4776: &appenv(
4777: {
4778: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4779: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4780: }
4781: );
4782: }
4783: return $putres;
1.505 albertel 4784: }
4785: return 'already_set';
1.504 albertel 4786: }
1.1153 www 4787: }
1.1172.2.32 raeburn 4788:
4789: sub checkout {
4790: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4791: my $now=time;
4792: my $lonhost=$perlvar{'lonHostID'};
4793: my $infostr=&escape(
4794: 'CHECKOUTTOKEN&'.
4795: $tuname.'&'.
4796: $tudom.'&'.
4797: $tcrsid.'&'.
4798: $symb.'&'.
4799: $now.'&'.$ENV{'REMOTE_ADDR'});
4800: my $token=&reply('tmpput:'.$infostr,$lonhost);
4801: if ($token=~/^error\:/) {
4802: &logthis("<font color=\"blue\">WARNING: ".
4803: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4804: "</font>");
4805: return '';
4806: }
4807:
4808: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4809: $token=~tr/a-z/A-Z/;
4810:
4811: my %infohash=('resource.0.outtoken' => $token,
4812: 'resource.0.checkouttime' => $now,
4813: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4814:
4815: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4816: return '';
4817: } else {
4818: &logthis("<font color=\"blue\">WARNING: ".
4819: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4820: "</font>");
4821: }
4822:
4823: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4824: &escape('Checkout '.$infostr.' - '.
4825: $token)) ne 'ok') {
4826: return '';
4827: } else {
4828: &logthis("<font color=\"blue\">WARNING: ".
4829: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4830: "</font>");
4831: }
4832: return $token;
4833: }
4834:
4835: # ------------------------------------------------------------ Check in an item
4836:
4837: sub checkin {
4838: my $token=shift;
4839: my $now=time;
4840: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4841: $lonhost=~tr/A-Z/a-z/;
4842: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4843: $dtoken=~s/\W/\_/g;
4844: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4845: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4846:
4847: unless (($tuname) && ($tudom)) {
4848: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4849: return '';
4850: }
4851:
4852: unless (&allowed('mgr',$tcrsid)) {
4853: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4854: $env{'user.name'}.' - '.$env{'user.domain'});
4855: return '';
4856: }
4857:
4858: my %infohash=('resource.0.intoken' => $token,
4859: 'resource.0.checkintime' => $now,
4860: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4861:
4862: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4863: return '';
4864: }
4865:
4866: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4867: &escape('Checkin - '.$token)) ne 'ok') {
4868: return '';
4869: }
4870:
4871: return ($symb,$tuname,$tudom,$tcrsid);
4872: }
4873:
1.110 www 4874: # --------------------------------------------- Set Expire Date for Spreadsheet
4875:
4876: sub expirespread {
4877: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4878: my $cid=$env{'request.course.id'};
1.110 www 4879: if ($cid) {
4880: my $now=time;
4881: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4882: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4883: $env{'course.'.$cid.'.num'}.
1.110 www 4884: ':nohist_expirationdates:'.
4885: &escape($key).'='.$now,
1.620 albertel 4886: $env{'course.'.$cid.'.home'})
1.110 www 4887: }
4888: return 'ok';
1.14 www 4889: }
4890:
1.109 www 4891: # ----------------------------------------------------- Devalidate Spreadsheets
4892:
4893: sub devalidate {
1.325 www 4894: my ($symb,$uname,$udom)=@_;
1.620 albertel 4895: my $cid=$env{'request.course.id'};
1.109 www 4896: if ($cid) {
1.391 matthew 4897: # delete the stored spreadsheets for
4898: # - the student level sheet of this user in course's homespace
4899: # - the assessment level sheet for this resource
4900: # for this user in user's homespace
1.553 albertel 4901: # - current conditional state info
1.325 www 4902: my $key=$uname.':'.$udom.':';
1.109 www 4903: my $status=
1.299 matthew 4904: &del('nohist_calculatedsheets',
1.391 matthew 4905: [$key.'studentcalc:'],
1.620 albertel 4906: $env{'course.'.$cid.'.domain'},
4907: $env{'course.'.$cid.'.num'})
1.133 albertel 4908: .' '.
4909: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4910: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4911: unless ($status eq 'ok ok') {
4912: &logthis('Could not devalidate spreadsheet '.
1.325 www 4913: $uname.' at '.$udom.' for '.
1.109 www 4914: $symb.': '.$status);
1.133 albertel 4915: }
1.553 albertel 4916: &delenv('user.state.'.$cid);
1.109 www 4917: }
4918: }
4919:
1.265 albertel 4920: sub get_scalar {
4921: my ($string,$end) = @_;
4922: my $value;
4923: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4924: $value = $1;
4925: } elsif ($$string =~ s/^([^&]*?)&//) {
4926: $value = $1;
4927: }
4928: return &unescape($value);
4929: }
4930:
4931: sub array2str {
4932: my (@array) = @_;
4933: my $result=&arrayref2str(\@array);
4934: $result=~s/^__ARRAY_REF__//;
4935: $result=~s/__END_ARRAY_REF__$//;
4936: return $result;
4937: }
4938:
1.204 albertel 4939: sub arrayref2str {
4940: my ($arrayref) = @_;
1.265 albertel 4941: my $result='__ARRAY_REF__';
1.204 albertel 4942: foreach my $elem (@$arrayref) {
1.265 albertel 4943: if(ref($elem) eq 'ARRAY') {
4944: $result.=&arrayref2str($elem).'&';
4945: } elsif(ref($elem) eq 'HASH') {
4946: $result.=&hashref2str($elem).'&';
4947: } elsif(ref($elem)) {
4948: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4949: } else {
4950: $result.=&escape($elem).'&';
4951: }
4952: }
4953: $result=~s/\&$//;
1.265 albertel 4954: $result .= '__END_ARRAY_REF__';
1.204 albertel 4955: return $result;
4956: }
4957:
1.168 albertel 4958: sub hash2str {
1.204 albertel 4959: my (%hash) = @_;
4960: my $result=&hashref2str(\%hash);
1.265 albertel 4961: $result=~s/^__HASH_REF__//;
4962: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4963: return $result;
4964: }
4965:
4966: sub hashref2str {
4967: my ($hashref)=@_;
1.265 albertel 4968: my $result='__HASH_REF__';
1.800 albertel 4969: foreach my $key (sort(keys(%$hashref))) {
4970: if (ref($key) eq 'ARRAY') {
4971: $result.=&arrayref2str($key).'=';
4972: } elsif (ref($key) eq 'HASH') {
4973: $result.=&hashref2str($key).'=';
4974: } elsif (ref($key)) {
1.265 albertel 4975: $result.='=';
1.800 albertel 4976: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4977: } else {
1.1132 raeburn 4978: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4979: }
4980:
1.800 albertel 4981: if(ref($hashref->{$key}) eq 'ARRAY') {
4982: $result.=&arrayref2str($hashref->{$key}).'&';
4983: } elsif(ref($hashref->{$key}) eq 'HASH') {
4984: $result.=&hashref2str($hashref->{$key}).'&';
4985: } elsif(ref($hashref->{$key})) {
1.265 albertel 4986: $result.='&';
1.800 albertel 4987: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4988: } else {
1.800 albertel 4989: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4990: }
4991: }
1.168 albertel 4992: $result=~s/\&$//;
1.265 albertel 4993: $result .= '__END_HASH_REF__';
1.168 albertel 4994: return $result;
4995: }
4996:
4997: sub str2hash {
1.265 albertel 4998: my ($string)=@_;
4999: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5000: return %$hash;
5001: }
5002:
5003: sub str2hashref {
1.168 albertel 5004: my ($string) = @_;
1.265 albertel 5005:
5006: my %hash;
5007:
5008: if($string !~ /^__HASH_REF__/) {
5009: if (! ($string eq '' || !defined($string))) {
5010: $hash{'error'}='Not hash reference';
5011: }
5012: return (\%hash, $string);
5013: }
5014:
5015: $string =~ s/^__HASH_REF__//;
5016:
5017: while($string !~ /^__END_HASH_REF__/) {
5018: #key
5019: my $key='';
5020: if($string =~ /^__HASH_REF__/) {
5021: ($key, $string)=&str2hashref($string);
5022: if(defined($key->{'error'})) {
5023: $hash{'error'}='Bad data';
5024: return (\%hash, $string);
5025: }
5026: } elsif($string =~ /^__ARRAY_REF__/) {
5027: ($key, $string)=&str2arrayref($string);
5028: if($key->[0] eq 'Array reference error') {
5029: $hash{'error'}='Bad data';
5030: return (\%hash, $string);
5031: }
5032: } else {
5033: $string =~ s/^(.*?)=//;
1.267 albertel 5034: $key=&unescape($1);
1.265 albertel 5035: }
5036: $string =~ s/^=//;
5037:
5038: #value
5039: my $value='';
5040: if($string =~ /^__HASH_REF__/) {
5041: ($value, $string)=&str2hashref($string);
5042: if(defined($value->{'error'})) {
5043: $hash{'error'}='Bad data';
5044: return (\%hash, $string);
5045: }
5046: } elsif($string =~ /^__ARRAY_REF__/) {
5047: ($value, $string)=&str2arrayref($string);
5048: if($value->[0] eq 'Array reference error') {
5049: $hash{'error'}='Bad data';
5050: return (\%hash, $string);
5051: }
5052: } else {
5053: $value=&get_scalar(\$string,'__END_HASH_REF__');
5054: }
5055: $string =~ s/^&//;
5056:
5057: $hash{$key}=$value;
1.204 albertel 5058: }
1.265 albertel 5059:
5060: $string =~ s/^__END_HASH_REF__//;
5061:
5062: return (\%hash, $string);
1.204 albertel 5063: }
5064:
5065: sub str2array {
1.265 albertel 5066: my ($string)=@_;
5067: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5068: return @$array;
5069: }
5070:
5071: sub str2arrayref {
1.204 albertel 5072: my ($string) = @_;
1.265 albertel 5073: my @array;
5074:
5075: if($string !~ /^__ARRAY_REF__/) {
5076: if (! ($string eq '' || !defined($string))) {
5077: $array[0]='Array reference error';
5078: }
5079: return (\@array, $string);
5080: }
5081:
5082: $string =~ s/^__ARRAY_REF__//;
5083:
5084: while($string !~ /^__END_ARRAY_REF__/) {
5085: my $value='';
5086: if($string =~ /^__HASH_REF__/) {
5087: ($value, $string)=&str2hashref($string);
5088: if(defined($value->{'error'})) {
5089: $array[0] ='Array reference error';
5090: return (\@array, $string);
5091: }
5092: } elsif($string =~ /^__ARRAY_REF__/) {
5093: ($value, $string)=&str2arrayref($string);
5094: if($value->[0] eq 'Array reference error') {
5095: $array[0] ='Array reference error';
5096: return (\@array, $string);
5097: }
5098: } else {
5099: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5100: }
5101: $string =~ s/^&//;
5102:
5103: push(@array, $value);
1.191 harris41 5104: }
1.265 albertel 5105:
5106: $string =~ s/^__END_ARRAY_REF__//;
5107:
5108: return (\@array, $string);
1.168 albertel 5109: }
5110:
1.167 albertel 5111: # -------------------------------------------------------------------Temp Store
5112:
1.168 albertel 5113: sub tmpreset {
5114: my ($symb,$namespace,$domain,$stuname) = @_;
5115: if (!$symb) {
5116: $symb=&symbread();
1.620 albertel 5117: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5118: }
5119: $symb=escape($symb);
5120:
1.620 albertel 5121: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5122: $namespace=~s/\//\_/g;
5123: $namespace=~s/\W//g;
5124:
1.620 albertel 5125: if (!$domain) { $domain=$env{'user.domain'}; }
5126: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5127: if ($domain eq 'public' && $stuname eq 'public') {
5128: $stuname=$ENV{'REMOTE_ADDR'};
5129: }
1.1117 foxr 5130: my $path=LONCAPA::tempdir();
1.168 albertel 5131: my %hash;
5132: if (tie(%hash,'GDBM_File',
5133: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5134: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5135: foreach my $key (keys(%hash)) {
1.180 albertel 5136: if ($key=~ /:$symb/) {
1.168 albertel 5137: delete($hash{$key});
5138: }
5139: }
5140: }
5141: }
5142:
1.167 albertel 5143: sub tmpstore {
1.168 albertel 5144: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5145:
5146: if (!$symb) {
5147: $symb=&symbread();
1.620 albertel 5148: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5149: }
5150: $symb=escape($symb);
5151:
5152: if (!$namespace) {
5153: # I don't think we would ever want to store this for a course.
5154: # it seems this will only be used if we don't have a course.
1.620 albertel 5155: #$namespace=$env{'request.course.id'};
1.168 albertel 5156: #if (!$namespace) {
1.620 albertel 5157: $namespace=$env{'request.state'};
1.168 albertel 5158: #}
5159: }
5160: $namespace=~s/\//\_/g;
5161: $namespace=~s/\W//g;
1.620 albertel 5162: if (!$domain) { $domain=$env{'user.domain'}; }
5163: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5164: if ($domain eq 'public' && $stuname eq 'public') {
5165: $stuname=$ENV{'REMOTE_ADDR'};
5166: }
1.168 albertel 5167: my $now=time;
5168: my %hash;
1.1117 foxr 5169: my $path=LONCAPA::tempdir();
1.168 albertel 5170: if (tie(%hash,'GDBM_File',
5171: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5172: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5173: $hash{"version:$symb"}++;
5174: my $version=$hash{"version:$symb"};
5175: my $allkeys='';
5176: foreach my $key (keys(%$storehash)) {
5177: $allkeys.=$key.':';
1.591 albertel 5178: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5179: }
5180: $hash{"$version:$symb:timestamp"}=$now;
5181: $allkeys.='timestamp';
5182: $hash{"$version:keys:$symb"}=$allkeys;
5183: if (untie(%hash)) {
5184: return 'ok';
5185: } else {
5186: return "error:$!";
5187: }
5188: } else {
5189: return "error:$!";
5190: }
5191: }
1.167 albertel 5192:
1.168 albertel 5193: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5194:
1.168 albertel 5195: sub tmprestore {
5196: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5197:
1.168 albertel 5198: if (!$symb) {
5199: $symb=&symbread();
1.620 albertel 5200: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5201: }
5202: $symb=escape($symb);
5203:
1.620 albertel 5204: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5205:
1.620 albertel 5206: if (!$domain) { $domain=$env{'user.domain'}; }
5207: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5208: if ($domain eq 'public' && $stuname eq 'public') {
5209: $stuname=$ENV{'REMOTE_ADDR'};
5210: }
1.168 albertel 5211: my %returnhash;
5212: $namespace=~s/\//\_/g;
5213: $namespace=~s/\W//g;
5214: my %hash;
1.1117 foxr 5215: my $path=LONCAPA::tempdir();
1.168 albertel 5216: if (tie(%hash,'GDBM_File',
5217: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5218: &GDBM_READER(),0640)) {
1.168 albertel 5219: my $version=$hash{"version:$symb"};
5220: $returnhash{'version'}=$version;
5221: my $scope;
5222: for ($scope=1;$scope<=$version;$scope++) {
5223: my $vkeys=$hash{"$scope:keys:$symb"};
5224: my @keys=split(/:/,$vkeys);
5225: my $key;
5226: $returnhash{"$scope:keys"}=$vkeys;
5227: foreach $key (@keys) {
1.591 albertel 5228: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5229: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5230: }
5231: }
1.168 albertel 5232: if (!(untie(%hash))) {
5233: return "error:$!";
5234: }
5235: } else {
5236: return "error:$!";
5237: }
5238: return %returnhash;
1.167 albertel 5239: }
5240:
1.9 www 5241: # ----------------------------------------------------------------------- Store
5242:
5243: sub store {
1.1172.2.64 raeburn 5244: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5245: my $home='';
5246:
1.168 albertel 5247: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5248:
1.213 www 5249: $symb=&symbclean($symb);
1.122 albertel 5250: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5251:
1.620 albertel 5252: if (!$domain) { $domain=$env{'user.domain'}; }
5253: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5254:
5255: &devalidate($symb,$stuname,$domain);
1.109 www 5256:
5257: $symb=escape($symb);
1.187 www 5258: if (!$namespace) {
1.620 albertel 5259: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5260: return '';
5261: }
5262: }
1.620 albertel 5263: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5264:
5265: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5266: $$storehash{'host'}=$perlvar{'lonHostID'};
5267:
1.12 www 5268: my $namevalue='';
1.800 albertel 5269: foreach my $key (keys(%$storehash)) {
5270: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5271: }
1.12 www 5272: $namevalue=~s/\&$//;
1.187 www 5273: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5274: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5275: }
5276:
1.47 www 5277: # -------------------------------------------------------------- Critical Store
5278:
5279: sub cstore {
1.1172.2.64 raeburn 5280: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5281: my $home='';
5282:
1.168 albertel 5283: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5284:
1.213 www 5285: $symb=&symbclean($symb);
1.122 albertel 5286: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5287:
1.620 albertel 5288: if (!$domain) { $domain=$env{'user.domain'}; }
5289: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5290:
5291: &devalidate($symb,$stuname,$domain);
1.109 www 5292:
5293: $symb=escape($symb);
1.187 www 5294: if (!$namespace) {
1.620 albertel 5295: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5296: return '';
5297: }
5298: }
1.620 albertel 5299: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5300:
5301: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5302: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5303:
1.47 www 5304: my $namevalue='';
1.800 albertel 5305: foreach my $key (keys(%$storehash)) {
5306: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5307: }
1.47 www 5308: $namevalue=~s/\&$//;
1.187 www 5309: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5310: return critical
1.1172.2.64 raeburn 5311: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5312: }
5313:
1.9 www 5314: # --------------------------------------------------------------------- Restore
5315:
5316: sub restore {
1.124 www 5317: my ($symb,$namespace,$domain,$stuname) = @_;
5318: my $home='';
5319:
1.168 albertel 5320: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5321:
1.122 albertel 5322: if (!$symb) {
1.1172.2.26 raeburn 5323: return if ($namespace eq 'courserequests');
5324: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5325: } else {
1.1172.2.26 raeburn 5326: unless ($namespace eq 'courserequests') {
5327: $symb=&escape(&symbclean($symb));
5328: }
1.122 albertel 5329: }
1.188 www 5330: if (!$namespace) {
1.620 albertel 5331: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5332: return '';
5333: }
5334: }
1.620 albertel 5335: if (!$domain) { $domain=$env{'user.domain'}; }
5336: if (!$stuname) { $stuname=$env{'user.name'}; }
5337: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5338: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5339:
1.12 www 5340: my %returnhash=();
1.800 albertel 5341: foreach my $line (split(/\&/,$answer)) {
5342: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5343: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5344: }
1.75 www 5345: my $version;
5346: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5347: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5348: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5349: }
1.75 www 5350: }
1.13 www 5351: return %returnhash;
1.34 www 5352: }
5353:
5354: # ---------------------------------------------------------- Course Description
1.1118 foxr 5355: #
5356: #
1.34 www 5357:
5358: sub coursedescription {
1.731 albertel 5359: my ($courseid,$args)=@_;
1.34 www 5360: $courseid=~s/^\///;
1.49 www 5361: $courseid=~s/\_/\//g;
1.34 www 5362: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5363: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5364: my $normalid=$cdomain.'_'.$cnum;
5365: # need to always cache even if we get errors otherwise we keep
5366: # trying and trying and trying to get the course description.
5367: my %envhash=();
5368: my %returnhash=();
1.731 albertel 5369:
5370: my $expiretime=600;
5371: if ($env{'request.course.id'} eq $normalid) {
5372: $expiretime=120;
5373: }
5374:
5375: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5376: if (!$args->{'freshen_cache'}
5377: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5378: foreach my $key (keys(%env)) {
5379: next if ($key !~ /^\Q$prefix\E(.*)/);
5380: my ($setting) = $1;
5381: $returnhash{$setting} = $env{$key};
5382: }
5383: return %returnhash;
5384: }
5385:
1.1118 foxr 5386: # get the data again
5387:
1.731 albertel 5388: if (!$args->{'one_time'}) {
5389: $envhash{'course.'.$normalid.'.last_cache'}=time;
5390: }
1.811 albertel 5391:
1.34 www 5392: if ($chome ne 'no_host') {
1.302 albertel 5393: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5394: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5395: my $username = $env{'user.name'}; # Defult username
5396: if(defined $args->{'user'}) {
5397: $username = $args->{'user'};
5398: }
1.129 albertel 5399: $returnhash{'home'}= $chome;
5400: $returnhash{'domain'} = $cdomain;
5401: $returnhash{'num'} = $cnum;
1.741 raeburn 5402: if (!defined($returnhash{'type'})) {
5403: $returnhash{'type'} = 'Course';
5404: }
1.130 albertel 5405: while (my ($name,$value) = each %returnhash) {
1.53 www 5406: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5407: }
1.270 www 5408: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5409: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5410: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5411: $envhash{'course.'.$normalid.'.home'}=$chome;
5412: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5413: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5414: }
5415: }
1.731 albertel 5416: if (!$args->{'one_time'}) {
1.949 raeburn 5417: &appenv(\%envhash);
1.731 albertel 5418: }
1.302 albertel 5419: return %returnhash;
1.461 www 5420: }
5421:
1.1080 raeburn 5422: sub update_released_required {
5423: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5424: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5425: $cid = $env{'request.course.id'};
5426: $cdom = $env{'course.'.$cid.'.domain'};
5427: $cnum = $env{'course.'.$cid.'.num'};
5428: $chome = $env{'course.'.$cid.'.home'};
5429: }
5430: if ($needsrelease) {
5431: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5432: my $needsupdate;
5433: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5434: $needsupdate = 1;
5435: } else {
5436: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5437: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5438: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5439: $needsupdate = 1;
5440: }
5441: }
5442: if ($needsupdate) {
5443: my %needshash = (
5444: 'internal.releaserequired' => $needsrelease,
5445: );
5446: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5447: if ($putresult eq 'ok') {
5448: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5449: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5450: if (ref($crsinfo{$cid}) eq 'HASH') {
5451: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5452: &courseidput($cdom,\%crsinfo,$chome,'notime');
5453: }
5454: }
5455: }
5456: }
5457: return;
5458: }
5459:
1.461 www 5460: # -------------------------------------------------See if a user is privileged
5461:
5462: sub privileged {
1.1172.2.23 raeburn 5463: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5464: my $now = time;
1.1172.2.23 raeburn 5465: my $roles;
5466: if (ref($possroles) eq 'ARRAY') {
5467: $roles = $possroles;
5468: } else {
5469: $roles = ['dc','su'];
5470: }
5471: if (ref($possdomains) eq 'ARRAY') {
5472: my %privileged = &privileged_by_domain($possdomains,$roles);
5473: foreach my $dom (@{$possdomains}) {
5474: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5475: (ref($privileged{$dom}) eq 'HASH')) {
5476: foreach my $role (@{$roles}) {
5477: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5478: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5479: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5480: return 1 unless (($end && $end < $now) ||
5481: ($start && $start > $now));
5482: }
5483: }
5484: }
5485: }
5486: }
5487: } else {
5488: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5489: my $now = time;
1.1170 droeschl 5490:
1.1172.2.58 raeburn 5491: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5492: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5493: if (grep(/^\Q$trole\E$/,@{$roles})) {
5494: return 1 unless ($tend && $tend < $now)
5495: or ($tstart && $tstart > $now);
1.1170 droeschl 5496: }
1.1172.2.23 raeburn 5497: }
5498: }
1.461 www 5499: return 0;
1.9 www 5500: }
1.1 albertel 5501:
1.1172.2.23 raeburn 5502: sub privileged_by_domain {
5503: my ($domains,$roles) = @_;
5504: my %privileged = ();
5505: my $cachetime = 60*60*24;
5506: my $now = time;
5507: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5508: return %privileged;
5509: }
5510: foreach my $dom (@{$domains}) {
5511: next if (ref($privileged{$dom}) eq 'HASH');
5512: my $needroles;
5513: foreach my $role (@{$roles}) {
5514: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5515: if (defined($cached)) {
5516: if (ref($result) eq 'HASH') {
5517: $privileged{$dom}{$role} = $result;
5518: }
5519: } else {
5520: $needroles = 1;
5521: }
5522: }
5523: if ($needroles) {
5524: my %dompersonnel = &get_domain_roles($dom,$roles);
5525: $privileged{$dom} = {};
5526: foreach my $server (keys(%dompersonnel)) {
5527: if (ref($dompersonnel{$server}) eq 'HASH') {
5528: foreach my $item (keys(%{$dompersonnel{$server}})) {
5529: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5530: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5531: next if ($end && $end < $now);
5532: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5533: $dompersonnel{$server}{$item};
5534: }
5535: }
5536: }
5537: if (ref($privileged{$dom}) eq 'HASH') {
5538: foreach my $role (@{$roles}) {
5539: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5540: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5541: } else {
5542: my %hash = ();
5543: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5544: }
5545: }
5546: }
5547: }
5548: }
5549: return %privileged;
5550: }
5551:
1.103 harris41 5552: # -------------------------------------------------------- Get user privileges
1.11 www 5553:
5554: sub rolesinit {
1.1169 droeschl 5555: my ($domain, $username) = @_;
5556: my %userroles = ('user.login.time' => time);
5557: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5558:
5559: # firstaccess and timerinterval are related to timed maps/resources.
5560: # also, blocking can be triggered by an activating timer
5561: # it's saved in the user's %env.
5562: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5563: my %timerinterval = &dump('timerinterval', $domain, $username);
5564: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5565: %timerintchk, %timerintenv);
5566:
1.1162 raeburn 5567: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5568: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5569: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5570: }
1.1169 droeschl 5571:
1.1162 raeburn 5572: foreach my $key (keys(%timerinterval)) {
5573: my ($cid,$rest) = split(/\0/,$key);
5574: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5575: }
1.1169 droeschl 5576:
1.11 www 5577: my %allroles=();
1.1162 raeburn 5578: my %allgroups=();
1.11 www 5579:
1.1172.2.58 raeburn 5580: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5581: my $role = $rolesdump{$area};
5582: $area =~ s/\_\w\w$//;
5583:
5584: my ($trole, $tend, $tstart, $group_privs);
5585:
5586: if ($role =~ /^cr/) {
5587: # Custom role, defined by a user
5588: # e.g., user.role.cr/msu/smith/mynewrole
5589: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5590: $trole = $1;
5591: ($tend, $tstart) = split('_', $2);
5592: } else {
5593: $trole = $role;
5594: }
5595: } elsif ($role =~ m|^gr/|) {
5596: # Role of member in a group, defined within a course/community
5597: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5598: ($trole, $tend, $tstart) = split(/_/, $role);
5599: next if $tstart eq '-1';
5600: ($trole, $group_privs) = split(/\//, $trole);
5601: $group_privs = &unescape($group_privs);
5602: } else {
5603: # Just a normal role, defined in roles.tab
5604: ($trole, $tend, $tstart) = split(/_/,$role);
5605: }
5606:
5607: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5608: $username);
5609: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5610:
5611: # role expired or not available yet?
5612: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5613: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5614:
5615: next if $area eq '' or $trole eq '';
5616:
5617: my $spec = "$trole.$area";
5618: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5619:
5620: if ($trole =~ /^cr\//) {
5621: # Custom role, defined by a user
5622: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5623: } elsif ($trole eq 'gr') {
5624: # Role of a member in a group, defined within a course/community
5625: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5626: next;
5627: } else {
5628: # Normal role, defined in roles.tab
5629: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5630: }
5631:
5632: my $cid = $tdomain.'_'.$trest;
5633: unless ($firstaccchk{$cid}) {
5634: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5635: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5636: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5637: $coursetimerstarts{$cid}{$item};
5638: }
5639: }
5640: $firstaccchk{$cid} = 1;
5641: }
5642: unless ($timerintchk{$cid}) {
5643: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5644: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5645: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5646: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5647: }
1.12 www 5648: }
1.1169 droeschl 5649: $timerintchk{$cid} = 1;
1.191 harris41 5650: }
1.11 www 5651: }
1.1169 droeschl 5652:
5653: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5654: \%allroles, \%allgroups);
5655: $env{'user.adv'} = $userroles{'user.adv'};
5656:
1.1162 raeburn 5657: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5658: }
5659:
1.567 raeburn 5660: sub set_arearole {
1.1172.2.19 raeburn 5661: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5662: unless ($nolog) {
1.567 raeburn 5663: # log the associated role with the area
1.1172.2.19 raeburn 5664: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5665: }
1.743 albertel 5666: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5667: }
5668:
5669: sub custom_roleprivs {
5670: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5671: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5672: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5673: if (&hostname($homsvr) ne '') {
1.567 raeburn 5674: my ($rdummy,$roledef)=
5675: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5676: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5677: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5678: if (defined($syspriv)) {
1.1043 raeburn 5679: if ($trest =~ /^$match_community$/) {
5680: $syspriv =~ s/bre\&S//;
5681: }
1.567 raeburn 5682: $$allroles{'cm./'}.=':'.$syspriv;
5683: $$allroles{$spec.'./'}.=':'.$syspriv;
5684: }
5685: if ($tdomain ne '') {
5686: if (defined($dompriv)) {
5687: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5688: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5689: }
5690: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89! raeburn 5691: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
! 5692: my $rolename = $1;
! 5693: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
! 5694: }
1.567 raeburn 5695: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5696: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5697: }
5698: }
5699: }
5700: }
5701: }
5702:
1.1172.2.89! raeburn 5703: sub course_adhocrole_privs {
! 5704: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
! 5705: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
! 5706: if ($overrides{"internal.adhocpriv.$rolename"}) {
! 5707: my (%currprivs,%storeprivs);
! 5708: foreach my $item (split(/:/,$coursepriv)) {
! 5709: my ($priv,$restrict) = split(/\&/,$item);
! 5710: $currprivs{$priv} = $restrict;
! 5711: }
! 5712: my (%possadd,%possremove,%full);
! 5713: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
! 5714: my ($priv,$restrict)=split(/\&/,$item);
! 5715: $full{$priv} = $restrict;
! 5716: }
! 5717: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
! 5718: next if ($item eq '');
! 5719: my ($rule,$rest) = split(/=/,$item);
! 5720: next unless (($rule eq 'off') || ($rule eq 'on'));
! 5721: foreach my $priv (split(/:/,$rest)) {
! 5722: if ($priv ne '') {
! 5723: if ($rule eq 'off') {
! 5724: $possremove{$priv} = 1;
! 5725: } else {
! 5726: $possadd{$priv} = 1;
! 5727: }
! 5728: }
! 5729: }
! 5730: }
! 5731: foreach my $priv (sort(keys(%full))) {
! 5732: if (exists($currprivs{$priv})) {
! 5733: unless (exists($possremove{$priv})) {
! 5734: $storeprivs{$priv} = $currprivs{$priv};
! 5735: }
! 5736: } elsif (exists($possadd{$priv})) {
! 5737: $storeprivs{$priv} = $full{$priv};
! 5738: }
! 5739: }
! 5740: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
! 5741: }
! 5742: return $coursepriv;
! 5743: }
! 5744:
1.678 raeburn 5745: sub group_roleprivs {
5746: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5747: my $access = 1;
5748: my $now = time;
5749: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5750: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5751: if ($access) {
1.811 albertel 5752: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5753: $$allgroups{$course}{$group} .=':'.$group_privs;
5754: }
5755: }
1.567 raeburn 5756:
5757: sub standard_roleprivs {
5758: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5759: if (defined($pr{$trole.':s'})) {
5760: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5761: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5762: }
5763: if ($tdomain ne '') {
5764: if (defined($pr{$trole.':d'})) {
5765: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5766: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5767: }
5768: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5769: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5770: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5771: }
5772: }
5773: }
5774:
5775: sub set_userprivs {
1.1064 raeburn 5776: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5777: my $author=0;
5778: my $adv=0;
1.678 raeburn 5779: my %grouproles = ();
5780: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5781: my @groupkeys;
1.1000 raeburn 5782: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5783: push(@groupkeys,$role);
5784: }
5785: if (ref($groups_roles) eq 'HASH') {
5786: foreach my $key (keys(%{$groups_roles})) {
5787: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5788: push(@groupkeys,$key);
5789: }
5790: }
5791: }
5792: if (@groupkeys > 0) {
5793: foreach my $role (@groupkeys) {
5794: my ($trole,$area,$sec,$extendedarea);
5795: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5796: $trole = $1;
5797: $area = $2;
5798: $sec = $3;
5799: $extendedarea = $area.$sec;
5800: if (exists($$allgroups{$area})) {
5801: foreach my $group (keys(%{$$allgroups{$area}})) {
5802: my $spec = $trole.'.'.$extendedarea;
5803: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5804: $$allgroups{$area}{$group};
1.1064 raeburn 5805: }
1.678 raeburn 5806: }
5807: }
5808: }
5809: }
5810: }
1.800 albertel 5811: foreach my $group (keys(%grouproles)) {
5812: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5813: }
1.800 albertel 5814: foreach my $role (keys(%{$allroles})) {
5815: my %thesepriv;
1.941 raeburn 5816: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5817: foreach my $item (split(/:/,$$allroles{$role})) {
5818: if ($item ne '') {
5819: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5820: if ($restrictions eq '') {
5821: $thesepriv{$privilege}='F';
5822: } elsif ($thesepriv{$privilege} ne 'F') {
5823: $thesepriv{$privilege}.=$restrictions;
5824: }
5825: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5826: }
5827: }
5828: my $thesestr='';
1.1104 raeburn 5829: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5830: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5831: }
5832: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5833: }
5834: return ($author,$adv);
5835: }
5836:
1.994 raeburn 5837: sub role_status {
1.1104 raeburn 5838: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5839: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5840: my ($one,$two) = split(m{\./},$rolekey,2);
5841: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5842: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5843: $$where = '/'.$two;
1.994 raeburn 5844: $$trolecode=$$role.'.'.$$where;
5845: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5846: $$tstatus='is';
1.1104 raeburn 5847: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5848: $$tstatus='future';
1.1034 raeburn 5849: if ($$tstart<$now) {
5850: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5851: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5852: my (%allroles,%allgroups,$group_privs,
5853: %groups_roles,@rolecodes);
1.1002 raeburn 5854: my %userroles = (
5855: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5856: );
1.1064 raeburn 5857: @rolecodes = ('cm');
1.1002 raeburn 5858: my $spec=$$role.'.'.$$where;
5859: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5860: if ($$role =~ /^cr\//) {
5861: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5862: push(@rolecodes,'cr');
1.1002 raeburn 5863: } elsif ($$role eq 'gr') {
1.1064 raeburn 5864: push(@rolecodes,$$role);
1.1002 raeburn 5865: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5866: $env{'user.name'});
1.1064 raeburn 5867: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5868: (undef,my $group_privs) = split(/\//,$trole);
5869: $group_privs = &unescape($group_privs);
5870: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5871: 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 5872: &get_groups_roles($tdomain,$trest,
5873: \%course_roles,\@rolecodes,
5874: \%groups_roles);
1.1002 raeburn 5875: } else {
1.1064 raeburn 5876: push(@rolecodes,$$role);
1.1002 raeburn 5877: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5878: }
1.1064 raeburn 5879: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5880: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5881: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5882: }
5883: }
1.1034 raeburn 5884: $$tstatus = 'is';
1.1002 raeburn 5885: }
1.994 raeburn 5886: }
5887: if ($$tend) {
1.1104 raeburn 5888: if ($$tend<$update) {
1.994 raeburn 5889: $$tstatus='expired';
5890: } elsif ($$tend<$now) {
5891: $$tstatus='will_not';
5892: }
5893: }
5894: }
5895: }
5896: }
5897:
1.1104 raeburn 5898: sub get_groups_roles {
5899: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5900: return unless((ref($cdom_courseroles) eq 'HASH') &&
5901: (ref($rolecodes) eq 'ARRAY') &&
5902: (ref($groups_roles) eq 'HASH'));
5903: if (keys(%{$cdom_courseroles}) > 0) {
5904: my ($cnum) = ($rest =~ /^($match_courseid)/);
5905: if ($cdom ne '' && $cnum ne '') {
5906: foreach my $key (keys(%{$cdom_courseroles})) {
5907: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5908: my $crsrole = $1;
5909: my $crssec = $2;
5910: if ($crsrole =~ /^cr/) {
5911: unless (grep(/^cr$/,@{$rolecodes})) {
5912: push(@{$rolecodes},'cr');
5913: }
5914: } else {
5915: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5916: push(@{$rolecodes},$crsrole);
5917: }
5918: }
5919: my $rolekey = "$crsrole./$cdom/$cnum";
5920: if ($crssec ne '') {
5921: $rolekey .= "/$crssec";
5922: }
5923: $rolekey .= './';
5924: $groups_roles->{$rolekey} = $rolecodes;
5925: }
5926: }
5927: }
5928: }
5929: return;
5930: }
5931:
5932: sub delete_env_groupprivs {
5933: my ($where,$courseroles,$possroles) = @_;
5934: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5935: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5936: unless (ref($courseroles->{$udom}) eq 'HASH') {
5937: %{$courseroles->{$udom}} =
5938: &get_my_roles('','','userroles',['active'],
5939: $possroles,[$udom],1);
5940: }
5941: if (ref($courseroles->{$udom}) eq 'HASH') {
5942: foreach my $item (keys(%{$courseroles->{$udom}})) {
5943: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5944: my $area = '/'.$cdom.'/'.$cnum;
5945: my $privkey = "user.priv.$crsrole.$area";
5946: if ($crssec ne '') {
5947: $privkey .= '/'.$crssec;
5948: }
5949: $privkey .= ".$area/$group";
5950: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5951: }
5952: }
5953: return;
5954: }
5955:
1.994 raeburn 5956: sub check_adhoc_privs {
1.1172.2.86 raeburn 5957: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 5958: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 5959: if ($sec) {
5960: $cckey .= '/'.$sec;
5961: }
1.1172.2.9 raeburn 5962: my $setprivs;
1.994 raeburn 5963: if ($env{$cckey}) {
5964: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5965: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5966: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 5967: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 5968: $setprivs = 1;
1.994 raeburn 5969: }
5970: } else {
1.1172.2.87 raeburn 5971: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 5972: $setprivs = 1;
1.994 raeburn 5973: }
1.1172.2.9 raeburn 5974: return $setprivs;
1.994 raeburn 5975: }
5976:
5977: sub set_adhoc_privileges {
1.1172.2.84 raeburn 5978: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 5979: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 5980: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 5981: if ($sec ne '') {
5982: $area .= '/'.$sec;
5983: }
1.994 raeburn 5984: my $spec = $role.'.'.$area;
5985: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5986: $env{'user.name'},1);
1.1172.2.84 raeburn 5987: my %rolehash = ();
1.1172.2.89! raeburn 5988: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
! 5989: my $rolename = $1;
1.1172.2.84 raeburn 5990: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89! raeburn 5991: my %domdef = &get_domain_defaults($dcdom);
! 5992: if (ref($domdef{'adhocroles'}) eq 'HASH') {
! 5993: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
! 5994: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
! 5995: }
! 5996: }
1.1172.2.84 raeburn 5997: } else {
5998: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
5999: }
6000: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6001: &appenv(\%userroles,[$role,'cm']);
6002: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 6003: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6004: &appenv( {'request.role' => $spec,
6005: 'request.role.domain' => $dcdom,
1.1172.2.89! raeburn 6006: 'request.course.sec' => $sec,
1.1088 raeburn 6007: }
6008: );
6009: my $tadv=0;
6010: if (&allowed('adv') eq 'F') { $tadv=1; }
6011: &appenv({'request.role.adv' => $tadv});
6012: }
1.994 raeburn 6013: }
6014:
1.12 www 6015: # --------------------------------------------------------------- get interface
6016:
6017: sub get {
1.131 albertel 6018: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6019: my $items='';
1.800 albertel 6020: foreach my $item (@$storearr) {
6021: $items.=&escape($item).'&';
1.191 harris41 6022: }
1.12 www 6023: $items=~s/\&$//;
1.620 albertel 6024: if (!$udomain) { $udomain=$env{'user.domain'}; }
6025: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6026: my $uhome=&homeserver($uname,$udomain);
6027:
1.133 albertel 6028: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6029: my @pairs=split(/\&/,$rep);
1.273 albertel 6030: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6031: return @pairs;
6032: }
1.15 www 6033: my %returnhash=();
1.42 www 6034: my $i=0;
1.800 albertel 6035: foreach my $item (@$storearr) {
6036: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6037: $i++;
1.191 harris41 6038: }
1.15 www 6039: return %returnhash;
1.27 www 6040: }
6041:
6042: # --------------------------------------------------------------- del interface
6043:
6044: sub del {
1.133 albertel 6045: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6046: my $items='';
1.800 albertel 6047: foreach my $item (@$storearr) {
6048: $items.=&escape($item).'&';
1.191 harris41 6049: }
1.984 neumanie 6050:
1.27 www 6051: $items=~s/\&$//;
1.620 albertel 6052: if (!$udomain) { $udomain=$env{'user.domain'}; }
6053: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6054: my $uhome=&homeserver($uname,$udomain);
6055: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6056: }
6057:
6058: # -------------------------------------------------------------- dump interface
6059:
1.1172.2.22 raeburn 6060: sub unserialize {
6061: my ($rep, $escapedkeys) = @_;
6062:
6063: return {} if $rep =~ /^error/;
6064:
6065: my %returnhash=();
6066: foreach my $item (split(/\&/,$rep)) {
6067: my ($key, $value) = split(/=/, $item, 2);
6068: $key = unescape($key) unless $escapedkeys;
6069: next if $key =~ /^error: 2 /;
6070: $returnhash{$key} = &thaw_unescape($value);
6071: }
6072: return \%returnhash;
6073: }
6074:
6075: # see Lond::dump_with_regexp
6076: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6077: sub dump {
1.1172.2.22 raeburn 6078: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6079: if (!$udomain) { $udomain=$env{'user.domain'}; }
6080: if (!$uname) { $uname=$env{'user.name'}; }
6081: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6082:
1.1172.2.55 raeburn 6083: if ($regexp) {
6084: $regexp=&escape($regexp);
6085: } else {
6086: $regexp='.';
6087: }
1.1172.2.22 raeburn 6088: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6089: # user is hosted on this machine
1.1172.2.55 raeburn 6090: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6091: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6092: return %{&unserialize($reply, $escapedkeys)};
6093: }
1.1166 raeburn 6094: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6095: my @pairs=split(/\&/,$rep);
6096: my %returnhash=();
1.1098 foxr 6097: if (!($rep =~ /^error/ )) {
6098: foreach my $item (@pairs) {
6099: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6100: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6101: next if ($key =~ /^error: 2 /);
6102: $returnhash{$key}=&thaw_unescape($value);
6103: }
1.755 albertel 6104: }
6105: return %returnhash;
1.407 www 6106: }
6107:
1.1098 foxr 6108:
1.717 albertel 6109: # --------------------------------------------------------- dumpstore interface
6110:
6111: sub dumpstore {
6112: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6113: # same as dump but keys must be escaped. They may contain colon separated
6114: # lists of values that may themself contain colons (e.g. symbs).
6115: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6116: }
6117:
1.407 www 6118: # -------------------------------------------------------------- keys interface
6119:
6120: sub getkeys {
6121: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6122: if (!$udomain) { $udomain=$env{'user.domain'}; }
6123: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6124: my $uhome=&homeserver($uname,$udomain);
6125: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6126: my @keyarray=();
1.800 albertel 6127: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6128: next if ($key =~ /^error: 2 /);
1.800 albertel 6129: push(@keyarray,&unescape($key));
1.407 www 6130: }
6131: return @keyarray;
1.318 matthew 6132: }
6133:
1.319 matthew 6134: # --------------------------------------------------------------- currentdump
6135: sub currentdump {
1.328 matthew 6136: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6137: $courseid = $env{'request.course.id'} if (! defined($courseid));
6138: $sdom = $env{'user.domain'} if (! defined($sdom));
6139: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6140: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6141: my $rep;
6142:
6143: if (grep { $_ eq $uhome } current_machine_ids()) {
6144: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6145: $courseid)));
6146: } else {
6147: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6148: }
6149:
1.318 matthew 6150: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6151: #
1.318 matthew 6152: my %returnhash=();
1.319 matthew 6153: #
6154: if ($rep eq "unknown_cmd") {
6155: # an old lond will not know currentdump
6156: # Do a dump and make it look like a currentdump
1.822 albertel 6157: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6158: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6159: my %hash = @tmp;
6160: @tmp=();
1.424 matthew 6161: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6162: } else {
6163: my @pairs=split(/\&/,$rep);
1.800 albertel 6164: foreach my $pair (@pairs) {
6165: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6166: my ($symb,$param) = split(/:/,$key);
6167: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6168: &thaw_unescape($value);
1.319 matthew 6169: }
1.191 harris41 6170: }
1.12 www 6171: return %returnhash;
1.424 matthew 6172: }
6173:
6174: sub convert_dump_to_currentdump{
6175: my %hash = %{shift()};
6176: my %returnhash;
6177: # Code ripped from lond, essentially. The only difference
6178: # here is the unescaping done by lonnet::dump(). Conceivably
6179: # we might run in to problems with parameter names =~ /^v\./
6180: while (my ($key,$value) = each(%hash)) {
6181: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6182: $symb = &unescape($symb);
6183: $param = &unescape($param);
1.424 matthew 6184: next if ($v eq 'version' || $symb eq 'keys');
6185: next if (exists($returnhash{$symb}) &&
6186: exists($returnhash{$symb}->{$param}) &&
6187: $returnhash{$symb}->{'v.'.$param} > $v);
6188: $returnhash{$symb}->{$param}=$value;
6189: $returnhash{$symb}->{'v.'.$param}=$v;
6190: }
6191: #
6192: # Remove all of the keys in the hashes which keep track of
6193: # the version of the parameter.
6194: while (my ($symb,$param_hash) = each(%returnhash)) {
6195: # use a foreach because we are going to delete from the hash.
6196: foreach my $key (keys(%$param_hash)) {
6197: delete($param_hash->{$key}) if ($key =~ /^v\./);
6198: }
6199: }
6200: return \%returnhash;
1.12 www 6201: }
6202:
1.627 albertel 6203: # ------------------------------------------------------ critical inc interface
6204:
6205: sub cinc {
6206: return &inc(@_,'critical');
6207: }
6208:
1.449 matthew 6209: # --------------------------------------------------------------- inc interface
6210:
6211: sub inc {
1.627 albertel 6212: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6213: if (!$udomain) { $udomain=$env{'user.domain'}; }
6214: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6215: my $uhome=&homeserver($uname,$udomain);
6216: my $items='';
6217: if (! ref($store)) {
6218: # got a single value, so use that instead
6219: $items = &escape($store).'=&';
6220: } elsif (ref($store) eq 'SCALAR') {
6221: $items = &escape($$store).'=&';
6222: } elsif (ref($store) eq 'ARRAY') {
6223: $items = join('=&',map {&escape($_);} @{$store});
6224: } elsif (ref($store) eq 'HASH') {
6225: while (my($key,$value) = each(%{$store})) {
6226: $items.= &escape($key).'='.&escape($value).'&';
6227: }
6228: }
6229: $items=~s/\&$//;
1.627 albertel 6230: if ($critical) {
6231: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6232: } else {
6233: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6234: }
1.449 matthew 6235: }
6236:
1.12 www 6237: # --------------------------------------------------------------- put interface
6238:
6239: sub put {
1.134 albertel 6240: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6241: if (!$udomain) { $udomain=$env{'user.domain'}; }
6242: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6243: my $uhome=&homeserver($uname,$udomain);
1.12 www 6244: my $items='';
1.800 albertel 6245: foreach my $item (keys(%$storehash)) {
6246: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6247: }
1.12 www 6248: $items=~s/\&$//;
1.134 albertel 6249: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6250: }
6251:
1.631 albertel 6252: # ------------------------------------------------------------ newput interface
6253:
6254: sub newput {
6255: my ($namespace,$storehash,$udomain,$uname)=@_;
6256: if (!$udomain) { $udomain=$env{'user.domain'}; }
6257: if (!$uname) { $uname=$env{'user.name'}; }
6258: my $uhome=&homeserver($uname,$udomain);
6259: my $items='';
6260: foreach my $key (keys(%$storehash)) {
6261: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6262: }
6263: $items=~s/\&$//;
6264: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6265: }
6266:
6267: # --------------------------------------------------------- putstore interface
6268:
1.524 raeburn 6269: sub putstore {
1.1172.2.59 raeburn 6270: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6271: if (!$udomain) { $udomain=$env{'user.domain'}; }
6272: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6273: my $uhome=&homeserver($uname,$udomain);
6274: my $items='';
1.715 albertel 6275: foreach my $key (keys(%$storehash)) {
6276: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6277: }
1.715 albertel 6278: $items=~s/\&$//;
1.716 albertel 6279: my $esc_symb=&escape($symb);
6280: my $esc_v=&escape($version);
1.715 albertel 6281: my $reply =
1.716 albertel 6282: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6283: $uhome);
1.1172.2.59 raeburn 6284: if (($tolog) && ($reply eq 'ok')) {
6285: my $namevalue='';
6286: foreach my $key (keys(%{$storehash})) {
6287: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6288: }
6289: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6290: '&host='.&escape($perlvar{'lonHostID'}).
6291: '&version='.$esc_v.
6292: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6293: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6294: }
1.715 albertel 6295: if ($reply eq 'unknown_cmd') {
1.716 albertel 6296: # gfall back to way things use to be done
1.715 albertel 6297: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6298: $uname);
1.524 raeburn 6299: }
1.715 albertel 6300: return $reply;
6301: }
6302:
6303: sub old_putstore {
1.716 albertel 6304: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6305: if (!$udomain) { $udomain=$env{'user.domain'}; }
6306: if (!$uname) { $uname=$env{'user.name'}; }
6307: my $uhome=&homeserver($uname,$udomain);
6308: my %newstorehash;
1.800 albertel 6309: foreach my $item (keys(%$storehash)) {
6310: my $key = $version.':'.&escape($symb).':'.$item;
6311: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6312: }
6313: my $items='';
6314: my %allitems = ();
1.800 albertel 6315: foreach my $item (keys(%newstorehash)) {
6316: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6317: my $key = $1.':keys:'.$2;
6318: $allitems{$key} .= $3.':';
6319: }
1.800 albertel 6320: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6321: }
1.800 albertel 6322: foreach my $item (keys(%allitems)) {
6323: $allitems{$item} =~ s/\:$//;
6324: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6325: }
6326: $items=~s/\&$//;
6327: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6328: }
6329:
1.47 www 6330: # ------------------------------------------------------ critical put interface
6331:
6332: sub cput {
1.134 albertel 6333: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6334: if (!$udomain) { $udomain=$env{'user.domain'}; }
6335: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6336: my $uhome=&homeserver($uname,$udomain);
1.47 www 6337: my $items='';
1.800 albertel 6338: foreach my $item (keys(%$storehash)) {
6339: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6340: }
1.47 www 6341: $items=~s/\&$//;
1.134 albertel 6342: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6343: }
6344:
6345: # -------------------------------------------------------------- eget interface
6346:
6347: sub eget {
1.133 albertel 6348: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6349: my $items='';
1.800 albertel 6350: foreach my $item (@$storearr) {
6351: $items.=&escape($item).'&';
1.191 harris41 6352: }
1.12 www 6353: $items=~s/\&$//;
1.620 albertel 6354: if (!$udomain) { $udomain=$env{'user.domain'}; }
6355: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6356: my $uhome=&homeserver($uname,$udomain);
6357: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6358: my @pairs=split(/\&/,$rep);
6359: my %returnhash=();
1.42 www 6360: my $i=0;
1.800 albertel 6361: foreach my $item (@$storearr) {
6362: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6363: $i++;
1.191 harris41 6364: }
1.12 www 6365: return %returnhash;
6366: }
6367:
1.667 albertel 6368: # ------------------------------------------------------------ tmpput interface
6369: sub tmpput {
1.802 raeburn 6370: my ($storehash,$server,$context)=@_;
1.667 albertel 6371: my $items='';
1.800 albertel 6372: foreach my $item (keys(%$storehash)) {
6373: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6374: }
6375: $items=~s/\&$//;
1.802 raeburn 6376: if (defined($context)) {
6377: $items .= ':'.&escape($context);
6378: }
1.667 albertel 6379: return &reply("tmpput:$items",$server);
6380: }
6381:
6382: # ------------------------------------------------------------ tmpget interface
6383: sub tmpget {
1.688 albertel 6384: my ($token,$server)=@_;
6385: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6386: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6387: my %returnhash;
1.1172.2.85 raeburn 6388: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6389: return %returnhash;
6390: }
1.667 albertel 6391: foreach my $item (split(/\&/,$rep)) {
6392: my ($key,$value)=split(/=/,$item);
6393: $returnhash{&unescape($key)}=&thaw_unescape($value);
6394: }
6395: return %returnhash;
6396: }
6397:
1.1113 raeburn 6398: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6399: sub tmpdel {
6400: my ($token,$server)=@_;
6401: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6402: return &reply("tmpdel:$token",$server);
6403: }
6404:
1.1172.2.13 raeburn 6405: # ------------------------------------------------------------ get_timebased_id
6406:
6407: sub get_timebased_id {
6408: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6409: $maxtries) = @_;
6410: my ($newid,$error,$dellock);
6411: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6412: return ('','ok','invalid call to get suffix');
6413: }
6414:
6415: # set defaults for any optional args for which values were not supplied
6416: if ($who eq '') {
6417: $who = $env{'user.name'}.':'.$env{'user.domain'};
6418: }
6419: if (!$locktries) {
6420: $locktries = 3;
6421: }
6422: if (!$maxtries) {
6423: $maxtries = 10;
6424: }
6425:
6426: if (($cdom eq '') || ($cnum eq '')) {
6427: if ($env{'request.course.id'}) {
6428: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6429: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6430: }
6431: if (($cdom eq '') || ($cnum eq '')) {
6432: return ('','ok','call to get suffix not in course context');
6433: }
6434: }
6435:
6436: # construct locking item
6437: my $lockhash = {
6438: $prefix."\0".'locked_'.$keyid => $who,
6439: };
6440: my $tries = 0;
6441:
6442: # attempt to get lock on nohist_$namespace file
6443: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6444: while (($gotlock ne 'ok') && $tries <$locktries) {
6445: $tries ++;
6446: sleep 1;
6447: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6448: }
6449:
6450: # attempt to get unique identifier, based on current timestamp
6451: if ($gotlock eq 'ok') {
6452: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6453: my $id = time;
6454: $newid = $id;
1.1172.2.56 raeburn 6455: if ($idtype eq 'addcode') {
6456: $newid .= &sixnum_code();
6457: }
1.1172.2.13 raeburn 6458: my $idtries = 0;
6459: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6460: if ($idtype eq 'concat') {
6461: $newid = $id.$idtries;
1.1172.2.56 raeburn 6462: } elsif ($idtype eq 'addcode') {
6463: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6464: } else {
6465: $newid ++;
6466: }
6467: $idtries ++;
6468: }
6469: if (!exists($inuse{$prefix."\0".$newid})) {
6470: my %new_item = (
6471: $prefix."\0".$newid => $who,
6472: );
6473: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6474: $cdom,$cnum);
6475: if ($putresult ne 'ok') {
6476: undef($newid);
6477: $error = 'error saving new item: '.$putresult;
6478: }
6479: } else {
1.1172.2.56 raeburn 6480: undef($newid);
1.1172.2.13 raeburn 6481: $error = ('error: no unique suffix available for the new item ');
6482: }
6483: # remove lock
6484: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6485: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6486: } else {
6487: $error = "error: could not obtain lockfile\n";
6488: $dellock = 'ok';
1.1172.2.58 raeburn 6489: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6490: $dellock = 'nolock';
6491: }
1.1172.2.13 raeburn 6492: }
6493: return ($newid,$dellock,$error);
6494: }
6495:
1.1172.2.56 raeburn 6496: sub sixnum_code {
6497: my $code;
6498: for (0..6) {
6499: $code .= int( rand(9) );
6500: }
6501: return $code;
6502: }
6503:
1.765 albertel 6504: # -------------------------------------------------- portfolio access checking
6505:
6506: sub portfolio_access {
1.1172.2.77 raeburn 6507: my ($requrl,$clientip) = @_;
1.765 albertel 6508: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6509: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6510: if ($result) {
6511: my %setters;
6512: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6513: my ($startblock,$endblock) =
6514: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6515: if ($startblock && $endblock) {
6516: return 'B';
6517: }
6518: } else {
6519: my ($startblock,$endblock) =
6520: &Apache::loncommon::blockcheck(\%setters,'port');
6521: if ($startblock && $endblock) {
6522: return 'B';
6523: }
6524: }
6525: }
1.765 albertel 6526: if ($result eq 'ok') {
1.766 albertel 6527: return 'F';
1.765 albertel 6528: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6529: return 'A';
1.765 albertel 6530: }
1.766 albertel 6531: return '';
1.765 albertel 6532: }
6533:
6534: sub get_portfolio_access {
1.1172.2.77 raeburn 6535: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6536:
6537: if (!ref($access_hash)) {
6538: my $current_perms = &get_portfile_permissions($udom,$unum);
6539: my %access_controls = &get_access_controls($current_perms,$group,
6540: $file_name);
6541: $access_hash = $access_controls{$file_name};
6542: }
6543:
1.1172.2.77 raeburn 6544: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6545: my $now = time;
6546: if (ref($access_hash) eq 'HASH') {
6547: foreach my $key (keys(%{$access_hash})) {
6548: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6549: if ($start > $now) {
6550: next;
6551: }
6552: if ($end && $end<$now) {
6553: next;
6554: }
6555: if ($scope eq 'public') {
6556: $public = $key;
6557: last;
6558: } elsif ($scope eq 'guest') {
6559: $guest = $key;
6560: } elsif ($scope eq 'domains') {
6561: push(@domains,$key);
6562: } elsif ($scope eq 'users') {
6563: push(@users,$key);
6564: } elsif ($scope eq 'course') {
6565: push(@courses,$key);
6566: } elsif ($scope eq 'group') {
6567: push(@groups,$key);
1.1172.2.77 raeburn 6568: } elsif ($scope eq 'ip') {
6569: push(@ips,$key);
1.765 albertel 6570: }
6571: }
6572: if ($public) {
6573: return 'ok';
1.1172.2.77 raeburn 6574: } elsif (@ips > 0) {
6575: my $allowed;
6576: foreach my $ipkey (@ips) {
6577: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6578: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6579: $allowed = 1;
6580: last;
6581: }
6582: }
6583: }
6584: if ($allowed) {
6585: return 'ok';
6586: }
1.765 albertel 6587: }
6588: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6589: if ($guest) {
6590: return $guest;
6591: }
6592: } else {
6593: if (@domains > 0) {
6594: foreach my $domkey (@domains) {
6595: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6596: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6597: return 'ok';
6598: }
6599: }
6600: }
6601: }
6602: if (@users > 0) {
6603: foreach my $userkey (@users) {
1.865 raeburn 6604: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6605: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6606: if (ref($item) eq 'HASH') {
6607: if (($item->{'uname'} eq $env{'user.name'}) &&
6608: ($item->{'udom'} eq $env{'user.domain'})) {
6609: return 'ok';
6610: }
6611: }
6612: }
6613: }
1.765 albertel 6614: }
6615: }
6616: my %roleshash;
6617: my @courses_and_groups = @courses;
6618: push(@courses_and_groups,@groups);
6619: if (@courses_and_groups > 0) {
6620: my (%allgroups,%allroles);
6621: my ($start,$end,$role,$sec,$group);
6622: foreach my $envkey (%env) {
1.1060 raeburn 6623: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6624: my $cid = $2.'_'.$3;
6625: if ($1 eq 'gr') {
6626: $group = $4;
6627: $allgroups{$cid}{$group} = $env{$envkey};
6628: } else {
6629: if ($4 eq '') {
6630: $sec = 'none';
6631: } else {
6632: $sec = $4;
6633: }
6634: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6635: }
1.811 albertel 6636: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6637: my $cid = $2.'_'.$3;
6638: if ($4 eq '') {
6639: $sec = 'none';
6640: } else {
6641: $sec = $4;
6642: }
6643: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6644: }
6645: }
6646: if (keys(%allroles) == 0) {
6647: return;
6648: }
6649: foreach my $key (@courses_and_groups) {
6650: my %content = %{$$access_hash{$key}};
6651: my $cnum = $content{'number'};
6652: my $cdom = $content{'domain'};
6653: my $cid = $cdom.'_'.$cnum;
6654: if (!exists($allroles{$cid})) {
6655: next;
6656: }
6657: foreach my $role_id (keys(%{$content{'roles'}})) {
6658: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6659: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6660: my @status = @{$content{'roles'}{$role_id}{'access'}};
6661: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6662: foreach my $role (keys(%{$allroles{$cid}})) {
6663: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6664: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6665: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6666: if (grep/^all$/,@sections) {
6667: return 'ok';
6668: } else {
6669: if (grep/^$sec$/,@sections) {
6670: return 'ok';
6671: }
6672: }
6673: }
6674: }
6675: if (keys(%{$allgroups{$cid}}) == 0) {
6676: if (grep/^none$/,@groups) {
6677: return 'ok';
6678: }
6679: } else {
6680: if (grep/^all$/,@groups) {
6681: return 'ok';
6682: }
6683: foreach my $group (keys(%{$allgroups{$cid}})) {
6684: if (grep/^$group$/,@groups) {
6685: return 'ok';
6686: }
6687: }
6688: }
6689: }
6690: }
6691: }
6692: }
6693: }
6694: if ($guest) {
6695: return $guest;
6696: }
6697: }
6698: }
6699: return;
6700: }
6701:
6702: sub course_group_datechecker {
6703: my ($dates,$now,$status) = @_;
6704: my ($start,$end) = split(/\./,$dates);
6705: if (!$start && !$end) {
6706: return 'ok';
6707: }
6708: if (grep/^active$/,@{$status}) {
6709: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6710: return 'ok';
6711: }
6712: }
6713: if (grep/^previous$/,@{$status}) {
6714: if ($end > $now ) {
6715: return 'ok';
6716: }
6717: }
6718: if (grep/^future$/,@{$status}) {
6719: if ($start > $now) {
6720: return 'ok';
6721: }
6722: }
6723: return;
6724: }
6725:
6726: sub parse_portfolio_url {
6727: my ($url) = @_;
6728:
6729: my ($type,$udom,$unum,$group,$file_name);
6730:
1.823 albertel 6731: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6732: $type = 1;
6733: $udom = $1;
6734: $unum = $2;
6735: $file_name = $3;
1.823 albertel 6736: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6737: $type = 2;
6738: $udom = $1;
6739: $unum = $2;
6740: $group = $3;
6741: $file_name = $3.'/'.$4;
6742: }
6743: if (wantarray) {
6744: return ($type,$udom,$unum,$file_name,$group);
6745: }
6746: return $type;
6747: }
6748:
6749: sub is_portfolio_url {
6750: my ($url) = @_;
6751: return scalar(&parse_portfolio_url($url));
6752: }
6753:
1.798 raeburn 6754: sub is_portfolio_file {
6755: my ($file) = @_;
1.820 raeburn 6756: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6757: return 1;
6758: }
6759: return;
6760: }
6761:
1.976 raeburn 6762: sub usertools_access {
1.1084 raeburn 6763: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6764: my ($access,%tools);
6765: if ($context eq '') {
6766: $context = 'tools';
6767: }
6768: if ($context eq 'requestcourses') {
6769: %tools = (
6770: official => 1,
6771: unofficial => 1,
1.1006 raeburn 6772: community => 1,
1.1172.2.37 raeburn 6773: textbook => 1,
1.985 raeburn 6774: );
1.1172.2.9 raeburn 6775: } elsif ($context eq 'requestauthor') {
6776: %tools = (
6777: requestauthor => 1,
6778: );
1.985 raeburn 6779: } else {
6780: %tools = (
6781: aboutme => 1,
6782: blog => 1,
1.1172.2.6 raeburn 6783: webdav => 1,
1.985 raeburn 6784: portfolio => 1,
6785: );
6786: }
1.976 raeburn 6787: return if (!defined($tools{$tool}));
6788:
1.1172.2.35 raeburn 6789: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6790: $udom = $env{'user.domain'};
6791: $uname = $env{'user.name'};
6792: }
6793:
1.978 raeburn 6794: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6795: if ($action ne 'reload') {
1.985 raeburn 6796: if ($context eq 'requestcourses') {
6797: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6798: } elsif ($context eq 'requestauthor') {
6799: return $env{'environment.canrequest.author'};
1.985 raeburn 6800: } else {
6801: return $env{'environment.availabletools.'.$tool};
6802: }
6803: }
1.976 raeburn 6804: }
6805:
1.1172.2.9 raeburn 6806: my ($toolstatus,$inststatus,$envkey);
6807: if ($context eq 'requestauthor') {
6808: $envkey = $context;
6809: } else {
6810: $envkey = $context.'.'.$tool;
6811: }
1.976 raeburn 6812:
1.985 raeburn 6813: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6814: ($action ne 'reload')) {
1.1172.2.9 raeburn 6815: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6816: $inststatus = $env{'environment.inststatus'};
6817: } else {
1.1084 raeburn 6818: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6819: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6820: $inststatus = $userenvref->{'inststatus'};
6821: } else {
1.1172.2.9 raeburn 6822: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6823: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6824: $inststatus = $userenv{'inststatus'};
6825: }
1.976 raeburn 6826: }
6827:
6828: if ($toolstatus ne '') {
6829: if ($toolstatus) {
6830: $access = 1;
6831: } else {
6832: $access = 0;
6833: }
6834: return $access;
6835: }
6836:
1.1084 raeburn 6837: my ($is_adv,%domdef);
6838: if (ref($is_advref) eq 'HASH') {
6839: $is_adv = $is_advref->{'is_adv'};
6840: } else {
6841: $is_adv = &is_advanced_user($udom,$uname);
6842: }
6843: if (ref($domdefref) eq 'HASH') {
6844: %domdef = %{$domdefref};
6845: } else {
6846: %domdef = &get_domain_defaults($udom);
6847: }
1.976 raeburn 6848: if (ref($domdef{$tool}) eq 'HASH') {
6849: if ($is_adv) {
6850: if ($domdef{$tool}{'_LC_adv'} ne '') {
6851: if ($domdef{$tool}{'_LC_adv'}) {
6852: $access = 1;
6853: } else {
6854: $access = 0;
6855: }
6856: return $access;
6857: }
6858: }
6859: if ($inststatus ne '') {
6860: my ($hasaccess,$hasnoaccess);
6861: foreach my $affiliation (split(/:/,$inststatus)) {
6862: if ($domdef{$tool}{$affiliation} ne '') {
6863: if ($domdef{$tool}{$affiliation}) {
6864: $hasaccess = 1;
6865: } else {
6866: $hasnoaccess = 1;
6867: }
6868: }
6869: }
6870: if ($hasaccess || $hasnoaccess) {
6871: if ($hasaccess) {
6872: $access = 1;
6873: } elsif ($hasnoaccess) {
6874: $access = 0;
6875: }
6876: return $access;
6877: }
6878: } else {
6879: if ($domdef{$tool}{'default'} ne '') {
6880: if ($domdef{$tool}{'default'}) {
6881: $access = 1;
6882: } elsif ($domdef{$tool}{'default'} == 0) {
6883: $access = 0;
6884: }
6885: return $access;
6886: }
6887: }
6888: } else {
1.1172.2.6 raeburn 6889: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6890: $access = 1;
6891: } else {
6892: $access = 0;
6893: }
1.976 raeburn 6894: return $access;
6895: }
6896: }
6897:
1.1050 raeburn 6898: sub is_course_owner {
6899: my ($cdom,$cnum,$udom,$uname) = @_;
6900: if (($udom eq '') || ($uname eq '')) {
6901: $udom = $env{'user.domain'};
6902: $uname = $env{'user.name'};
6903: }
6904: unless (($udom eq '') || ($uname eq '')) {
6905: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6906: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6907: return 1;
6908: } else {
6909: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6910: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6911: return 1;
6912: }
6913: }
6914: }
6915: }
6916: return;
6917: }
6918:
1.976 raeburn 6919: sub is_advanced_user {
6920: my ($udom,$uname) = @_;
1.1085 raeburn 6921: if ($udom ne '' && $uname ne '') {
6922: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6923: if (wantarray) {
6924: return ($env{'user.adv'},$env{'user.author'});
6925: } else {
6926: return $env{'user.adv'};
6927: }
1.1085 raeburn 6928: }
6929: }
1.976 raeburn 6930: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6931: my %allroles;
1.1128 raeburn 6932: my ($is_adv,$is_author);
1.976 raeburn 6933: foreach my $role (keys(%roleshash)) {
6934: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6935: my $area = '/'.$tdomain.'/'.$trest;
6936: if ($sec ne '') {
6937: $area .= '/'.$sec;
6938: }
6939: if (($area ne '') && ($trole ne '')) {
6940: my $spec=$trole.'.'.$area;
6941: if ($trole =~ /^cr\//) {
6942: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6943: } elsif ($trole ne 'gr') {
6944: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6945: }
1.1128 raeburn 6946: if ($trole eq 'au') {
6947: $is_author = 1;
6948: }
1.976 raeburn 6949: }
6950: }
6951: foreach my $role (keys(%allroles)) {
6952: last if ($is_adv);
6953: foreach my $item (split(/:/,$allroles{$role})) {
6954: if ($item ne '') {
6955: my ($privilege,$restrictions)=split(/&/,$item);
6956: if ($privilege eq 'adv') {
6957: $is_adv = 1;
6958: last;
6959: }
6960: }
6961: }
6962: }
1.1128 raeburn 6963: if (wantarray) {
6964: return ($is_adv,$is_author);
6965: }
1.976 raeburn 6966: return $is_adv;
6967: }
1.798 raeburn 6968:
1.1035 raeburn 6969: sub check_can_request {
1.1036 raeburn 6970: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6971: my $canreq = 0;
6972: my ($types,$typename) = &Apache::loncommon::course_types();
6973: my @options = ('approval','validate','autolimit');
6974: my $optregex = join('|',@options);
6975: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6976: foreach my $type (@{$types}) {
6977: if (&usertools_access($env{'user.name'},
6978: $env{'user.domain'},
6979: $type,undef,'requestcourses')) {
6980: $canreq ++;
1.1036 raeburn 6981: if (ref($request_domains) eq 'HASH') {
6982: push(@{$request_domains->{$type}},$env{'user.domain'});
6983: }
1.1035 raeburn 6984: if ($dom eq $env{'user.domain'}) {
6985: $can_request->{$type} = 1;
6986: }
6987: }
6988: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6989: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6990: if (@curr > 0) {
1.1036 raeburn 6991: foreach my $item (@curr) {
6992: if (ref($request_domains) eq 'HASH') {
6993: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6994: if ($otherdom ne '') {
6995: if (ref($request_domains->{$type}) eq 'ARRAY') {
6996: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6997: push(@{$request_domains->{$type}},$otherdom);
6998: }
6999: } else {
7000: push(@{$request_domains->{$type}},$otherdom);
7001: }
7002: }
7003: }
7004: }
7005: unless($dom eq $env{'user.domain'}) {
7006: $canreq ++;
1.1035 raeburn 7007: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7008: $can_request->{$type} = 1;
7009: }
7010: }
7011: }
7012: }
7013: }
7014: }
7015: return $canreq;
7016: }
7017:
1.341 www 7018: # ---------------------------------------------- Custom access rule evaluation
7019:
7020: sub customaccess {
7021: my ($priv,$uri)=@_;
1.807 albertel 7022: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7023: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7024: $udom = &LONCAPA::clean_domain($udom);
7025: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7026: my $access=0;
1.800 albertel 7027: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7028: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7029: if ($type eq 'user') {
7030: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7031: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7032: if ($tdom) {
7033: if ($tdom ne $env{'user.domain'}) { next; }
7034: }
1.896 albertel 7035: if ($tuname) {
7036: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7037: }
7038: $access=($effect eq 'allow');
7039: last;
7040: }
7041: } else {
7042: if ($role) {
7043: if ($role ne $urole) { next; }
7044: }
7045: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7046: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7047: if ($tdom) {
7048: if ($tdom ne $udom) { next; }
7049: }
7050: if ($tcrs) {
7051: if ($tcrs ne $ucrs) { next; }
7052: }
7053: if ($tsec) {
7054: if ($tsec ne $usec) { next; }
7055: }
7056: $access=($effect eq 'allow');
7057: last;
7058: }
7059: if ($realm eq '' && $role eq '') {
7060: $access=($effect eq 'allow');
7061: }
1.402 bowersj2 7062: }
1.341 www 7063: }
7064: return $access;
7065: }
7066:
1.103 harris41 7067: # ------------------------------------------------- Check for a user privilege
1.12 www 7068:
7069: sub allowed {
1.1172.2.65 raeburn 7070: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7071: my $ver_orguri=$uri;
1.439 www 7072: $uri=&deversion($uri);
1.152 www 7073: my $orguri=$uri;
1.52 www 7074: $uri=&declutter($uri);
1.809 raeburn 7075:
1.810 raeburn 7076: if ($priv eq 'evb') {
7077: # Evade communication block restrictions for specified role in a course
7078: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7079: return $1;
7080: } else {
7081: return;
7082: }
7083: }
7084:
1.620 albertel 7085: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7086: # Free bre access to adm and meta resources
1.775 albertel 7087: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7088: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7089: && ($priv eq 'bre')) {
1.14 www 7090: return 'F';
1.159 www 7091: }
7092:
1.545 banghart 7093: # Free bre access to user's own portfolio contents
1.714 raeburn 7094: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7095: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7096: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7097: my %setters;
7098: my ($startblock,$endblock) =
7099: &Apache::loncommon::blockcheck(\%setters,'port');
7100: if ($startblock && $endblock) {
7101: return 'B';
7102: } else {
7103: return 'F';
7104: }
1.545 banghart 7105: }
7106:
1.762 raeburn 7107: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7108: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7109: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7110: if (exists($env{'request.course.id'})) {
7111: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7112: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7113: if (($domain eq $cdom) && ($name eq $cnum)) {
7114: my $courseprivid=$env{'request.course.id'};
7115: $courseprivid=~s/\_/\//;
7116: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7117: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7118: return $1;
1.762 raeburn 7119: } else {
7120: if ($env{'request.course.sec'}) {
7121: $courseprivid.='/'.$env{'request.course.sec'};
7122: }
7123: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7124: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7125: return $2;
7126: }
1.714 raeburn 7127: }
7128: }
7129: }
7130: }
7131:
1.159 www 7132: # Free bre to public access
7133:
7134: if ($priv eq 'bre') {
1.238 www 7135: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7136: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7137: return 'F';
7138: }
1.238 www 7139: if ($copyright eq 'priv') {
7140: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7141: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7142: return '';
7143: }
7144: }
7145: if ($copyright eq 'domain') {
7146: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7147: unless (($env{'user.domain'} eq $1) ||
7148: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7149: return '';
7150: }
1.262 matthew 7151: }
1.620 albertel 7152: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7153: # Library role, so allow browsing of resources in this domain.
7154: return 'F';
1.238 www 7155: }
1.341 www 7156: if ($copyright eq 'custom') {
7157: unless (&customaccess($priv,$uri)) { return ''; }
7158: }
1.14 www 7159: }
1.264 matthew 7160: # Domain coordinator is trying to create a course
1.620 albertel 7161: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7162: # uri is the requested domain in this case.
7163: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7164: # a role of dc for the domain in question.
1.620 albertel 7165: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7166: }
1.29 www 7167:
1.52 www 7168: my $thisallowed='';
7169: my $statecond=0;
7170: my $courseprivid='';
7171:
1.1039 raeburn 7172: my $ownaccess;
1.1043 raeburn 7173: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7174: if (($priv eq 'bro') && ($env{'user.author'})) {
7175: if ($uri eq '') {
7176: $ownaccess = 1;
7177: } else {
7178: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7179: my $udom = $env{'user.domain'};
7180: my $uname = $env{'user.name'};
7181: if ($uri =~ m{^\Q$udom\E/?$}) {
7182: $ownaccess = 1;
1.1040 raeburn 7183: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7184: unless ($uri =~ m{\.\./}) {
7185: $ownaccess = 1;
7186: }
7187: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7188: my $now = time;
7189: if ($uri =~ m{^([^/]+)/?$}) {
7190: my $adom = $1;
7191: foreach my $key (keys(%env)) {
1.1042 raeburn 7192: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7193: my ($start,$end) = split('.',$env{$key});
7194: if (($now >= $start) && (!$end || $end < $now)) {
7195: $ownaccess = 1;
7196: last;
7197: }
7198: }
7199: }
7200: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7201: my $adom = $1;
7202: my $aname = $2;
1.1042 raeburn 7203: foreach my $role ('ca','aa') {
7204: if ($env{"user.role.$role./$adom/$aname"}) {
7205: my ($start,$end) =
7206: split('.',$env{"user.role.$role./$adom/$aname"});
7207: if (($now >= $start) && (!$end || $end < $now)) {
7208: $ownaccess = 1;
7209: last;
7210: }
1.1039 raeburn 7211: }
7212: }
7213: }
7214: }
7215: }
7216: }
7217: }
7218:
1.52 www 7219: # Course
7220:
1.620 albertel 7221: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7222: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7223: $thisallowed.=$1;
7224: }
1.52 www 7225: }
1.29 www 7226:
1.52 www 7227: # Domain
7228:
1.620 albertel 7229: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7230: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7231: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7232: $thisallowed.=$1;
7233: }
1.12 www 7234: }
1.52 www 7235:
1.1141 raeburn 7236: # User who is not author or co-author might still be able to edit
7237: # resource of an author in the domain (e.g., if Domain Coordinator).
7238: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7239: (&allowed('mdc',$env{'request.course.id'}))) {
7240: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7241: $thisallowed.=$1;
7242: }
7243: }
7244:
1.52 www 7245: # Course: uri itself is a course
1.66 www 7246: my $courseuri=$uri;
7247: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7248: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7249:
1.620 albertel 7250: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7251: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7252: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7253: $thisallowed.=$1;
7254: }
1.12 www 7255: }
1.29 www 7256:
1.665 albertel 7257: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7258: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7259: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7260: $thisallowed='';
1.671 raeburn 7261: my ($match)=&is_on_map($uri);
7262: if ($match) {
7263: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7264: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7265: my $value = $1;
7266: if ($noblockcheck) {
7267: $thisallowed.=$value;
1.1162 raeburn 7268: } else {
1.1172.2.65 raeburn 7269: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7270: if (@blockers > 0) {
7271: $thisallowed = 'B';
7272: } else {
7273: $thisallowed.=$value;
7274: }
1.1162 raeburn 7275: }
1.671 raeburn 7276: }
7277: } else {
1.705 albertel 7278: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7279: if ($refuri) {
7280: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7281: $thisallowed='F';
1.671 raeburn 7282: } else {
7283: $refuri=&declutter($refuri);
7284: my ($match) = &is_on_map($refuri);
7285: if ($match) {
1.1172.2.65 raeburn 7286: if ($noblockcheck) {
1.1162 raeburn 7287: $thisallowed='F';
1.1172.2.65 raeburn 7288: } else {
7289: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7290: if (@blockers > 0) {
7291: $thisallowed = 'B';
7292: } else {
7293: $thisallowed='F';
7294: }
1.1162 raeburn 7295: }
1.671 raeburn 7296: }
1.669 raeburn 7297: }
1.671 raeburn 7298: }
7299: }
1.314 www 7300: }
1.492 albertel 7301:
1.766 albertel 7302: if ($priv eq 'bre'
7303: && $thisallowed ne 'F'
7304: && $thisallowed ne '2'
7305: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7306: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7307: }
7308:
1.52 www 7309: # Full access at system, domain or course-wide level? Exit.
1.29 www 7310: if ($thisallowed=~/F/) {
7311: return 'F';
7312: }
7313:
1.52 www 7314: # If this is generating or modifying users, exit with special codes
1.29 www 7315:
1.643 www 7316: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7317: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7318: my ($audom,$auname)=split('/',$uri);
1.643 www 7319: # no author name given, so this just checks on the general right to make a co-author in this domain
7320: unless ($auname) { return $thisallowed; }
7321: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7322: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7323: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7324: ($audom ne $env{'request.role.domain'}))) { return ''; }
7325: }
1.52 www 7326: return $thisallowed;
7327: }
7328: #
1.103 harris41 7329: # Gathered so far: system, domain and course wide privileges
1.52 www 7330: #
7331: # Course: See if uri or referer is an individual resource that is part of
7332: # the course
7333:
1.620 albertel 7334: if ($env{'request.course.id'}) {
1.232 www 7335:
1.620 albertel 7336: $courseprivid=$env{'request.course.id'};
7337: if ($env{'request.course.sec'}) {
7338: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7339: }
7340: $courseprivid=~s/\_/\//;
7341: my $checkreferer=1;
1.232 www 7342: my ($match,$cond)=&is_on_map($uri);
7343: if ($match) {
7344: $statecond=$cond;
1.620 albertel 7345: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7346: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7347: my $value = $1;
7348: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7349: if ($noblockcheck) {
1.1162 raeburn 7350: $thisallowed.=$value;
1.1172.2.65 raeburn 7351: } else {
7352: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7353: if (@blockers > 0) {
7354: $thisallowed = 'B';
7355: } else {
7356: $thisallowed.=$value;
7357: }
1.1162 raeburn 7358: }
7359: } else {
7360: $thisallowed.=$value;
7361: }
1.52 www 7362: $checkreferer=0;
7363: }
1.29 www 7364: }
1.83 www 7365:
1.148 www 7366: if ($checkreferer) {
1.620 albertel 7367: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7368: unless ($refuri) {
1.800 albertel 7369: foreach my $key (keys(%env)) {
7370: if ($key=~/^httpref\..*\*/) {
7371: my $pattern=$key;
1.156 www 7372: $pattern=~s/^httpref\.\/res\///;
1.148 www 7373: $pattern=~s/\*/\[\^\/\]\+/g;
7374: $pattern=~s/\//\\\//g;
1.152 www 7375: if ($orguri=~/$pattern/) {
1.800 albertel 7376: $refuri=$env{$key};
1.148 www 7377: }
7378: }
1.191 harris41 7379: }
1.148 www 7380: }
1.232 www 7381:
1.148 www 7382: if ($refuri) {
1.152 www 7383: $refuri=&declutter($refuri);
1.232 www 7384: my ($match,$cond)=&is_on_map($refuri);
7385: if ($match) {
7386: my $refstatecond=$cond;
1.620 albertel 7387: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7388: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7389: my $value = $1;
7390: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7391: if ($noblockcheck) {
1.1162 raeburn 7392: $thisallowed.=$value;
1.1172.2.65 raeburn 7393: } else {
7394: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7395: if (@blockers > 0) {
7396: $thisallowed = 'B';
7397: } else {
7398: $thisallowed.=$value;
7399: }
1.1162 raeburn 7400: }
7401: } else {
7402: $thisallowed.=$value;
7403: }
1.53 www 7404: $uri=$refuri;
7405: $statecond=$refstatecond;
1.52 www 7406: }
7407: }
1.148 www 7408: }
1.29 www 7409: }
1.52 www 7410: }
1.29 www 7411:
1.52 www 7412: #
1.103 harris41 7413: # Gathered now: all privileges that could apply, and condition number
1.52 www 7414: #
7415: #
7416: # Full or no access?
7417: #
1.29 www 7418:
1.52 www 7419: if ($thisallowed=~/F/) {
7420: return 'F';
7421: }
1.29 www 7422:
1.52 www 7423: unless ($thisallowed) {
7424: return '';
7425: }
1.29 www 7426:
1.52 www 7427: # Restrictions exist, deal with them
7428: #
7429: # C:according to course preferences
7430: # R:according to resource settings
7431: # L:unless locked
7432: # X:according to user session state
7433: #
7434:
7435: # Possibly locked functionality, check all courses
1.54 www 7436: # Locks might take effect only after 10 minutes cache expiration for other
7437: # courses, and 2 minutes for current course
1.52 www 7438:
7439: my $envkey;
7440: if ($thisallowed=~/L/) {
1.1000 raeburn 7441: foreach $envkey (keys(%env)) {
1.54 www 7442: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7443: my $courseid=$2;
7444: my $roleid=$1.'.'.$2;
1.92 www 7445: $courseid=~s/^\///;
1.54 www 7446: my $expiretime=600;
1.620 albertel 7447: if ($env{'request.role'} eq $roleid) {
1.54 www 7448: $expiretime=120;
7449: }
7450: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7451: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7452: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7453: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7454: }
1.620 albertel 7455: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7456: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7457: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7458: &log($env{'user.domain'},$env{'user.name'},
7459: $env{'user.home'},
1.57 www 7460: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7461: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7462: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7463: return '';
7464: }
7465: }
1.620 albertel 7466: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7467: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7468: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7469: &log($env{'user.domain'},$env{'user.name'},
7470: $env{'user.home'},
1.57 www 7471: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7472: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7473: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7474: return '';
7475: }
7476: }
7477: }
1.29 www 7478: }
1.52 www 7479: }
7480:
7481: #
7482: # Rest of the restrictions depend on selected course
7483: #
7484:
1.620 albertel 7485: unless ($env{'request.course.id'}) {
1.766 albertel 7486: if ($thisallowed eq 'A') {
7487: return 'A';
1.814 raeburn 7488: } elsif ($thisallowed eq 'B') {
7489: return 'B';
1.766 albertel 7490: } else {
7491: return '1';
7492: }
1.52 www 7493: }
1.29 www 7494:
1.52 www 7495: #
7496: # Now user is definitely in a course
7497: #
1.53 www 7498:
7499:
7500: # Course preferences
7501:
7502: if ($thisallowed=~/C/) {
1.620 albertel 7503: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7504: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7505: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7506: =~/\Q$rolecode\E/) {
1.1103 raeburn 7507: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7508: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7509: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7510: $env{'request.course.id'});
7511: }
1.237 www 7512: return '';
7513: }
7514:
1.620 albertel 7515: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7516: =~/\Q$unamedom\E/) {
1.1103 raeburn 7517: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7518: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7519: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7520: $env{'request.course.id'});
7521: }
1.54 www 7522: return '';
7523: }
1.53 www 7524: }
7525:
7526: # Resource preferences
7527:
7528: if ($thisallowed=~/R/) {
1.620 albertel 7529: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7530: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7531: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7532: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7533: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7534: }
7535: return '';
1.54 www 7536: }
1.53 www 7537: }
1.30 www 7538:
1.246 www 7539: # Restricted by state or randomout?
1.30 www 7540:
1.52 www 7541: if ($thisallowed=~/X/) {
1.620 albertel 7542: if ($env{'acc.randomout'}) {
1.579 albertel 7543: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7544: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7545: return '';
7546: }
1.247 www 7547: }
7548: if (&condval($statecond)) {
1.52 www 7549: return '2';
7550: } else {
7551: return '';
7552: }
7553: }
1.30 www 7554:
1.766 albertel 7555: if ($thisallowed eq 'A') {
7556: return 'A';
1.814 raeburn 7557: } elsif ($thisallowed eq 'B') {
7558: return 'B';
1.766 albertel 7559: }
1.52 www 7560: return 'F';
1.232 www 7561: }
1.1162 raeburn 7562:
1.1172.2.13 raeburn 7563: # ------------------------------------------- Check construction space access
7564:
7565: sub constructaccess {
7566: my ($url,$setpriv)=@_;
7567:
7568: # We do not allow editing of previous versions of files
7569: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7570:
7571: # Get username and domain from URL
7572: my ($ownername,$ownerdomain,$ownerhome);
7573:
7574: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7575: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7576:
7577: # The URL does not really point to any authorspace, forget it
7578: unless (($ownername) && ($ownerdomain)) { return ''; }
7579:
7580: # Now we need to see if the user has access to the authorspace of
7581: # $ownername at $ownerdomain
7582:
7583: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7584: # Real author for this?
7585: $ownerhome = $env{'user.home'};
7586: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7587: return ($ownername,$ownerdomain,$ownerhome);
7588: }
7589: } else {
7590: # Co-author for this?
7591: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7592: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7593: $ownerhome = &homeserver($ownername,$ownerdomain);
7594: return ($ownername,$ownerdomain,$ownerhome);
7595: }
7596: }
7597:
7598: # We don't have any access right now. If we are not possibly going to do anything about this,
7599: # we might as well leave
7600: unless ($setpriv) { return ''; }
7601:
7602: # Backdoor access?
7603: my $allowed=&allowed('eco',$ownerdomain);
7604: # Nope
7605: unless ($allowed) { return ''; }
7606: # Looks like we may have access, but could be locked by the owner of the construction space
7607: if ($allowed eq 'U') {
7608: my %blocked=&get('environment',['domcoord.author'],
7609: $ownerdomain,$ownername);
7610: # Is blocked by owner
7611: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7612: }
7613: if (($allowed eq 'F') || ($allowed eq 'U')) {
7614: # Grant temporary access
7615: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7616: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7617: if (!$update) { $update = $then; }
7618: my $refresh=$env{'user.refresh.time'};
7619: if (!$refresh) { $refresh = $update; }
7620: my $now = time;
7621: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7622: $now,'ca','constructaccess');
7623: $ownerhome = &homeserver($ownername,$ownerdomain);
7624: return($ownername,$ownerdomain,$ownerhome);
7625: }
7626: # No business here
7627: return '';
7628: }
7629:
1.1172.2.66 raeburn 7630: # ----------------------------------------------------------- Content Blocking
7631:
7632: {
7633: # Caches for faster Course Contents display where content blocking
7634: # is in operation (i.e., interval param set) for timed quiz.
7635: #
7636: # User for whom data are being temporarily cached.
7637: my $cacheduser='';
7638: # Cached blockers for this user (a hash of blocking items).
7639: my %cachedblockers=();
7640: # When the data were last cached.
7641: my $cachedlast='';
7642:
7643: sub load_all_blockers {
7644: my ($uname,$udom,$blocks)=@_;
7645: if (($uname ne '') && ($udom ne '')) {
7646: if (($cacheduser eq $uname.':'.$udom) &&
7647: (abs($cachedlast-time)<5)) {
7648: return;
7649: }
7650: }
7651: $cachedlast=time;
7652: $cacheduser=$uname.':'.$udom;
7653: %cachedblockers = &get_commblock_resources($blocks);
7654: }
7655:
1.1162 raeburn 7656: sub get_comm_blocks {
7657: my ($cdom,$cnum) = @_;
7658: if ($cdom eq '' || $cnum eq '') {
7659: return unless ($env{'request.course.id'});
7660: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7661: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7662: }
7663: my %commblocks;
7664: my $hashid=$cdom.'_'.$cnum;
7665: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7666: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7667: %commblocks = %{$blocksref};
7668: } else {
7669: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7670: my $cachetime = 600;
7671: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7672: }
7673: return %commblocks;
7674: }
7675:
1.1172.2.66 raeburn 7676: sub get_commblock_resources {
7677: my ($blocks) = @_;
7678: my %blockers = ();
7679: return %blockers unless ($env{'request.course.id'});
7680: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7681: my %commblocks;
7682: if (ref($blocks) eq 'HASH') {
7683: %commblocks = %{$blocks};
7684: } else {
7685: %commblocks = &get_comm_blocks();
7686: }
1.1172.2.66 raeburn 7687: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7688: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7689: return %blockers unless (ref($navmap));
7690: my $now = time;
1.1162 raeburn 7691: foreach my $block (keys(%commblocks)) {
7692: if ($block =~ /^(\d+)____(\d+)$/) {
7693: my ($start,$end) = ($1,$2);
7694: if ($start <= $now && $end >= $now) {
7695: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7696: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7697: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7698: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7699: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7700: }
7701: }
7702: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7703: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7704: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7705: }
7706: }
7707: }
7708: }
7709: }
7710: } elsif ($block =~ /^firstaccess____(.+)$/) {
7711: my $item = $1;
1.1163 raeburn 7712: my @to_test;
1.1162 raeburn 7713: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7714: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7715: my @interval;
7716: my $type = 'map';
7717: if ($item eq 'course') {
7718: $type = 'course';
7719: @interval=&EXT("resource.0.interval");
7720: } else {
7721: if ($item =~ /___\d+___/) {
7722: $type = 'resource';
7723: @interval=&EXT("resource.0.interval",$item);
7724: if (ref($navmap)) {
7725: my $res = $navmap->getBySymb($item);
7726: push(@to_test,$res);
7727: }
1.1162 raeburn 7728: } else {
1.1172.2.66 raeburn 7729: my $mapsymb = &symbread($item,1);
7730: if ($mapsymb) {
7731: if (ref($navmap)) {
7732: my $mapres = $navmap->getBySymb($mapsymb);
7733: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7734: foreach my $res (@to_test) {
7735: my $symb = $res->symb();
7736: next if ($symb eq $mapsymb);
7737: if ($symb ne '') {
7738: @interval=&EXT("resource.0.interval",$symb);
7739: if ($interval[1] eq 'map') {
7740: last;
1.1162 raeburn 7741: }
7742: }
7743: }
7744: }
7745: }
7746: }
1.1172.2.66 raeburn 7747: }
7748: if ($interval[0] =~ /^\d+$/) {
7749: my $first_access;
7750: if ($type eq 'resource') {
7751: $first_access=&get_first_access($interval[1],$item);
7752: } elsif ($type eq 'map') {
7753: $first_access=&get_first_access($interval[1],undef,$item);
7754: } else {
7755: $first_access=&get_first_access($interval[1]);
7756: }
7757: if ($first_access) {
7758: my $timesup = $first_access+$interval[0];
7759: if ($timesup > $now) {
7760: my $activeblock;
7761: foreach my $res (@to_test) {
7762: if ($res->answerable()) {
7763: $activeblock = 1;
7764: last;
7765: }
7766: }
7767: if ($activeblock) {
7768: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7769: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7770: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7771: }
7772: }
7773: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7774: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7775: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7776: }
1.1162 raeburn 7777: }
7778: }
7779: }
7780: }
7781: }
7782: }
7783: }
7784: }
7785: }
1.1172.2.66 raeburn 7786: return %blockers;
1.1162 raeburn 7787: }
7788:
1.1172.2.66 raeburn 7789: sub has_comm_blocking {
7790: my ($priv,$symb,$uri,$blocks) = @_;
7791: my @blockers;
7792: return unless ($env{'request.course.id'});
7793: return unless ($priv eq 'bre');
7794: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7795: return if ($env{'request.state'} eq 'construct');
7796: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7797: return unless (keys(%cachedblockers) > 0);
7798: my (%possibles,@symbs);
7799: if (!$symb) {
7800: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7801: }
1.1172.2.66 raeburn 7802: if ($symb) {
7803: @symbs = ($symb);
7804: } elsif (keys(%possibles)) {
7805: @symbs = keys(%possibles);
7806: }
7807: my $noblock;
7808: foreach my $symb (@symbs) {
7809: last if ($noblock);
7810: my ($map,$resid,$resurl)=&decode_symb($symb);
7811: foreach my $block (keys(%cachedblockers)) {
7812: if ($block =~ /^firstaccess____(.+)$/) {
7813: my $item = $1;
7814: if (($item eq $map) || ($item eq $symb)) {
7815: $noblock = 1;
7816: last;
7817: }
1.1162 raeburn 7818: }
1.1172.2.66 raeburn 7819: if (ref($cachedblockers{$block}) eq 'HASH') {
7820: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7821: if ($cachedblockers{$block}{'resources'}{$symb}) {
7822: unless (grep(/^\Q$block\E$/,@blockers)) {
7823: push(@blockers,$block);
7824: }
7825: }
7826: }
7827: }
7828: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7829: if ($cachedblockers{$block}{'maps'}{$map}) {
7830: unless (grep(/^\Q$block\E$/,@blockers)) {
7831: push(@blockers,$block);
7832: }
7833: }
1.1162 raeburn 7834: }
7835: }
7836: }
1.1172.2.66 raeburn 7837: return if ($noblock);
7838: return @blockers;
7839: }
1.1162 raeburn 7840: }
7841:
1.1172.2.66 raeburn 7842: # -------------------------------- Deversion and split uri into path an filename
7843:
1.1133 foxr 7844: #
1.1172.2.66 raeburn 7845: # Removes the version from a URI and
1.1133 foxr 7846: # splits it in to its filename and path to the filename.
7847: # Seems like File::Basename could have done this more clearly.
7848: # Parameters:
7849: # $uri - input URI
7850: # Returns:
7851: # Two element list consisting of
7852: # $pathname - the URI up to and excluding the trailing /
7853: # $filename - The part of the URI following the last /
7854: # NOTE:
7855: # Another realization of this is simply:
7856: # use File::Basename;
7857: # ...
7858: # $uri = shift;
7859: # $filename = basename($uri);
7860: # $path = dirname($uri);
7861: # return ($filename, $path);
7862: #
7863: # The implementation below is probably faster however.
7864: #
1.710 albertel 7865: sub split_uri_for_cond {
7866: my $uri=&deversion(&declutter(shift));
7867: my @uriparts=split(/\//,$uri);
7868: my $filename=pop(@uriparts);
7869: my $pathname=join('/',@uriparts);
7870: return ($pathname,$filename);
7871: }
1.232 www 7872: # --------------------------------------------------- Is a resource on the map?
7873:
7874: sub is_on_map {
1.710 albertel 7875: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7876: #Trying to find the conditional for the file
1.620 albertel 7877: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7878: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7879: if ($match) {
1.289 bowersj2 7880: return (1,$1);
7881: } else {
1.434 www 7882: return (0,0);
1.289 bowersj2 7883: }
1.12 www 7884: }
7885:
1.427 www 7886: # --------------------------------------------------------- Get symb from alias
7887:
7888: sub get_symb_from_alias {
7889: my $symb=shift;
7890: my ($map,$resid,$url)=&decode_symb($symb);
7891: # Already is a symb
7892: if ($url) { return $symb; }
7893: # Must be an alias
7894: my $aliassymb='';
7895: my %bighash;
1.620 albertel 7896: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7897: &GDBM_READER(),0640)) {
7898: my $rid=$bighash{'mapalias_'.$symb};
7899: if ($rid) {
7900: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7901: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7902: $resid,$bighash{'src_'.$rid});
1.427 www 7903: }
7904: untie %bighash;
7905: }
7906: return $aliassymb;
7907: }
7908:
1.12 www 7909: # ----------------------------------------------------------------- Define Role
7910:
7911: sub definerole {
7912: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 7913: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7914: foreach my $role (split(':',$sysrole)) {
7915: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7916: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7917: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7918: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7919: return "refused:s:$crole&$cqual";
7920: }
7921: }
1.191 harris41 7922: }
1.800 albertel 7923: foreach my $role (split(':',$domrole)) {
7924: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7925: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7926: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7927: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7928: return "refused:d:$crole&$cqual";
7929: }
7930: }
1.191 harris41 7931: }
1.800 albertel 7932: foreach my $role (split(':',$courole)) {
7933: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7934: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7935: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7936: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7937: return "refused:c:$crole&$cqual";
7938: }
7939: }
1.191 harris41 7940: }
1.1172.2.84 raeburn 7941: my $uhome;
7942: if (($uname ne '') && ($udom ne '')) {
7943: $uhome = &homeserver($uname,$udom);
7944: return $uhome if ($uhome eq 'no_host');
7945: } else {
7946: $uname = $env{'user.name'};
7947: $udom = $env{'user.domain'};
7948: $uhome = $env{'user.home'};
7949: }
1.620 albertel 7950: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 7951: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7952: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 7953: return reply($command,$uhome);
1.12 www 7954: } else {
7955: return 'refused';
7956: }
1.105 harris41 7957: }
7958:
7959: # ---------------- Make a metadata query against the network of library servers
7960:
7961: sub metadata_query {
1.1172.2.33 raeburn 7962: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7963: my %rhash;
1.845 albertel 7964: my %libserv = &all_library();
1.244 matthew 7965: my @server_list = (defined($server_array) ? @$server_array
7966: : keys(%libserv) );
7967: for my $server (@server_list) {
1.1172.2.33 raeburn 7968: my $domains = '';
7969: if (ref($domains_hash) eq 'HASH') {
7970: $domains = $domains_hash->{$server};
7971: }
1.118 harris41 7972: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7973: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7974: $rhash{$server}=$reply;
7975: }
7976: else {
7977: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7978: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7979: $server);
7980: $rhash{$server}=$reply;
7981: }
1.112 harris41 7982: }
1.118 harris41 7983: return \%rhash;
1.240 www 7984: }
7985:
7986: # ----------------------------------------- Send log queries and wait for reply
7987:
7988: sub log_query {
7989: my ($uname,$udom,$query,%filters)=@_;
7990: my $uhome=&homeserver($uname,$udom);
7991: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7992: my $uhost=&hostname($uhome);
1.800 albertel 7993: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7994: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7995: $uhome);
1.479 albertel 7996: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7997: return get_query_reply($queryid);
7998: }
7999:
1.818 raeburn 8000: # -------------------------- Update MySQL table for portfolio file
8001:
8002: sub update_portfolio_table {
1.821 raeburn 8003: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8004: if ($group ne '') {
8005: $file_name =~s /^\Q$group\E//;
8006: }
1.818 raeburn 8007: my $homeserver = &homeserver($uname,$udom);
8008: my $queryid=
1.821 raeburn 8009: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8010: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8011: my $reply = &get_query_reply($queryid);
8012: return $reply;
8013: }
8014:
1.899 raeburn 8015: # -------------------------- Update MySQL allusers table
8016:
8017: sub update_allusers_table {
8018: my ($uname,$udom,$names) = @_;
8019: my $homeserver = &homeserver($uname,$udom);
8020: my $queryid=
8021: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8022: 'lastname='.&escape($names->{'lastname'}).'%%'.
8023: 'firstname='.&escape($names->{'firstname'}).'%%'.
8024: 'middlename='.&escape($names->{'middlename'}).'%%'.
8025: 'generation='.&escape($names->{'generation'}).'%%'.
8026: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8027: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8028: return;
1.899 raeburn 8029: }
8030:
1.508 raeburn 8031: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8032:
8033: sub fetch_enrollment_query {
1.511 raeburn 8034: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8035: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8036: my $maxtries = 1;
1.508 raeburn 8037: if ($context eq 'automated') {
8038: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8039: $sleep = 2;
8040: $loopmax = 100;
1.547 raeburn 8041: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8042: } else {
8043: $homeserver = &homeserver($cnum,$dom);
8044: }
1.838 albertel 8045: my $host=&hostname($homeserver);
1.506 raeburn 8046: my $cmd = '';
1.1000 raeburn 8047: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8048: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8049: }
8050: $cmd =~ s/%%$//;
8051: $cmd = &escape($cmd);
8052: my $query = 'fetchenrollment';
1.620 albertel 8053: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8054: unless ($queryid=~/^\Q$host\E\_/) {
8055: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8056: return 'error: '.$queryid;
8057: }
1.1172.2.79 raeburn 8058: my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547 raeburn 8059: my $tries = 1;
8060: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8061: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8062: $tries ++;
8063: }
1.526 raeburn 8064: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8065: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8066: } else {
1.901 albertel 8067: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8068: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8069: foreach my $line (@responses) {
8070: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8071: $$replyref{$key} = $value;
8072: }
8073: } else {
1.1117 foxr 8074: my $pathname = LONCAPA::tempdir();
1.800 albertel 8075: foreach my $line (@responses) {
8076: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8077: $$replyref{$key} = $value;
8078: if ($value > 0) {
1.800 albertel 8079: foreach my $item (@{$$affiliatesref{$key}}) {
8080: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8081: my $destname = $pathname.'/'.$filename;
8082: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8083: if ($xml_classlist =~ /^error/) {
8084: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8085: } else {
1.506 raeburn 8086: if ( open(FILE,">$destname") ) {
8087: print FILE &unescape($xml_classlist);
8088: close(FILE);
1.526 raeburn 8089: } else {
8090: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8091: }
8092: }
8093: }
8094: }
8095: }
8096: }
8097: return 'ok';
8098: }
8099: return 'error';
8100: }
8101:
1.242 www 8102: sub get_query_reply {
1.1172.2.79 raeburn 8103: my ($queryid,$sleep,$loopmax) = @_;
8104: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8105: $sleep = 0.2;
8106: }
8107: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8108: $loopmax = 100;
8109: }
1.1117 foxr 8110: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8111: my $reply='';
1.1172.2.79 raeburn 8112: for (1..$loopmax) {
8113: sleep($sleep);
1.240 www 8114: if (-e $replyfile.'.end') {
1.448 albertel 8115: if (open(my $fh,$replyfile)) {
1.904 albertel 8116: $reply = join('',<$fh>);
8117: close($fh);
1.240 www 8118: } else { return 'error: reply_file_error'; }
1.242 www 8119: return &unescape($reply);
8120: }
1.240 www 8121: }
1.242 www 8122: return 'timeout:'.$queryid;
1.240 www 8123: }
8124:
8125: sub courselog_query {
1.241 www 8126: #
8127: # possible filters:
8128: # url: url or symb
8129: # username
8130: # domain
8131: # action: view, submit, grade
8132: # start: timestamp
8133: # end: timestamp
8134: #
1.240 www 8135: my (%filters)=@_;
1.620 albertel 8136: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8137: if ($filters{'url'}) {
8138: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8139: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8140: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8141: }
1.620 albertel 8142: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8143: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8144: return &log_query($cname,$cdom,'courselog',%filters);
8145: }
8146:
8147: sub userlog_query {
1.858 raeburn 8148: #
8149: # possible filters:
8150: # action: log check role
8151: # start: timestamp
8152: # end: timestamp
8153: #
1.240 www 8154: my ($uname,$udom,%filters)=@_;
8155: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8156: }
8157:
1.506 raeburn 8158: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8159:
8160: sub auto_run {
1.508 raeburn 8161: my ($cnum,$cdom) = @_;
1.876 raeburn 8162: my $response = 0;
8163: my $settings;
8164: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8165: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8166: $settings = $domconfig{'autoenroll'};
8167: if ($settings->{'run'} eq '1') {
8168: $response = 1;
8169: }
8170: } else {
1.934 raeburn 8171: my $homeserver;
8172: if (&is_course($cdom,$cnum)) {
8173: $homeserver = &homeserver($cnum,$cdom);
8174: } else {
8175: $homeserver = &domain($cdom,'primary');
8176: }
8177: if ($homeserver ne 'no_host') {
8178: $response = &reply('autorun:'.$cdom,$homeserver);
8179: }
1.876 raeburn 8180: }
1.506 raeburn 8181: return $response;
8182: }
1.776 albertel 8183:
1.506 raeburn 8184: sub auto_get_sections {
1.508 raeburn 8185: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8186: my $homeserver;
8187: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8188: $homeserver = &homeserver($cnum,$cdom);
8189: }
8190: if (!defined($homeserver)) {
8191: if ($cdom =~ /^$match_domain$/) {
8192: $homeserver = &domain($cdom,'primary');
8193: }
8194: }
8195: my @secs;
8196: if (defined($homeserver)) {
8197: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8198: unless ($response eq 'refused') {
8199: @secs = split(/:/,$response);
8200: }
1.506 raeburn 8201: }
8202: return @secs;
8203: }
1.776 albertel 8204:
1.506 raeburn 8205: sub auto_new_course {
1.1099 raeburn 8206: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8207: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8208: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8209: return $response;
8210: }
1.776 albertel 8211:
1.506 raeburn 8212: sub auto_validate_courseID {
1.508 raeburn 8213: my ($cnum,$cdom,$inst_course_id) = @_;
8214: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8215: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8216: return $response;
8217: }
1.776 albertel 8218:
1.1007 raeburn 8219: sub auto_validate_instcode {
1.1020 raeburn 8220: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8221: my ($homeserver,$response);
8222: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8223: $homeserver = &homeserver($cnum,$cdom);
8224: }
8225: if (!defined($homeserver)) {
8226: if ($cdom =~ /^$match_domain$/) {
8227: $homeserver = &domain($cdom,'primary');
8228: }
8229: }
1.1065 raeburn 8230: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8231: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8232: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8233: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8234: }
8235:
1.506 raeburn 8236: sub auto_create_password {
1.873 raeburn 8237: my ($cnum,$cdom,$authparam,$udom) = @_;
8238: my ($homeserver,$response);
1.506 raeburn 8239: my $create_passwd = 0;
8240: my $authchk = '';
1.873 raeburn 8241: if ($udom =~ /^$match_domain$/) {
8242: $homeserver = &domain($udom,'primary');
8243: }
8244: if ($homeserver eq '') {
8245: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8246: $homeserver = &homeserver($cnum,$cdom);
8247: }
8248: }
8249: if ($homeserver eq '') {
8250: $authchk = 'nodomain';
1.506 raeburn 8251: } else {
1.873 raeburn 8252: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8253: if ($response eq 'refused') {
8254: $authchk = 'refused';
8255: } else {
1.901 albertel 8256: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8257: }
1.506 raeburn 8258: }
8259: return ($authparam,$create_passwd,$authchk);
8260: }
8261:
1.706 raeburn 8262: sub auto_photo_permission {
8263: my ($cnum,$cdom,$students) = @_;
8264: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8265: my ($outcome,$perm_reqd,$conditions) =
8266: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8267: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8268: return (undef,undef);
8269: }
1.706 raeburn 8270: return ($outcome,$perm_reqd,$conditions);
8271: }
8272:
8273: sub auto_checkphotos {
8274: my ($uname,$udom,$pid) = @_;
8275: my $homeserver = &homeserver($uname,$udom);
8276: my ($result,$resulttype);
8277: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8278: &escape($uname).':'.&escape($pid),
8279: $homeserver));
1.709 albertel 8280: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8281: return (undef,undef);
8282: }
1.706 raeburn 8283: if ($outcome) {
8284: ($result,$resulttype) = split(/:/,$outcome);
8285: }
8286: return ($result,$resulttype);
8287: }
8288:
8289: sub auto_photochoice {
8290: my ($cnum,$cdom) = @_;
8291: my $homeserver = &homeserver($cnum,$cdom);
8292: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8293: &escape($cdom),
8294: $homeserver)));
1.709 albertel 8295: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8296: return (undef,undef);
8297: }
1.706 raeburn 8298: return ($update,$comment);
8299: }
8300:
8301: sub auto_photoupdate {
8302: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8303: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8304: my $host=&hostname($homeserver);
1.706 raeburn 8305: my $cmd = '';
8306: my $maxtries = 1;
1.800 albertel 8307: foreach my $affiliate (keys(%{$affiliatesref})) {
8308: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8309: }
8310: $cmd =~ s/%%$//;
8311: $cmd = &escape($cmd);
8312: my $query = 'institutionalphotos';
8313: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8314: unless ($queryid=~/^\Q$host\E\_/) {
8315: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8316: return 'error: '.$queryid;
8317: }
8318: my $reply = &get_query_reply($queryid);
8319: my $tries = 1;
8320: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8321: $reply = &get_query_reply($queryid);
8322: $tries ++;
8323: }
8324: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8325: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8326: } else {
8327: my @responses = split(/:/,$reply);
8328: my $outcome = shift(@responses);
8329: foreach my $item (@responses) {
8330: my ($key,$value) = split(/=/,$item);
8331: $$photo{$key} = $value;
8332: }
8333: return $outcome;
8334: }
8335: return 'error';
8336: }
8337:
1.521 raeburn 8338: sub auto_instcode_format {
1.793 albertel 8339: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8340: $cat_order) = @_;
1.521 raeburn 8341: my $courses = '';
1.772 raeburn 8342: my @homeservers;
1.521 raeburn 8343: if ($caller eq 'global') {
1.841 albertel 8344: my %servers = &get_servers($codedom,'library');
8345: foreach my $tryserver (keys(%servers)) {
8346: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8347: push(@homeservers,$tryserver);
8348: }
1.584 raeburn 8349: }
1.1022 raeburn 8350: } elsif ($caller eq 'requests') {
8351: if ($codedom =~ /^$match_domain$/) {
8352: my $chome = &domain($codedom,'primary');
8353: unless ($chome eq 'no_host') {
8354: push(@homeservers,$chome);
8355: }
8356: }
1.521 raeburn 8357: } else {
1.772 raeburn 8358: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8359: }
1.793 albertel 8360: foreach my $code (keys(%{$instcodes})) {
8361: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8362: }
8363: chop($courses);
1.772 raeburn 8364: my $ok_response = 0;
8365: my $response;
8366: while (@homeservers > 0 && $ok_response == 0) {
8367: my $server = shift(@homeservers);
8368: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8369: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8370: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8371: split(/:/,$response);
1.772 raeburn 8372: %{$codes} = (%{$codes},&str2hash($codes_str));
8373: push(@{$codetitles},&str2array($codetitles_str));
8374: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8375: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8376: $ok_response = 1;
8377: }
8378: }
8379: if ($ok_response) {
1.521 raeburn 8380: return 'ok';
1.772 raeburn 8381: } else {
8382: return $response;
1.521 raeburn 8383: }
8384: }
8385:
1.792 raeburn 8386: sub auto_instcode_defaults {
8387: my ($domain,$returnhash,$code_order) = @_;
8388: my @homeservers;
1.841 albertel 8389:
8390: my %servers = &get_servers($domain,'library');
8391: foreach my $tryserver (keys(%servers)) {
8392: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8393: push(@homeservers,$tryserver);
8394: }
1.792 raeburn 8395: }
1.841 albertel 8396:
1.792 raeburn 8397: my $response;
1.841 albertel 8398: foreach my $server (@homeservers) {
1.792 raeburn 8399: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8400: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8401:
8402: foreach my $pair (split(/\&/,$response)) {
8403: my ($name,$value)=split(/\=/,$pair);
8404: if ($name eq 'code_order') {
8405: @{$code_order} = split(/\&/,&unescape($value));
8406: } else {
8407: $returnhash->{&unescape($name)}=&unescape($value);
8408: }
8409: }
8410: return 'ok';
1.792 raeburn 8411: }
1.841 albertel 8412:
8413: return $response;
1.1003 raeburn 8414: }
8415:
8416: sub auto_possible_instcodes {
1.1007 raeburn 8417: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8418: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8419: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8420: return;
8421: }
1.1003 raeburn 8422: my (@homeservers,$uhome);
8423: if (defined(&domain($domain,'primary'))) {
8424: $uhome=&domain($domain,'primary');
8425: push(@homeservers,&domain($domain,'primary'));
8426: } else {
8427: my %servers = &get_servers($domain,'library');
8428: foreach my $tryserver (keys(%servers)) {
8429: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8430: push(@homeservers,$tryserver);
8431: }
8432: }
8433: }
8434: my $response;
8435: foreach my $server (@homeservers) {
8436: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8437: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8438: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8439: split(':',$response);
8440: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8441: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8442: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8443: my ($name,$value)=split('=',$item);
8444: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8445: }
8446: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8447: my ($name,$value)=split('=',$item);
8448: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8449: }
8450: return 'ok';
8451: }
8452: return $response;
8453: }
1.792 raeburn 8454:
1.1010 raeburn 8455: sub auto_courserequest_checks {
8456: my ($dom) = @_;
1.1020 raeburn 8457: my ($homeserver,%validations);
8458: if ($dom =~ /^$match_domain$/) {
8459: $homeserver = &domain($dom,'primary');
8460: }
8461: unless ($homeserver eq 'no_host') {
8462: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8463: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8464: my @items = split(/&/,$response);
8465: foreach my $item (@items) {
8466: my ($key,$value) = split('=',$item);
8467: $validations{&unescape($key)} = &thaw_unescape($value);
8468: }
8469: }
8470: }
1.1010 raeburn 8471: return %validations;
8472: }
8473:
1.1020 raeburn 8474: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8475: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8476: my ($homeserver,$response);
8477: if ($dom =~ /^$match_domain$/) {
8478: $homeserver = &domain($dom,'primary');
8479: }
1.1172.2.43 raeburn 8480: unless ($homeserver eq 'no_host') {
8481: my $customdata;
8482: if (ref($custominfo) eq 'HASH') {
8483: $customdata = &freeze_escape($custominfo);
8484: }
1.1020 raeburn 8485: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8486: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8487: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8488: $customdata,$homeserver));
1.1020 raeburn 8489: }
8490: return $response;
8491: }
8492:
1.777 albertel 8493: sub auto_validate_class_sec {
1.918 raeburn 8494: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8495: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8496: my $ownerlist;
8497: if (ref($owners) eq 'ARRAY') {
8498: $ownerlist = join(',',@{$owners});
8499: } else {
8500: $ownerlist = $owners;
8501: }
1.773 raeburn 8502: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8503: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8504: return $response;
8505: }
8506:
1.1172.2.38 raeburn 8507: sub auto_crsreq_update {
8508: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8509: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8510: my ($homeserver,%crsreqresponse);
8511: if ($cdom =~ /^$match_domain$/) {
8512: $homeserver = &domain($cdom,'primary');
8513: }
8514: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8515: my $info;
8516: if (ref($inbound) eq 'HASH') {
8517: $info = &freeze_escape($inbound);
8518: }
8519: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8520: ':'.&escape($action).':'.&escape($ownername).':'.
8521: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8522: &escape($title).':'.&escape($code).':'.
8523: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8524: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8525: my @items = split(/&/,$response);
8526: foreach my $item (@items) {
8527: my ($key,$value) = split('=',$item);
8528: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8529: }
8530: }
8531: }
8532: return \%crsreqresponse;
8533: }
8534:
1.1172.2.78 raeburn 8535: sub auto_export_grades {
8536: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8537: my ($homeserver,%exportresponse);
8538: if ($cdom =~ /^$match_domain$/) {
8539: $homeserver = &domain($cdom,'primary');
8540: }
8541: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8542: my $info;
8543: if (ref($inforef) eq 'HASH') {
8544: $info = &freeze_escape($inforef);
8545: }
8546: if (ref($gradesref) eq 'HASH') {
8547: my $grades = &freeze_escape($gradesref);
8548: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8549: $info.':'.$grades,$homeserver);
8550: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8551: my @items = split(/&/,$response);
8552: foreach my $item (@items) {
8553: my ($key,$value) = split('=',$item);
8554: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8555: }
8556: }
8557: }
8558: }
8559: return \%exportresponse;
8560: }
8561:
1.1172.2.68 raeburn 8562: sub check_instcode_cloning {
8563: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8564: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8565: return;
8566: }
8567: my $canclone;
8568: if (@{$code_order} > 0) {
8569: my $instcoderegexp ='^';
8570: my @clonecodes = split(/\&/,$cloner);
8571: foreach my $item (@{$code_order}) {
8572: if (grep(/^\Q$item\E=/,@clonecodes)) {
8573: foreach my $pair (@clonecodes) {
8574: my ($key,$val) = split(/\=/,$pair,2);
8575: $val = &unescape($val);
8576: if ($key eq $item) {
8577: $instcoderegexp .= '('.$val.')';
8578: last;
8579: }
8580: }
8581: } else {
8582: $instcoderegexp .= $codedefaults->{$item};
8583: }
8584: }
8585: $instcoderegexp .= '$';
8586: my (@from,@to);
8587: eval {
8588: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8589: (@to) = ($clonetocode =~ /$instcoderegexp/);
8590: };
8591: if ((@from > 0) && (@to > 0)) {
8592: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8593: if (!@diffs) {
8594: $canclone = 1;
8595: }
8596: }
8597: }
8598: return $canclone;
8599: }
8600:
8601: sub default_instcode_cloning {
8602: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8603: my (%codedefaults,@code_order,$canclone);
8604: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8605: %codedefaults = %{$codedefaultsref};
8606: @code_order = @{$codeorderref};
8607: } elsif ($clonedom) {
8608: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8609: }
8610: if (($domdefclone) && (@code_order)) {
8611: my @clonecodes = split(/\+/,$domdefclone);
8612: my $instcoderegexp ='^';
8613: foreach my $item (@code_order) {
8614: if (grep(/^\Q$item\E$/,@clonecodes)) {
8615: $instcoderegexp .= '('.$codedefaults{$item}.')';
8616: } else {
8617: $instcoderegexp .= $codedefaults{$item};
8618: }
8619: }
8620: $instcoderegexp .= '$';
8621: my (@from,@to);
8622: eval {
8623: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8624: (@to) = ($clonetocode =~ /$instcoderegexp/);
8625: };
8626: if ((@from > 0) && (@to > 0)) {
8627: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8628: if (!@diffs) {
8629: $canclone = 1;
8630: }
8631: }
8632: }
8633: return $canclone;
8634: }
8635:
1.679 raeburn 8636: # ------------------------------------------------------- Course Group routines
8637:
8638: sub get_coursegroups {
1.809 raeburn 8639: my ($cdom,$cnum,$group,$namespace) = @_;
8640: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8641: }
8642:
1.679 raeburn 8643: sub modify_coursegroup {
8644: my ($cdom,$cnum,$groupsettings) = @_;
8645: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8646: }
8647:
1.809 raeburn 8648: sub toggle_coursegroup_status {
8649: my ($cdom,$cnum,$group,$action) = @_;
8650: my ($from_namespace,$to_namespace);
8651: if ($action eq 'delete') {
8652: $from_namespace = 'coursegroups';
8653: $to_namespace = 'deleted_groups';
8654: } else {
8655: $from_namespace = 'deleted_groups';
8656: $to_namespace = 'coursegroups';
8657: }
8658: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8659: if (my $tmp = &error(%curr_group)) {
8660: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8661: return ('read error',$tmp);
8662: } else {
8663: my %savedsettings = %curr_group;
1.809 raeburn 8664: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8665: my $deloutcome;
8666: if ($result eq 'ok') {
1.809 raeburn 8667: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8668: } else {
8669: return ('write error',$result);
8670: }
8671: if ($deloutcome eq 'ok') {
8672: return 'ok';
8673: } else {
8674: return ('delete error',$deloutcome);
8675: }
8676: }
8677: }
8678:
1.679 raeburn 8679: sub modify_group_roles {
1.957 raeburn 8680: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8681: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8682: my $role = 'gr/'.&escape($userprivs);
8683: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8684: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8685: if ($result eq 'ok') {
8686: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8687: }
1.679 raeburn 8688: return $result;
8689: }
8690:
8691: sub modify_coursegroup_membership {
8692: my ($cdom,$cnum,$membership) = @_;
8693: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8694: return $result;
8695: }
8696:
1.682 raeburn 8697: sub get_active_groups {
8698: my ($udom,$uname,$cdom,$cnum) = @_;
8699: my $now = time;
8700: my %groups = ();
8701: foreach my $key (keys(%env)) {
1.811 albertel 8702: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8703: my ($start,$end) = split(/\./,$env{$key});
8704: if (($end!=0) && ($end<$now)) { next; }
8705: if (($start!=0) && ($start>$now)) { next; }
8706: if ($1 eq $cdom && $2 eq $cnum) {
8707: $groups{$3} = $env{$key} ;
8708: }
8709: }
8710: }
8711: return %groups;
8712: }
8713:
1.683 raeburn 8714: sub get_group_membership {
8715: my ($cdom,$cnum,$group) = @_;
8716: return(&dump('groupmembership',$cdom,$cnum,$group));
8717: }
8718:
8719: sub get_users_groups {
8720: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8721: my @usersgroups;
1.683 raeburn 8722: my $cachetime=1800;
8723:
8724: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8725: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8726: if (defined($cached)) {
1.734 albertel 8727: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8728: } else {
8729: $grouplist = '';
1.816 raeburn 8730: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8731: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8732: my $access_end = $env{'course.'.$courseid.
8733: '.default_enrollment_end_date'};
8734: my $now = time;
8735: foreach my $key (keys(%roleshash)) {
8736: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8737: my $group = $1;
8738: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8739: my $start = $2;
8740: my $end = $1;
8741: if ($start == -1) { next; } # deleted from group
8742: if (($start!=0) && ($start>$now)) { next; }
8743: if (($end!=0) && ($end<$now)) {
8744: if ($access_end && $access_end < $now) {
8745: if ($access_end - $end < 86400) {
8746: push(@usersgroups,$group);
1.733 raeburn 8747: }
8748: }
1.817 raeburn 8749: next;
1.733 raeburn 8750: }
1.817 raeburn 8751: push(@usersgroups,$group);
1.683 raeburn 8752: }
8753: }
8754: }
1.817 raeburn 8755: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8756: $grouplist = join(':',@usersgroups);
8757: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8758: }
1.733 raeburn 8759: return @usersgroups;
1.683 raeburn 8760: }
8761:
8762: sub devalidate_getgroups_cache {
8763: my ($udom,$uname,$cdom,$cnum)=@_;
8764: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8765:
1.683 raeburn 8766: my $hashid="$udom:$uname:$courseid";
8767: &devalidate_cache_new('getgroups',$hashid);
8768: }
8769:
1.12 www 8770: # ------------------------------------------------------------------ Plain Text
8771:
8772: sub plaintext {
1.988 raeburn 8773: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8774: if ($short =~ m{^cr/}) {
1.758 albertel 8775: return (split('/',$short))[-1];
8776: }
1.742 raeburn 8777: if (!defined($cid)) {
8778: $cid = $env{'request.course.id'};
8779: }
8780: my %rolenames = (
1.1008 raeburn 8781: Course => 'std',
8782: Community => 'alt1',
1.742 raeburn 8783: );
1.1037 raeburn 8784: if ($cid ne '') {
8785: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8786: unless ($forcedefault) {
8787: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8788: &Apache::lonlocal::mt_escape(\$roletext);
8789: return &Apache::lonlocal::mt($roletext);
8790: }
8791: }
8792: }
8793: if ((defined($type)) && (defined($rolenames{$type})) &&
8794: (defined($rolenames{$type})) &&
8795: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8796: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8797: } elsif ($cid ne '') {
8798: my $crstype = $env{'course.'.$cid.'.type'};
8799: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8800: (defined($prp{$short}{$rolenames{$crstype}}))) {
8801: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8802: }
1.742 raeburn 8803: }
1.1037 raeburn 8804: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8805: }
8806:
8807: # ----------------------------------------------------------------- Assign Role
8808:
8809: sub assignrole {
1.957 raeburn 8810: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8811: $context)=@_;
1.21 www 8812: my $mrole;
8813: if ($role =~ /^cr\//) {
1.393 www 8814: my $cwosec=$url;
1.811 albertel 8815: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8816: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8817: my $refused = 1;
8818: if ($context eq 'requestcourses') {
8819: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8820: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8821: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8822: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8823: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8824: if ($crsenv{'internal.courseowner'} eq
8825: $env{'user.name'}.':'.$env{'user.domain'}) {
8826: $refused = '';
8827: }
8828: }
8829: }
8830: }
8831: }
8832: if ($refused) {
8833: &logthis('Refused custom assignrole: '.
8834: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8835: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8836: return 'refused';
8837: }
1.104 www 8838: }
1.21 www 8839: $mrole='cr';
1.678 raeburn 8840: } elsif ($role =~ /^gr\//) {
8841: my $cwogrp=$url;
1.811 albertel 8842: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8843: unless (&allowed('mdg',$cwogrp)) {
8844: &logthis('Refused group assignrole: '.
8845: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8846: $env{'user.name'}.' at '.$env{'user.domain'});
8847: return 'refused';
8848: }
8849: $mrole='gr';
1.21 www 8850: } else {
1.82 www 8851: my $cwosec=$url;
1.811 albertel 8852: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8853: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8854: my $refused;
8855: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8856: if (!(&allowed('c'.$role,$url))) {
8857: $refused = 1;
8858: }
8859: } else {
8860: $refused = 1;
8861: }
1.947 raeburn 8862: if ($refused) {
1.1045 raeburn 8863: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8864: if (!$selfenroll && $context eq 'course') {
8865: my %crsenv;
8866: if ($role eq 'cc' || $role eq 'co') {
8867: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8868: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8869: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8870: if ($crsenv{'internal.courseowner'} eq
8871: $env{'user.name'}.':'.$env{'user.domain'}) {
8872: $refused = '';
8873: }
8874: }
8875: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8876: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8877: if ($crsenv{'internal.courseowner'} eq
8878: $env{'user.name'}.':'.$env{'user.domain'}) {
8879: $refused = '';
8880: }
8881: }
8882: }
8883: }
8884: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8885: $refused = '';
1.1017 raeburn 8886: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8887: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8888: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8889: my $wrongcc;
8890: if ($cnum =~ /^$match_community$/) {
8891: $wrongcc = 1 if ($role eq 'cc');
8892: } else {
8893: $wrongcc = 1 if ($role eq 'co');
8894: }
8895: unless ($wrongcc) {
8896: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8897: if ($crsenv{'internal.courseowner'} eq
8898: $env{'user.name'}.':'.$env{'user.domain'}) {
8899: $refused = '';
8900: }
1.1017 raeburn 8901: }
8902: }
1.1172.2.9 raeburn 8903: } elsif ($context eq 'requestauthor') {
8904: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8905: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8906: if ($env{'environment.requestauthor'} eq 'automatic') {
8907: $refused = '';
8908: } else {
8909: my %domdefaults = &get_domain_defaults($udom);
8910: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8911: my $checkbystatus;
8912: if ($env{'user.adv'}) {
8913: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8914: if ($disposition eq 'automatic') {
8915: $refused = '';
8916: } elsif ($disposition eq '') {
8917: $checkbystatus = 1;
8918: }
8919: } else {
8920: $checkbystatus = 1;
8921: }
8922: if ($checkbystatus) {
8923: if ($env{'environment.inststatus'}) {
8924: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8925: foreach my $type (@inststatuses) {
8926: if (($type ne '') &&
8927: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8928: $refused = '';
8929: }
8930: }
8931: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8932: $refused = '';
8933: }
8934: }
8935: }
8936: }
8937: }
1.1017 raeburn 8938: }
8939: if ($refused) {
1.947 raeburn 8940: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8941: ' '.$role.' '.$end.' '.$start.' by '.
8942: $env{'user.name'}.' at '.$env{'user.domain'});
8943: return 'refused';
8944: }
1.932 raeburn 8945: }
1.1131 raeburn 8946: } elsif ($role eq 'au') {
8947: if ($url ne '/'.$udom.'/') {
8948: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8949: ' to assign author role for '.$uname.':'.$udom.
8950: ' in domain: '.$url.' refused (wrong domain).');
8951: return 'refused';
8952: }
1.104 www 8953: }
1.21 www 8954: $mrole=$role;
8955: }
1.620 albertel 8956: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8957: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8958: if ($end) { $command.='_'.$end; }
1.21 www 8959: if ($start) {
8960: if ($end) {
1.81 www 8961: $command.='_'.$start;
1.21 www 8962: } else {
1.81 www 8963: $command.='_0_'.$start;
1.21 www 8964: }
8965: }
1.739 raeburn 8966: my $origstart = $start;
8967: my $origend = $end;
1.957 raeburn 8968: my $delflag;
1.357 www 8969: # actually delete
8970: if ($deleteflag) {
1.373 www 8971: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8972: # modify command to delete the role
1.620 albertel 8973: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8974: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8975: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8976: # set start and finish to negative values for userrolelog
8977: $start=-1;
8978: $end=-1;
1.957 raeburn 8979: $delflag = 1;
1.357 www 8980: }
8981: }
8982: # send command
1.349 www 8983: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8984: # log new user role if status is ok
1.349 www 8985: if ($answer eq 'ok') {
1.663 raeburn 8986: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8987: if (($role eq 'cc') || ($role eq 'in') ||
8988: ($role eq 'ep') || ($role eq 'ad') ||
8989: ($role eq 'ta') || ($role eq 'st') ||
8990: ($role=~/^cr/) || ($role eq 'gr') ||
8991: ($role eq 'co')) {
1.1172.2.13 raeburn 8992: # for course roles, perform group memberships changes triggered by role change.
8993: unless ($role =~ /^gr/) {
8994: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8995: $origstart,$selfenroll,$context);
8996: }
1.1172.2.9 raeburn 8997: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8998: $selfenroll,$context);
8999: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.84 raeburn 9000: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1172.2.9 raeburn 9001: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9002: $context);
9003: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9004: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9005: $context);
9006: }
1.1053 raeburn 9007: if ($role eq 'cc') {
9008: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9009: }
1.349 www 9010: }
9011: return $answer;
1.169 harris41 9012: }
9013:
1.1053 raeburn 9014: sub autoupdate_coowners {
9015: my ($url,$end,$start,$uname,$udom) = @_;
9016: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9017: if (($cdom ne '') && ($cnum ne '')) {
9018: my $now = time;
9019: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9020: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9021: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9022: my $instcode = $coursehash{'internal.coursecode'};
9023: if ($instcode ne '') {
1.1056 raeburn 9024: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9025: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9026: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9027: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9028: if ($result eq 'valid') {
9029: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9030: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9031: push(@newcoowners,$coowner);
9032: }
9033: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9034: push(@newcoowners,$uname.':'.$udom);
9035: }
9036: @newcoowners = sort(@newcoowners);
9037: } else {
9038: push(@newcoowners,$uname.':'.$udom);
9039: }
9040: } else {
9041: if ($coursehash{'internal.co-owners'}) {
9042: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9043: unless ($coowner eq $uname.':'.$udom) {
9044: push(@newcoowners,$coowner);
9045: }
9046: }
9047: unless (@newcoowners > 0) {
9048: $delcoowners = 1;
9049: $coowners = '';
9050: }
9051: }
9052: }
9053: if (@newcoowners || $delcoowners) {
9054: &store_coowners($cdom,$cnum,$coursehash{'home'},
9055: $delcoowners,@newcoowners);
9056: }
9057: }
9058: }
9059: }
9060: }
9061: }
9062: }
9063:
9064: sub store_coowners {
9065: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9066: my $cid = $cdom.'_'.$cnum;
9067: my ($coowners,$delresult,$putresult);
9068: if (@newcoowners) {
9069: $coowners = join(',',@newcoowners);
9070: my %coownershash = (
9071: 'internal.co-owners' => $coowners,
9072: );
9073: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9074: if ($putresult eq 'ok') {
9075: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9076: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9077: }
9078: }
9079: }
9080: if ($delcoowners) {
9081: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9082: if ($delresult eq 'ok') {
9083: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9084: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9085: }
9086: }
9087: }
9088: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9089: my %crsinfo =
9090: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9091: if (ref($crsinfo{$cid}) eq 'HASH') {
9092: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9093: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9094: }
9095: }
9096: }
9097:
1.169 harris41 9098: # -------------------------------------------------- Modify user authentication
1.197 www 9099: # Overrides without validation
9100:
1.169 harris41 9101: sub modifyuserauth {
9102: my ($udom,$uname,$umode,$upass)=@_;
9103: my $uhome=&homeserver($uname,$udom);
1.197 www 9104: unless (&allowed('mau',$udom)) { return 'refused'; }
9105: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9106: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9107: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9108: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9109: &escape($upass),$uhome);
1.620 albertel 9110: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9111: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9112: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9113: &log($udom,,$uname,$uhome,
1.620 albertel 9114: 'Authentication changed by '.$env{'user.domain'}.', '.
9115: $env{'user.name'}.', '.$umode.
1.197 www 9116: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9117: unless ($reply eq 'ok') {
1.197 www 9118: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9119: return 'error: '.$reply;
9120: }
1.170 harris41 9121: return 'ok';
1.80 www 9122: }
9123:
1.81 www 9124: # --------------------------------------------------------------- Modify a user
1.80 www 9125:
1.81 www 9126: sub modifyuser {
1.206 matthew 9127: my ($udom, $uname, $uid,
9128: $umode, $upass, $first,
9129: $middle, $last, $gene,
1.1058 raeburn 9130: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9131: $udom= &LONCAPA::clean_domain($udom);
9132: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9133: my $showcandelete = 'none';
9134: if (ref($candelete) eq 'ARRAY') {
9135: if (@{$candelete} > 0) {
9136: $showcandelete = join(', ',@{$candelete});
9137: }
9138: }
1.81 www 9139: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9140: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9141: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9142: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9143: ' desiredhome not specified').
1.620 albertel 9144: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9145: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9146: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9147: my $newuser;
9148: if ($uhome eq 'no_host') {
9149: $newuser = 1;
9150: }
1.80 www 9151: # ----------------------------------------------------------------- Create User
1.406 albertel 9152: if (($uhome eq 'no_host') &&
9153: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9154: my $unhome='';
1.844 albertel 9155: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9156: $unhome = $desiredhome;
1.620 albertel 9157: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9158: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9159: } else { # load balancing routine for determining $unhome
1.81 www 9160: my $loadm=10000000;
1.841 albertel 9161: my %servers = &get_servers($udom,'library');
9162: foreach my $tryserver (keys(%servers)) {
9163: my $answer=reply('load',$tryserver);
9164: if (($answer=~/\d+/) && ($answer<$loadm)) {
9165: $loadm=$answer;
9166: $unhome=$tryserver;
9167: }
1.80 www 9168: }
9169: }
9170: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9171: return 'error: unable to find a home server for '.$uname.
9172: ' in domain '.$udom;
1.80 www 9173: }
9174: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9175: &escape($upass),$unhome);
9176: unless ($reply eq 'ok') {
9177: return 'error: '.$reply;
9178: }
1.230 stredwic 9179: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9180: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9181: return 'error: unable verify users home machine.';
1.80 www 9182: }
1.209 matthew 9183: } # End of creation of new user
1.80 www 9184: # ---------------------------------------------------------------------- Add ID
9185: if ($uid) {
9186: $uid=~tr/A-Z/a-z/;
9187: my %uidhash=&idrget($udom,$uname);
1.196 www 9188: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9189: && (!$forceid)) {
1.80 www 9190: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9191: return 'error: user id "'.$uid.'" does not match '.
9192: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9193: }
9194: } else {
9195: &idput($udom,($uname => $uid));
9196: }
9197: }
9198: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9199: my @tmp=&get('environment',
1.899 raeburn 9200: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9201: 'permanentemail','inststatus'],
1.134 albertel 9202: $udom,$uname);
1.1075 raeburn 9203: my (%names,%oldnames);
1.313 matthew 9204: if ($tmp[0] =~ m/^error:.*/) {
9205: %names=();
9206: } else {
9207: %names = @tmp;
1.1075 raeburn 9208: %oldnames = %names;
1.313 matthew 9209: }
1.388 www 9210: #
1.1058 raeburn 9211: # If name, email and/or uid are blank (e.g., because an uploaded file
9212: # of users did not contain them), do not overwrite existing values
9213: # unless field is in $candelete array ref.
9214: #
9215:
9216: my @fields = ('firstname','middlename','lastname','generation',
9217: 'permanentemail','id');
9218: my %newvalues;
9219: if (ref($candelete) eq 'ARRAY') {
9220: foreach my $field (@fields) {
9221: if (grep(/^\Q$field\E$/,@{$candelete})) {
9222: if ($field eq 'firstname') {
9223: $names{$field} = $first;
9224: } elsif ($field eq 'middlename') {
9225: $names{$field} = $middle;
9226: } elsif ($field eq 'lastname') {
9227: $names{$field} = $last;
9228: } elsif ($field eq 'generation') {
9229: $names{$field} = $gene;
9230: } elsif ($field eq 'permanentemail') {
9231: $names{$field} = $email;
9232: } elsif ($field eq 'id') {
9233: $names{$field} = $uid;
9234: }
9235: }
9236: }
9237: }
1.388 www 9238: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9239: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9240: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9241: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9242: if ($email) {
9243: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9244: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9245: }
1.899 raeburn 9246: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9247: if (defined($inststatus)) {
9248: $names{'inststatus'} = '';
9249: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9250: if (ref($usertypes) eq 'HASH') {
9251: my @okstatuses;
9252: foreach my $item (split(/:/,$inststatus)) {
9253: if (defined($usertypes->{$item})) {
9254: push(@okstatuses,$item);
9255: }
9256: }
9257: if (@okstatuses) {
9258: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9259: }
9260: }
9261: }
1.1075 raeburn 9262: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9263: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9264: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9265: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9266: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9267: } else {
9268: $logmsg .= ' during self creation';
9269: }
1.1075 raeburn 9270: my $changed;
9271: if ($newuser) {
9272: $changed = 1;
9273: } else {
9274: foreach my $field (@fields) {
9275: if ($names{$field} ne $oldnames{$field}) {
9276: $changed = 1;
9277: last;
9278: }
9279: }
9280: }
9281: unless ($changed) {
9282: $logmsg = 'No changes in user information needed for: '.$logmsg;
9283: &logthis($logmsg);
9284: return 'ok';
9285: }
9286: my $reply = &put('environment', \%names, $udom,$uname);
9287: if ($reply ne 'ok') {
9288: return 'error: '.$reply;
9289: }
1.1087 raeburn 9290: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9291: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9292: }
1.1075 raeburn 9293: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9294: &devalidate_cache_new('namescache',$uname.':'.$udom);
9295: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9296: &logthis($logmsg);
1.134 albertel 9297: return 'ok';
1.80 www 9298: }
9299:
1.81 www 9300: # -------------------------------------------------------------- Modify student
1.80 www 9301:
1.81 www 9302: sub modifystudent {
9303: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9304: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9305: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9306: if (!$cid) {
1.620 albertel 9307: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9308: return 'not_in_class';
9309: }
1.80 www 9310: }
9311: # --------------------------------------------------------------- Make the user
1.81 www 9312: my $reply=&modifyuser
1.209 matthew 9313: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9314: $desiredhome,$email,$inststatus);
1.80 www 9315: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9316: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9317: # student's environment
1.297 matthew 9318: $uid = undef if (!$forceid);
1.455 albertel 9319: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9320: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9321: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9322: return $reply;
9323: }
9324:
9325: sub modify_student_enrollment {
1.1172.2.23 raeburn 9326: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9327: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9328: my ($cdom,$cnum,$chome);
9329: if (!$cid) {
1.620 albertel 9330: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9331: return 'not_in_class';
9332: }
1.620 albertel 9333: $cdom=$env{'course.'.$cid.'.domain'};
9334: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9335: } else {
9336: ($cdom,$cnum)=split(/_/,$cid);
9337: }
1.620 albertel 9338: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9339: if (!$chome) {
1.457 raeburn 9340: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9341: }
1.455 albertel 9342: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9343: # Make sure the user exists
1.81 www 9344: my $uhome=&homeserver($uname,$udom);
9345: if (($uhome eq '') || ($uhome eq 'no_host')) {
9346: return 'error: no such user';
9347: }
1.297 matthew 9348: # Get student data if we were not given enough information
9349: if (!defined($first) || $first eq '' ||
9350: !defined($last) || $last eq '' ||
9351: !defined($uid) || $uid eq '' ||
9352: !defined($middle) || $middle eq '' ||
9353: !defined($gene) || $gene eq '') {
1.294 matthew 9354: # They did not supply us with enough data to enroll the student, so
9355: # we need to pick up more information.
1.297 matthew 9356: my %tmp = &get('environment',
1.294 matthew 9357: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9358: ,$udom,$uname);
9359:
1.800 albertel 9360: #foreach my $key (keys(%tmp)) {
9361: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9362: #}
1.294 matthew 9363: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9364: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9365: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9366: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9367: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9368: }
1.556 albertel 9369: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9370: my $user = "$uname:$udom";
9371: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9372: my $reply=cput('classlist',
1.1148 raeburn 9373: {$user =>
1.1172.2.76 raeburn 9374: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9375: $cdom,$cnum);
1.1148 raeburn 9376: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9377: &devalidate_getsection_cache($udom,$uname,$cid);
9378: } else {
1.81 www 9379: return 'error: '.$reply;
9380: }
1.297 matthew 9381: # Add student role to user
1.83 www 9382: my $uurl='/'.$cid;
1.81 www 9383: $uurl=~s/\_/\//g;
9384: if ($usec) {
9385: $uurl.='/'.$usec;
9386: }
1.1148 raeburn 9387: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9388: $selfenroll,$context);
9389: if ($result ne 'ok') {
9390: if ($old_entry{$user} ne '') {
9391: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9392: } else {
9393: $reply = &del('classlist',[$user],$cdom,$cnum);
9394: }
9395: }
9396: return $result;
1.21 www 9397: }
9398:
1.556 albertel 9399: sub format_name {
9400: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9401: my $name;
9402: if ($first ne 'lastname') {
9403: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9404: } else {
9405: if ($lastname=~/\S/) {
9406: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9407: $name=~s/\s+,/,/;
9408: } else {
9409: $name.= $firstname.' '.$middlename.' '.$generation;
9410: }
9411: }
9412: $name=~s/^\s+//;
9413: $name=~s/\s+$//;
9414: $name=~s/\s+/ /g;
9415: return $name;
9416: }
9417:
1.84 www 9418: # ------------------------------------------------- Write to course preferences
9419:
9420: sub writecoursepref {
9421: my ($courseid,%prefs)=@_;
9422: $courseid=~s/^\///;
9423: $courseid=~s/\_/\//g;
9424: my ($cdomain,$cnum)=split(/\//,$courseid);
9425: my $chome=homeserver($cnum,$cdomain);
9426: if (($chome eq '') || ($chome eq 'no_host')) {
9427: return 'error: no such course';
9428: }
9429: my $cstring='';
1.800 albertel 9430: foreach my $pref (keys(%prefs)) {
9431: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9432: }
1.84 www 9433: $cstring=~s/\&$//;
9434: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9435: }
9436:
9437: # ---------------------------------------------------------- Make/modify course
9438:
9439: sub createcourse {
1.741 raeburn 9440: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9441: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9442: $url=&declutter($url);
9443: my $cid='';
1.1028 raeburn 9444: if ($context eq 'requestcourses') {
9445: my $can_create = 0;
9446: my ($ownername,$ownerdom) = split(':',$course_owner);
9447: if ($udom eq $ownerdom) {
9448: if (&usertools_access($ownername,$ownerdom,$category,undef,
9449: $context)) {
9450: $can_create = 1;
9451: }
9452: } else {
9453: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9454: $category);
9455: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9456: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9457: if (@curr > 0) {
9458: my @options = qw(approval validate autolimit);
9459: my $optregex = join('|',@options);
9460: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9461: $can_create = 1;
9462: }
9463: }
9464: }
9465: }
9466: if ($can_create) {
9467: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9468: unless (&allowed('ccc',$udom)) {
9469: return 'refused';
9470: }
1.1017 raeburn 9471: }
9472: } else {
9473: return 'refused';
9474: }
1.1028 raeburn 9475: } elsif (!&allowed('ccc',$udom)) {
9476: return 'refused';
1.84 www 9477: }
1.1011 raeburn 9478: # --------------------------------------------------------------- Get Unique ID
9479: my $uname;
9480: if ($cnum =~ /^$match_courseid$/) {
9481: my $chome=&homeserver($cnum,$udom,'true');
9482: if (($chome eq '') || ($chome eq 'no_host')) {
9483: $uname = $cnum;
9484: } else {
1.1038 raeburn 9485: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9486: }
9487: } else {
1.1038 raeburn 9488: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9489: }
9490: return $uname if ($uname =~ /^error/);
9491: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9492: if (!defined($course_server)) {
9493: if (defined(&domain($udom,'primary'))) {
9494: $course_server = &domain($udom,'primary');
9495: } else {
9496: $course_server = $env{'user.home'};
9497: }
9498: }
9499: my %host_servers =
9500: &Apache::lonnet::get_servers($udom,'library');
9501: unless ($host_servers{$course_server}) {
9502: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9503: }
1.84 www 9504: # ------------------------------------------------------------- Make the course
9505: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9506: $course_server);
1.84 www 9507: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9508: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9509: if (($uhome eq '') || ($uhome eq 'no_host')) {
9510: return 'error: no such course';
9511: }
1.271 www 9512: # ----------------------------------------------------------------- Course made
1.516 raeburn 9513: # log existence
1.1029 raeburn 9514: my $now = time;
1.918 raeburn 9515: my $newcourse = {
9516: $udom.'_'.$uname => {
1.921 raeburn 9517: description => $description,
9518: inst_code => $inst_code,
9519: owner => $course_owner,
9520: type => $crstype,
1.1029 raeburn 9521: creator => $env{'user.name'}.':'.
9522: $env{'user.domain'},
9523: created => $now,
9524: context => $context,
1.918 raeburn 9525: },
9526: };
1.921 raeburn 9527: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9528: # set toplevel url
1.271 www 9529: my $topurl=$url;
9530: unless ($nonstandard) {
9531: # ------------------------------------------ For standard courses, make top url
9532: my $mapurl=&clutter($url);
1.278 www 9533: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9534: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9535: <map>
9536: <resource id="1" type="start"></resource>
9537: <resource id="2" src="$mapurl"></resource>
9538: <resource id="3" type="finish"></resource>
9539: <link index="1" from="1" to="2"></link>
9540: <link index="2" from="2" to="3"></link>
9541: </map>
9542: ENDINITMAP
9543: $topurl=&declutter(
1.638 albertel 9544: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9545: );
9546: }
9547: # ----------------------------------------------------------- Write preferences
1.84 www 9548: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9549: ('description' => $description,
9550: 'url' => $topurl,
9551: 'internal.creator' => $env{'user.name'}.':'.
9552: $env{'user.domain'},
9553: 'internal.created' => $now,
9554: 'internal.creationcontext' => $context)
9555: );
1.84 www 9556: return '/'.$udom.'/'.$uname;
9557: }
9558:
1.1011 raeburn 9559: # ------------------------------------------------------------------- Create ID
9560: sub generate_coursenum {
1.1038 raeburn 9561: my ($udom,$crstype) = @_;
1.1011 raeburn 9562: my $domdesc = &domain($udom);
9563: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9564: my $first;
9565: if ($crstype eq 'Community') {
9566: $first = '0';
9567: } else {
9568: $first = int(1+rand(9));
9569: }
9570: my $uname=$first.
1.1011 raeburn 9571: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9572: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9573: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9574: # ----------------------------------------------- Make sure that does not exist
9575: my $uhome=&homeserver($uname,$udom,'true');
9576: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9577: if ($crstype eq 'Community') {
9578: $first = '0';
9579: } else {
9580: $first = int(1+rand(9));
9581: }
9582: $uname=$first.
1.1011 raeburn 9583: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9584: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9585: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9586: $uhome=&homeserver($uname,$udom,'true');
9587: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9588: return 'error: unable to generate unique course-ID';
9589: }
9590: }
9591: return $uname;
9592: }
9593:
1.813 albertel 9594: sub is_course {
1.1167 droeschl 9595: my ($cdom, $cnum) = scalar(@_) == 1 ?
9596: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9597:
9598: return unless $cdom and $cnum;
9599:
9600: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9601: '.');
9602:
1.1172.2.23 raeburn 9603: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9604: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9605: }
9606:
1.1015 raeburn 9607: sub store_userdata {
9608: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9609: my $result;
1.1016 raeburn 9610: if ($datakey ne '') {
1.1013 raeburn 9611: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9612: if ($udom eq '' || $uname eq '') {
9613: $udom = $env{'user.domain'};
9614: $uname = $env{'user.name'};
9615: }
9616: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9617: if (($uhome eq '') || ($uhome eq 'no_host')) {
9618: $result = 'error: no_host';
9619: } else {
9620: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9621: $storehash->{'host'} = $perlvar{'lonHostID'};
9622:
9623: my $namevalue='';
9624: foreach my $key (keys(%{$storehash})) {
9625: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9626: }
9627: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9628: unless ($namespace eq 'courserequests') {
9629: $datakey = &escape($datakey);
9630: }
1.1105 raeburn 9631: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9632: $namevalue,$uhome);
1.1013 raeburn 9633: }
9634: } else {
9635: $result = 'error: data to store was not a hash reference';
9636: }
9637: } else {
9638: $result= 'error: invalid requestkey';
9639: }
9640: return $result;
9641: }
9642:
1.21 www 9643: # ---------------------------------------------------------- Assign Custom Role
9644:
9645: sub assigncustomrole {
1.957 raeburn 9646: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9647: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9648: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9649: }
9650:
9651: # ----------------------------------------------------------------- Revoke Role
9652:
9653: sub revokerole {
1.957 raeburn 9654: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9655: my $now=time;
1.965 raeburn 9656: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9657: }
9658:
9659: # ---------------------------------------------------------- Revoke Custom Role
9660:
9661: sub revokecustomrole {
1.957 raeburn 9662: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9663: my $now=time;
1.357 www 9664: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9665: $deleteflag,$selfenroll,$context);
1.17 www 9666: }
9667:
1.533 banghart 9668: # ------------------------------------------------------------ Disk usage
1.535 albertel 9669: sub diskusage {
1.955 raeburn 9670: my ($udom,$uname,$directorypath,$getpropath)=@_;
9671: $directorypath =~ s/\/$//;
9672: my $listing=&reply('du2:'.&escape($directorypath).':'
9673: .&escape($getpropath).':'.&escape($uname).':'
9674: .&escape($udom),homeserver($uname,$udom));
9675: if ($listing eq 'unknown_cmd') {
9676: if ($getpropath) {
9677: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9678: }
9679: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9680: }
1.514 albertel 9681: return $listing;
1.512 banghart 9682: }
9683:
1.566 banghart 9684: sub is_locked {
1.1096 raeburn 9685: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9686: my @check;
9687: my $is_locked;
1.1093 raeburn 9688: push (@check,$file_name);
1.613 albertel 9689: my %locked = &get('file_permissions',\@check,
1.620 albertel 9690: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9691: my ($tmp)=keys(%locked);
9692: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9693:
1.566 banghart 9694: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9695: $is_locked = 'false';
9696: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9697: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9698: $is_locked = 'true';
1.1096 raeburn 9699: if (ref($which) eq 'ARRAY') {
9700: push(@{$which},$entry);
9701: } else {
9702: last;
9703: }
1.745 raeburn 9704: }
9705: }
1.566 banghart 9706: } else {
9707: $is_locked = 'false';
9708: }
1.1093 raeburn 9709: return $is_locked;
1.566 banghart 9710: }
9711:
1.759 albertel 9712: sub declutter_portfile {
9713: my ($file) = @_;
1.833 albertel 9714: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9715: return $file;
9716: }
9717:
1.559 banghart 9718: # ------------------------------------------------------------- Mark as Read Only
9719:
9720: sub mark_as_readonly {
9721: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9722: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9723: my ($tmp)=keys(%current_permissions);
9724: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9725: foreach my $file (@{$files}) {
1.759 albertel 9726: $file = &declutter_portfile($file);
1.561 banghart 9727: push(@{$current_permissions{$file}},$what);
1.559 banghart 9728: }
1.613 albertel 9729: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9730: return;
9731: }
9732:
1.572 banghart 9733: # ------------------------------------------------------------Save Selected Files
9734:
9735: sub save_selected_files {
9736: my ($user, $path, @files) = @_;
9737: my $filename = $user."savedfiles";
1.573 banghart 9738: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9739: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9740: foreach my $file (@files) {
1.620 albertel 9741: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9742: }
9743: foreach my $file (@other_files) {
1.574 banghart 9744: print (OUT $file."\n");
1.572 banghart 9745: }
1.574 banghart 9746: close (OUT);
1.572 banghart 9747: return 'ok';
9748: }
9749:
1.574 banghart 9750: sub clear_selected_files {
9751: my ($user) = @_;
9752: my $filename = $user."savedfiles";
1.1117 foxr 9753: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9754: print (OUT undef);
9755: close (OUT);
9756: return ("ok");
9757: }
9758:
1.572 banghart 9759: sub files_in_path {
9760: my ($user, $path) = @_;
9761: my $filename = $user."savedfiles";
9762: my %return_files;
1.1117 foxr 9763: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9764: while (my $line_in = <IN>) {
1.574 banghart 9765: chomp ($line_in);
9766: my @paths_and_file = split (m!/!, $line_in);
9767: my $file_part = pop (@paths_and_file);
9768: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9769: $path_part.='/';
9770: my $path_and_file = $path_part.$file_part;
9771: if ($path_part eq $path) {
9772: $return_files{$file_part}= 'selected';
9773: }
9774: }
1.574 banghart 9775: close (IN);
9776: return (\%return_files);
1.572 banghart 9777: }
9778:
9779: # called in portfolio select mode, to show files selected NOT in current directory
9780: sub files_not_in_path {
9781: my ($user, $path) = @_;
9782: my $filename = $user."savedfiles";
9783: my @return_files;
9784: my $path_part;
1.1117 foxr 9785: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9786: while (my $line = <IN>) {
1.572 banghart 9787: #ok, I know it's clunky, but I want it to work
1.800 albertel 9788: my @paths_and_file = split(m|/|, $line);
9789: my $file_part = pop(@paths_and_file);
9790: chomp($file_part);
9791: my $path_part = join('/', @paths_and_file);
1.572 banghart 9792: $path_part .= '/';
9793: my $path_and_file = $path_part.$file_part;
9794: if ($path_part ne $path) {
1.800 albertel 9795: push(@return_files, ($path_and_file));
1.572 banghart 9796: }
9797: }
1.800 albertel 9798: close(OUT);
1.574 banghart 9799: return (@return_files);
1.572 banghart 9800: }
9801:
1.745 raeburn 9802: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9803:
1.745 raeburn 9804: sub get_portfile_permissions {
9805: my ($domain,$user) = @_;
1.613 albertel 9806: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9807: my ($tmp)=keys(%current_permissions);
9808: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9809: return \%current_permissions;
9810: }
9811:
9812: #---------------------------------------------Get portfolio file access controls
9813:
1.749 raeburn 9814: sub get_access_controls {
1.745 raeburn 9815: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9816: my %access;
9817: my $real_file = $file;
9818: $file =~ s/\.meta$//;
1.745 raeburn 9819: if (defined($file)) {
1.749 raeburn 9820: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9821: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9822: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9823: }
9824: }
1.745 raeburn 9825: } else {
1.749 raeburn 9826: foreach my $key (keys(%{$current_permissions})) {
9827: if ($key =~ /\0accesscontrol$/) {
9828: if (defined($group)) {
9829: if ($key !~ m-^\Q$group\E/-) {
9830: next;
9831: }
9832: }
9833: my ($fullpath) = split(/\0/,$key);
9834: if (ref($$current_permissions{$key}) eq 'HASH') {
9835: foreach my $control (keys(%{$$current_permissions{$key}})) {
9836: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9837: }
9838: }
9839: }
9840: }
9841: }
9842: return %access;
9843: }
9844:
9845: sub modify_access_controls {
9846: my ($file_name,$changes,$domain,$user)=@_;
9847: my ($outcome,$deloutcome);
9848: my %store_permissions;
9849: my %new_values;
9850: my %new_control;
9851: my %translation;
9852: my @deletions = ();
9853: my $now = time;
9854: if (exists($$changes{'activate'})) {
9855: if (ref($$changes{'activate'}) eq 'HASH') {
9856: my @newitems = sort(keys(%{$$changes{'activate'}}));
9857: my $numnew = scalar(@newitems);
9858: for (my $i=0; $i<$numnew; $i++) {
9859: my $newkey = $newitems[$i];
9860: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9861: if ($newkey =~ /^\d+:/) {
9862: $newkey =~ s/^(\d+)/$newid/;
9863: $translation{$1} = $newid;
9864: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9865: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9866: $translation{$1} = $newid;
9867: }
1.749 raeburn 9868: $new_values{$file_name."\0".$newkey} =
9869: $$changes{'activate'}{$newitems[$i]};
9870: $new_control{$newkey} = $now;
9871: }
9872: }
9873: }
9874: my %todelete;
9875: my %changed_items;
9876: foreach my $action ('delete','update') {
9877: if (exists($$changes{$action})) {
9878: if (ref($$changes{$action}) eq 'HASH') {
9879: foreach my $key (keys(%{$$changes{$action}})) {
9880: my ($itemnum) = ($key =~ /^([^:]+):/);
9881: if ($action eq 'delete') {
9882: $todelete{$itemnum} = 1;
9883: } else {
9884: $changed_items{$itemnum} = $key;
9885: }
9886: }
1.745 raeburn 9887: }
9888: }
1.749 raeburn 9889: }
9890: # get lock on access controls for file.
9891: my $lockhash = {
9892: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9893: ':'.$env{'user.domain'},
9894: };
9895: my $tries = 0;
9896: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9897:
1.1172.2.79 raeburn 9898: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9899: $tries ++;
1.1172.2.79 raeburn 9900: sleep(0.1);
1.749 raeburn 9901: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9902: }
9903: if ($gotlock eq 'ok') {
9904: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9905: my ($tmp)=keys(%curr_permissions);
9906: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9907: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9908: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9909: if (ref($curr_controls) eq 'HASH') {
9910: foreach my $control_item (keys(%{$curr_controls})) {
9911: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9912: if (defined($todelete{$itemnum})) {
9913: push(@deletions,$file_name."\0".$control_item);
9914: } else {
9915: if (defined($changed_items{$itemnum})) {
9916: $new_control{$changed_items{$itemnum}} = $now;
9917: push(@deletions,$file_name."\0".$control_item);
9918: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9919: } else {
9920: $new_control{$control_item} = $$curr_controls{$control_item};
9921: }
9922: }
1.745 raeburn 9923: }
9924: }
9925: }
1.970 raeburn 9926: my ($group);
9927: if (&is_course($domain,$user)) {
9928: ($group,my $file) = split(/\//,$file_name,2);
9929: }
1.749 raeburn 9930: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9931: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9932: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9933: # remove lock
9934: my @del_lock = ($file_name."\0".'locked_access_records');
9935: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9936: my $sqlresult =
1.970 raeburn 9937: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9938: $group);
1.749 raeburn 9939: } else {
9940: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9941: }
1.749 raeburn 9942: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9943: }
9944:
1.827 raeburn 9945: sub make_public_indefinitely {
9946: my ($requrl) = @_;
9947: my $now = time;
9948: my $action = 'activate';
9949: my $aclnum = 0;
9950: if (&is_portfolio_url($requrl)) {
9951: my (undef,$udom,$unum,$file_name,$group) =
9952: &parse_portfolio_url($requrl);
9953: my $current_perms = &get_portfile_permissions($udom,$unum);
9954: my %access_controls = &get_access_controls($current_perms,
9955: $group,$file_name);
9956: foreach my $key (keys(%{$access_controls{$file_name}})) {
9957: my ($num,$scope,$end,$start) =
9958: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9959: if ($scope eq 'public') {
9960: if ($start <= $now && $end == 0) {
9961: $action = 'none';
9962: } else {
9963: $action = 'update';
9964: $aclnum = $num;
9965: }
9966: last;
9967: }
9968: }
9969: if ($action eq 'none') {
9970: return 'ok';
9971: } else {
9972: my %changes;
9973: my $newend = 0;
9974: my $newstart = $now;
9975: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9976: $changes{$action}{$newkey} = {
9977: type => 'public',
9978: time => {
9979: start => $newstart,
9980: end => $newend,
9981: },
9982: };
9983: my ($outcome,$deloutcome,$new_values,$translation) =
9984: &modify_access_controls($file_name,\%changes,$udom,$unum);
9985: return $outcome;
9986: }
9987: } else {
9988: return 'invalid';
9989: }
9990: }
9991:
1.745 raeburn 9992: #------------------------------------------------------Get Marked as Read Only
9993:
9994: sub get_marked_as_readonly {
9995: my ($domain,$user,$what,$group) = @_;
9996: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9997: my @readonly_files;
1.629 banghart 9998: my $cmp1=$what;
9999: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10000: while (my ($file_name,$value) = each(%{$current_permissions})) {
10001: if (defined($group)) {
10002: if ($file_name !~ m-^\Q$group\E/-) {
10003: next;
10004: }
10005: }
1.561 banghart 10006: if (ref($value) eq "ARRAY"){
10007: foreach my $stored_what (@{$value}) {
1.629 banghart 10008: my $cmp2=$stored_what;
1.759 albertel 10009: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10010: $cmp2=join('',@{$stored_what});
1.745 raeburn 10011: }
1.629 banghart 10012: if ($cmp1 eq $cmp2) {
1.561 banghart 10013: push(@readonly_files, $file_name);
1.745 raeburn 10014: last;
1.563 banghart 10015: } elsif (!defined($what)) {
10016: push(@readonly_files, $file_name);
1.745 raeburn 10017: last;
1.561 banghart 10018: }
10019: }
1.745 raeburn 10020: }
1.561 banghart 10021: }
10022: return @readonly_files;
10023: }
1.577 banghart 10024: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10025:
1.577 banghart 10026: sub get_marked_as_readonly_hash {
1.745 raeburn 10027: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10028: my %readonly_files;
1.745 raeburn 10029: while (my ($file_name,$value) = each(%{$current_permissions})) {
10030: if (defined($group)) {
10031: if ($file_name !~ m-^\Q$group\E/-) {
10032: next;
10033: }
10034: }
1.577 banghart 10035: if (ref($value) eq "ARRAY"){
10036: foreach my $stored_what (@{$value}) {
1.745 raeburn 10037: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10038: foreach my $lock_descriptor(@{$stored_what}) {
10039: if ($lock_descriptor eq 'graded') {
10040: $readonly_files{$file_name} = 'graded';
10041: } elsif ($lock_descriptor eq 'handback') {
10042: $readonly_files{$file_name} = 'handback';
10043: } else {
10044: if (!exists($readonly_files{$file_name})) {
10045: $readonly_files{$file_name} = 'locked';
10046: }
10047: }
1.745 raeburn 10048: }
1.750 banghart 10049: }
1.577 banghart 10050: }
10051: }
10052: }
10053: return %readonly_files;
10054: }
1.559 banghart 10055: # ------------------------------------------------------------ Unmark as Read Only
10056:
10057: sub unmark_as_readonly {
1.629 banghart 10058: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10059: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10060: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10061: $file_name = &declutter_portfile($file_name);
1.634 albertel 10062: my $symb_crs = $what;
10063: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10064: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10065: my ($tmp)=keys(%current_permissions);
10066: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10067: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10068: foreach my $file (@readonly_files) {
1.759 albertel 10069: my $clean_file = &declutter_portfile($file);
10070: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10071: my $current_locks = $current_permissions{$file};
1.563 banghart 10072: my @new_locks;
10073: my @del_keys;
10074: if (ref($current_locks) eq "ARRAY"){
10075: foreach my $locker (@{$current_locks}) {
1.632 albertel 10076: my $compare=$locker;
1.749 raeburn 10077: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10078: $compare=join('',@{$locker});
1.746 raeburn 10079: if ($compare ne $symb_crs) {
10080: push(@new_locks, $locker);
10081: }
1.563 banghart 10082: }
10083: }
1.650 albertel 10084: if (scalar(@new_locks) > 0) {
1.563 banghart 10085: $current_permissions{$file} = \@new_locks;
10086: } else {
10087: push(@del_keys, $file);
1.613 albertel 10088: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10089: delete($current_permissions{$file});
1.563 banghart 10090: }
10091: }
1.561 banghart 10092: }
1.613 albertel 10093: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10094: return;
10095: }
1.512 banghart 10096:
1.17 www 10097: # ------------------------------------------------------------ Directory lister
10098:
10099: sub dirlist {
1.955 raeburn 10100: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10101: $uri=~s/^\///;
10102: $uri=~s/\/$//;
1.253 stredwic 10103: my ($udom, $uname);
1.955 raeburn 10104: if ($getuserdir) {
1.253 stredwic 10105: $udom = $userdomain;
10106: $uname = $username;
1.955 raeburn 10107: } else {
10108: (undef,$udom,$uname)=split(/\//,$uri);
10109: if(defined($userdomain)) {
10110: $udom = $userdomain;
10111: }
10112: if(defined($username)) {
10113: $uname = $username;
10114: }
1.253 stredwic 10115: }
1.955 raeburn 10116: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10117:
1.955 raeburn 10118: $dirRoot = $perlvar{'lonDocRoot'};
10119: if (defined($getpropath)) {
10120: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10121: $dirRoot =~ s/\/$//;
1.955 raeburn 10122: } elsif (defined($getuserdir)) {
10123: my $subdir=$uname.'__';
10124: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10125: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10126: ."/$udom/$subdir/$uname";
10127: } elsif (defined($alternateRoot)) {
10128: $dirRoot = $alternateRoot;
1.751 banghart 10129: }
1.253 stredwic 10130:
10131: if($udom) {
10132: if($uname) {
1.1135 raeburn 10133: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10134: if ($uhome eq 'no_host') {
10135: return ([],'no_host');
10136: }
1.955 raeburn 10137: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10138: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10139: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10140: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10141: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10142: } else {
10143: @listing_results = map { &unescape($_); } split(/:/,$listing);
10144: }
1.605 matthew 10145: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10146: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10147: @listing_results = split(/:/,$listing);
10148: } else {
10149: @listing_results = map { &unescape($_); } split(/:/,$listing);
10150: }
1.1135 raeburn 10151: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10152: ($listing eq 'rejected') || ($listing eq 'refused') ||
10153: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10154: return ([],$listing);
10155: } else {
10156: return (\@listing_results);
1.1135 raeburn 10157: }
1.955 raeburn 10158: } elsif(!$alternateRoot) {
1.1136 raeburn 10159: my (%allusers,%listerror);
1.841 albertel 10160: my %servers = &get_servers($udom,'library');
1.955 raeburn 10161: foreach my $tryserver (keys(%servers)) {
10162: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10163: &escape($udom),$tryserver);
10164: if ($listing eq 'unknown_cmd') {
10165: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10166: $udom, $tryserver);
10167: } else {
10168: @listing_results = map { &unescape($_); } split(/:/,$listing);
10169: }
1.841 albertel 10170: if ($listing eq 'unknown_cmd') {
10171: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10172: $udom, $tryserver);
10173: @listing_results = split(/:/,$listing);
10174: } else {
10175: @listing_results =
10176: map { &unescape($_); } split(/:/,$listing);
10177: }
1.1136 raeburn 10178: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10179: ($listing eq 'rejected') || ($listing eq 'refused') ||
10180: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10181: $listerror{$tryserver} = $listing;
10182: } else {
1.841 albertel 10183: foreach my $line (@listing_results) {
10184: my ($entry) = split(/&/,$line,2);
10185: $allusers{$entry} = 1;
10186: }
10187: }
1.253 stredwic 10188: }
1.1136 raeburn 10189: my @alluserslist=();
1.800 albertel 10190: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10191: push(@alluserslist,$user.'&user');
1.253 stredwic 10192: }
1.1172.2.80 raeburn 10193: if (!%listerror) {
10194: # no errors
10195: return (\@alluserslist);
10196: } elsif (scalar(keys(%servers)) == 1) {
10197: # one library server, one error
10198: my ($key) = keys(%listerror);
10199: return (\@alluserslist, $listerror{$key});
10200: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10201: # con_lost indicates that we might miss data from at least one
10202: # library server
10203: return (\@alluserslist, 'con_lost');
10204: } else {
10205: # multiple library servers and no con_lost -> data should be
10206: # complete.
10207: return (\@alluserslist);
10208: }
10209:
1.253 stredwic 10210: } else {
1.1136 raeburn 10211: return ([],'missing username');
1.253 stredwic 10212: }
1.955 raeburn 10213: } elsif(!defined($getpropath)) {
1.1136 raeburn 10214: my $path = $perlvar{'lonDocRoot'}.'/res/';
10215: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10216: return (\@all_domains);
1.955 raeburn 10217: } else {
1.1136 raeburn 10218: return ([],'missing domain');
1.275 stredwic 10219: }
10220: }
10221:
10222: # --------------------------------------------- GetFileTimestamp
10223: # This function utilizes dirlist and returns the date stamp for
10224: # when it was last modified. It will also return an error of -1
10225: # if an error occurs
10226:
10227: sub GetFileTimestamp {
1.955 raeburn 10228: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10229: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10230: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10231: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10232: undef,$getuserdir);
10233: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10234: return -1;
10235: }
10236: if (ref($fileref) eq 'ARRAY') {
10237: my @stats = split('&',$fileref->[0]);
1.375 matthew 10238: # @stats contains first the filename, then the stat output
10239: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10240: } else {
10241: return -1;
1.253 stredwic 10242: }
1.26 www 10243: }
10244:
1.712 albertel 10245: sub stat_file {
10246: my ($uri) = @_;
1.787 albertel 10247: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10248:
1.955 raeburn 10249: my ($udom,$uname,$file);
1.712 albertel 10250: if ($uri =~ m-^/(uploaded|editupload)/-) {
10251: ($udom,$uname,$file) =
1.811 albertel 10252: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10253: $file = 'userfiles/'.$file;
10254: }
10255: if ($uri =~ m-^/res/-) {
10256: ($udom,$uname) =
1.807 albertel 10257: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10258: $file = $uri;
10259: }
10260:
10261: if (!$udom || !$uname || !$file) {
10262: # unable to handle the uri
10263: return ();
10264: }
1.956 raeburn 10265: my $getpropath;
10266: if ($file =~ /^userfiles\//) {
10267: $getpropath = 1;
10268: }
1.1136 raeburn 10269: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10270: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10271: return ();
10272: } else {
10273: if (ref($listref) eq 'ARRAY') {
10274: my @stats = split('&',$listref->[0]);
10275: shift(@stats); #filename is first
10276: return @stats;
10277: }
1.712 albertel 10278: }
10279: return ();
10280: }
10281:
1.26 www 10282: # -------------------------------------------------------- Value of a Condition
10283:
1.713 albertel 10284: # gets the value of a specific preevaluated condition
10285: # stored in the string $env{user.state.<cid>}
10286: # or looks up a condition reference in the bighash and if if hasn't
10287: # already been evaluated recurses into docondval to get the value of
10288: # the condition, then memoizing it to
10289: # $env{user.state.<cid>.<condition>}
1.40 www 10290: sub directcondval {
10291: my $number=shift;
1.620 albertel 10292: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10293: &Apache::lonuserstate::evalstate();
10294: }
1.713 albertel 10295: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10296: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10297: } elsif ($number =~ /^_/) {
10298: my $sub_condition;
10299: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10300: &GDBM_READER(),0640)) {
10301: $sub_condition=$bighash{'conditions'.$number};
10302: untie(%bighash);
10303: }
10304: my $value = &docondval($sub_condition);
1.949 raeburn 10305: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10306: return $value;
10307: }
1.620 albertel 10308: if ($env{'user.state.'.$env{'request.course.id'}}) {
10309: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10310: } else {
10311: return 2;
10312: }
10313: }
10314:
1.713 albertel 10315: # get the collection of conditions for this resource
1.26 www 10316: sub condval {
10317: my $condidx=shift;
1.54 www 10318: my $allpathcond='';
1.713 albertel 10319: foreach my $cond (split(/\|/,$condidx)) {
10320: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10321: $allpathcond.=
10322: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10323: }
1.191 harris41 10324: }
1.54 www 10325: $allpathcond=~s/\|$//;
1.713 albertel 10326: return &docondval($allpathcond);
10327: }
10328:
10329: #evaluates an expression of conditions
10330: sub docondval {
10331: my ($allpathcond) = @_;
10332: my $result=0;
10333: if ($env{'request.course.id'}
10334: && defined($allpathcond)) {
10335: my $operand='|';
10336: my @stack;
10337: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10338: if ($chunk eq '(') {
10339: push @stack,($operand,$result);
10340: } elsif ($chunk eq ')') {
10341: my $before=pop @stack;
10342: if (pop @stack eq '&') {
10343: $result=$result>$before?$before:$result;
10344: } else {
10345: $result=$result>$before?$result:$before;
10346: }
10347: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10348: $operand=$chunk;
10349: } else {
10350: my $new=directcondval($chunk);
10351: if ($operand eq '&') {
10352: $result=$result>$new?$new:$result;
10353: } else {
10354: $result=$result>$new?$result:$new;
10355: }
10356: }
10357: }
1.26 www 10358: }
10359: return $result;
1.421 albertel 10360: }
10361:
10362: # ---------------------------------------------------- Devalidate courseresdata
10363:
10364: sub devalidatecourseresdata {
10365: my ($coursenum,$coursedomain)=@_;
10366: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10367: &devalidate_cache_new('courseres',$hashid);
1.28 www 10368: }
10369:
1.763 www 10370:
1.200 www 10371: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10372: #
10373: # Parameters:
10374: # $coursenum - Number of the course.
10375: # $coursedomain - Domain at which the course was created.
10376: # Returns:
10377: # A hash of the course parameters along (I think) with timestamps
10378: # and version info.
1.877 foxr 10379:
1.624 albertel 10380: sub get_courseresdata {
10381: my ($coursenum,$coursedomain)=@_;
1.200 www 10382: my $coursehom=&homeserver($coursenum,$coursedomain);
10383: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10384: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10385: my %dumpreply;
1.417 albertel 10386: unless (defined($cached)) {
1.624 albertel 10387: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10388: $result=\%dumpreply;
1.251 albertel 10389: my ($tmp) = keys(%dumpreply);
10390: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10391: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10392: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10393: return $tmp;
1.416 albertel 10394: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10395: $result=undef;
1.599 albertel 10396: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10397: }
10398: }
1.624 albertel 10399: return $result;
10400: }
10401:
1.633 albertel 10402: sub devalidateuserresdata {
10403: my ($uname,$udom)=@_;
10404: my $hashid="$udom:$uname";
10405: &devalidate_cache_new('userres',$hashid);
10406: }
10407:
1.624 albertel 10408: sub get_userresdata {
10409: my ($uname,$udom)=@_;
10410: #most student don\'t have any data set, check if there is some data
10411: if (&EXT_cache_status($udom,$uname)) { return undef; }
10412:
10413: my $hashid="$udom:$uname";
10414: my ($result,$cached)=&is_cached_new('userres',$hashid);
10415: if (!defined($cached)) {
10416: my %resourcedata=&dump('resourcedata',$udom,$uname);
10417: $result=\%resourcedata;
10418: &do_cache_new('userres',$hashid,$result,600);
10419: }
10420: my ($tmp)=keys(%$result);
10421: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10422: return $result;
10423: }
10424: #error 2 occurs when the .db doesn't exist
10425: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10426: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10427: &logthis("<font color=\"blue\">WARNING:".
10428: " Trying to get resource data for ".
10429: $uname." at ".$udom.": ".
10430: $tmp."</font>");
10431: }
1.624 albertel 10432: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10433: #&EXT_cache_set($udom,$uname);
10434: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10435: undef($tmp); # not really an error so don't send it back
1.624 albertel 10436: }
10437: return $tmp;
10438: }
1.879 foxr 10439: #----------------------------------------------- resdata - return resource data
10440: # Purpose:
10441: # Return resource data for either users or for a course.
10442: # Parameters:
10443: # $name - Course/user name.
10444: # $domain - Name of the domain the user/course is registered on.
10445: # $type - Type of thing $name is (must be 'course' or 'user'
10446: # @which - Array of names of resources desired.
10447: # Returns:
10448: # The value of the first reasource in @which that is found in the
10449: # resource hash.
10450: # Exceptional Conditions:
10451: # If the $type passed in is not valid (not the string 'course' or
10452: # 'user', an undefined reference is returned.
10453: # If none of the resources are found, an undef is returned
1.624 albertel 10454: sub resdata {
10455: my ($name,$domain,$type,@which)=@_;
10456: my $result;
10457: if ($type eq 'course') {
10458: $result=&get_courseresdata($name,$domain);
10459: } elsif ($type eq 'user') {
10460: $result=&get_userresdata($name,$domain);
10461: }
10462: if (!ref($result)) { return $result; }
1.251 albertel 10463: foreach my $item (@which) {
1.927 albertel 10464: if (defined($result->{$item->[0]})) {
10465: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10466: }
1.250 albertel 10467: }
1.291 albertel 10468: return undef;
1.200 www 10469: }
10470:
1.1172.2.31 raeburn 10471: sub get_numsuppfiles {
10472: my ($cnum,$cdom,$ignorecache)=@_;
10473: my $hashid=$cnum.':'.$cdom;
10474: my ($suppcount,$cached);
10475: unless ($ignorecache) {
10476: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10477: }
10478: unless (defined($cached)) {
10479: my $chome=&homeserver($cnum,$cdom);
10480: unless ($chome eq 'no_host') {
10481: ($suppcount,my $errors) = (0,0);
10482: my $suppmap = 'supplemental.sequence';
10483: ($suppcount,$errors) =
10484: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10485: }
10486: &do_cache_new('suppcount',$hashid,$suppcount,600);
10487: }
10488: return $suppcount;
10489: }
10490:
1.379 matthew 10491: #
10492: # EXT resource caching routines
10493: #
10494:
10495: sub clear_EXT_cache_status {
1.383 albertel 10496: &delenv('cache.EXT.');
1.379 matthew 10497: }
10498:
10499: sub EXT_cache_status {
10500: my ($target_domain,$target_user) = @_;
1.383 albertel 10501: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10502: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10503: # We know already the user has no data
10504: return 1;
10505: } else {
10506: return 0;
10507: }
10508: }
10509:
10510: sub EXT_cache_set {
10511: my ($target_domain,$target_user) = @_;
1.383 albertel 10512: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10513: #&appenv({$cachename => time});
1.379 matthew 10514: }
10515:
1.28 www 10516: # --------------------------------------------------------- Value of a Variable
1.58 www 10517: sub EXT {
1.715 albertel 10518:
1.1172.2.28 raeburn 10519: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10520: unless ($varname) { return ''; }
1.218 albertel 10521: #get real user name/domain, courseid and symb
10522: my $courseid;
1.359 albertel 10523: my $publicuser;
1.427 www 10524: if ($symbparm) {
10525: $symbparm=&get_symb_from_alias($symbparm);
10526: }
1.218 albertel 10527: if (!($uname && $udom)) {
1.790 albertel 10528: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10529: if (!$symbparm) { $symbparm=$cursymb; }
10530: } else {
1.620 albertel 10531: $courseid=$env{'request.course.id'};
1.218 albertel 10532: }
1.48 www 10533: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10534: my $rest;
1.320 albertel 10535: if (defined($therest[0])) {
1.48 www 10536: $rest=join('.',@therest);
10537: } else {
10538: $rest='';
10539: }
1.320 albertel 10540:
1.57 www 10541: my $qualifierrest=$qualifier;
10542: if ($rest) { $qualifierrest.='.'.$rest; }
10543: my $spacequalifierrest=$space;
10544: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10545: if ($realm eq 'user') {
1.48 www 10546: # --------------------------------------------------------------- user.resource
10547: if ($space eq 'resource') {
1.651 albertel 10548: if ( (defined($Apache::lonhomework::parsing_a_problem)
10549: || defined($Apache::lonhomework::parsing_a_task))
10550: &&
1.744 albertel 10551: ($symbparm eq &symbread()) ) {
10552: # if we are in the middle of processing the resource the
10553: # get the value we are planning on committing
10554: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10555: return $Apache::lonhomework::results{$qualifierrest};
10556: } else {
10557: return $Apache::lonhomework::history{$qualifierrest};
10558: }
1.335 albertel 10559: } else {
1.359 albertel 10560: my %restored;
1.620 albertel 10561: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10562: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10563: } else {
10564: %restored=&restore($symbparm,$courseid,$udom,$uname);
10565: }
1.335 albertel 10566: return $restored{$qualifierrest};
10567: }
1.48 www 10568: # ----------------------------------------------------------------- user.access
10569: } elsif ($space eq 'access') {
1.218 albertel 10570: # FIXME - not supporting calls for a specific user
1.48 www 10571: return &allowed($qualifier,$rest);
10572: # ------------------------------------------ user.preferences, user.environment
10573: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10574: if (($uname eq $env{'user.name'}) &&
10575: ($udom eq $env{'user.domain'})) {
10576: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10577: } else {
1.359 albertel 10578: my %returnhash;
10579: if (!$publicuser) {
10580: %returnhash=&userenvironment($udom,$uname,
10581: $qualifierrest);
10582: }
1.218 albertel 10583: return $returnhash{$qualifierrest};
10584: }
1.48 www 10585: # ----------------------------------------------------------------- user.course
10586: } elsif ($space eq 'course') {
1.218 albertel 10587: # FIXME - not supporting calls for a specific user
1.620 albertel 10588: return $env{join('.',('request.course',$qualifier))};
1.48 www 10589: # ------------------------------------------------------------------- user.role
10590: } elsif ($space eq 'role') {
1.218 albertel 10591: # FIXME - not supporting calls for a specific user
1.620 albertel 10592: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10593: if ($qualifier eq 'value') {
10594: return $role;
10595: } elsif ($qualifier eq 'extent') {
10596: return $where;
10597: }
10598: # ----------------------------------------------------------------- user.domain
10599: } elsif ($space eq 'domain') {
1.218 albertel 10600: return $udom;
1.48 www 10601: # ------------------------------------------------------------------- user.name
10602: } elsif ($space eq 'name') {
1.218 albertel 10603: return $uname;
1.48 www 10604: # ---------------------------------------------------- Any other user namespace
1.29 www 10605: } else {
1.359 albertel 10606: my %reply;
10607: if (!$publicuser) {
10608: %reply=&get($space,[$qualifierrest],$udom,$uname);
10609: }
10610: return $reply{$qualifierrest};
1.48 www 10611: }
1.236 www 10612: } elsif ($realm eq 'query') {
10613: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10614: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10615: [$spacequalifierrest]);
1.620 albertel 10616: return $env{'form.'.$spacequalifierrest};
1.236 www 10617: } elsif ($realm eq 'request') {
1.48 www 10618: # ------------------------------------------------------------- request.browser
10619: if ($space eq 'browser') {
1.1145 bisitz 10620: return $env{'browser.'.$qualifier};
1.57 www 10621: # ------------------------------------------------------------ request.filename
10622: } else {
1.620 albertel 10623: return $env{'request.'.$spacequalifierrest};
1.29 www 10624: }
1.28 www 10625: } elsif ($realm eq 'course') {
1.48 www 10626: # ---------------------------------------------------------- course.description
1.620 albertel 10627: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10628: } elsif ($realm eq 'resource') {
1.165 www 10629:
1.620 albertel 10630: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10631: if (!$symbparm) { $symbparm=&symbread(); }
10632: }
1.693 albertel 10633:
1.1172.2.30 raeburn 10634: if ($qualifier eq '') {
10635: if ($space eq 'title') {
10636: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10637: return &gettitle($symbparm);
10638: }
1.693 albertel 10639:
1.1172.2.30 raeburn 10640: if ($space eq 'map') {
10641: my ($map) = &decode_symb($symbparm);
10642: return &symbread($map);
10643: }
10644: if ($space eq 'maptitle') {
10645: my ($map) = &decode_symb($symbparm);
10646: return &gettitle($map);
10647: }
10648: if ($space eq 'filename') {
10649: if ($symbparm) {
10650: return &clutter((&decode_symb($symbparm))[2]);
10651: }
10652: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10653: }
1.1172.2.30 raeburn 10654:
10655: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10656: if ($space eq 'visibleparts') {
10657: my $navmap = Apache::lonnavmaps::navmap->new();
10658: my $item;
10659: if (ref($navmap)) {
10660: my $res = $navmap->getBySymb($symbparm);
10661: my $parts = $res->parts();
10662: if (ref($parts) eq 'ARRAY') {
10663: $item = join(',',@{$parts});
10664: }
10665: undef($navmap);
10666: }
10667: return $item;
10668: }
10669: }
10670: }
1.693 albertel 10671:
10672: my ($section, $group, @groups);
1.593 albertel 10673: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10674: if (($courseid eq '') && ($cid)) {
10675: $courseid = $cid;
10676: }
10677: if (($symbparm && $courseid) &&
10678: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10679:
1.218 albertel 10680: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10681:
1.60 www 10682: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10683: my $symbp=$symbparm;
1.735 albertel 10684: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10685:
10686: my $symbparm=$symbp.'.'.$spacequalifierrest;
10687: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10688:
1.620 albertel 10689: if (($env{'user.name'} eq $uname) &&
10690: ($env{'user.domain'} eq $udom)) {
10691: $section=$env{'request.course.sec'};
1.733 raeburn 10692: @groups = split(/:/,$env{'request.course.groups'});
10693: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10694: } else {
1.539 albertel 10695: if (! defined($usection)) {
1.551 albertel 10696: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10697: } else {
10698: $section = $usection;
10699: }
1.733 raeburn 10700: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10701: }
10702:
10703: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10704: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10705: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10706:
1.593 albertel 10707: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10708: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10709: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10710:
1.60 www 10711: # ----------------------------------------------------------- first, check user
1.624 albertel 10712:
10713: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10714: ([$courselevelr,'resource'],
10715: [$courselevelm,'map' ],
10716: [$courselevel, 'course' ]));
1.931 albertel 10717: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10718:
1.594 albertel 10719: # ------------------------------------------------ second, check some of course
1.684 raeburn 10720: my $coursereply;
1.691 raeburn 10721: if (@groups > 0) {
10722: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10723: $mapparm,$spacequalifierrest);
1.927 albertel 10724: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10725: }
1.96 www 10726:
1.684 raeburn 10727: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10728: $env{'course.'.$courseid.'.domain'},
10729: 'course',
10730: ([$seclevelr, 'resource'],
10731: [$seclevelm, 'map' ],
10732: [$seclevel, 'course' ],
10733: [$courselevelr,'resource']));
10734: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10735:
1.60 www 10736: # ------------------------------------------------------ third, check map parms
1.218 albertel 10737: my %parmhash=();
10738: my $thisparm='';
10739: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10740: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10741: &GDBM_READER(),0640)) {
1.218 albertel 10742: $thisparm=$parmhash{$symbparm};
10743: untie(%parmhash);
10744: }
1.927 albertel 10745: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10746: }
1.594 albertel 10747: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10748:
1.218 albertel 10749: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10750: my $filename;
10751: if (!$symbparm) { $symbparm=&symbread(); }
10752: if ($symbparm) {
1.409 www 10753: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10754: } else {
1.620 albertel 10755: $filename=$env{'request.filename'};
1.282 albertel 10756: }
10757: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10758: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10759: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10760: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10761:
1.927 albertel 10762: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10763: if ($symbparm && defined($courseid) &&
1.620 albertel 10764: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10765: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10766: $env{'course.'.$courseid.'.domain'},
10767: 'course',
1.927 albertel 10768: ([$courselevelm,'map' ],
10769: [$courselevel, 'course']));
10770: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10771: }
1.145 www 10772: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10773: unless ($space eq '0') {
1.336 albertel 10774: my @parts=split(/_/,$space);
10775: my $id=pop(@parts);
10776: my $part=join('_',@parts);
10777: if ($part eq '') { $part='0'; }
1.927 albertel 10778: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10779: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10780: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10781: }
1.395 albertel 10782: if ($recurse) { return undef; }
10783: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10784: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10785: # ---------------------------------------------------- Any other user namespace
10786: } elsif ($realm eq 'environment') {
10787: # ----------------------------------------------------------------- environment
1.620 albertel 10788: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10789: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10790: } else {
1.770 albertel 10791: if ($uname eq 'anonymous' && $udom eq '') {
10792: return '';
10793: }
1.219 albertel 10794: my %returnhash=&userenvironment($udom,$uname,
10795: $spacequalifierrest);
10796: return $returnhash{$spacequalifierrest};
10797: }
1.28 www 10798: } elsif ($realm eq 'system') {
1.48 www 10799: # ----------------------------------------------------------------- system.time
10800: if ($space eq 'time') {
10801: return time;
10802: }
1.696 albertel 10803: } elsif ($realm eq 'server') {
10804: # ----------------------------------------------------------------- system.time
10805: if ($space eq 'name') {
10806: return $ENV{'SERVER_NAME'};
10807: }
1.28 www 10808: }
1.48 www 10809: return '';
1.61 www 10810: }
10811:
1.927 albertel 10812: sub get_reply {
10813: my ($reply_value) = @_;
1.940 raeburn 10814: if (ref($reply_value) eq 'ARRAY') {
10815: if (wantarray) {
10816: return @$reply_value;
10817: }
10818: return $reply_value->[0];
10819: } else {
10820: return $reply_value;
1.927 albertel 10821: }
10822: }
10823:
1.691 raeburn 10824: sub check_group_parms {
10825: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10826: my @groupitems = ();
10827: my $resultitem;
1.927 albertel 10828: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10829: foreach my $group (@{$groups}) {
10830: foreach my $level (@levels) {
1.927 albertel 10831: my $item = $courseid.'.['.$group.'].'.$level->[0];
10832: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10833: }
10834: }
10835: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10836: $env{'course.'.$courseid.'.domain'},
10837: 'course',@groupitems);
10838: return $coursereply;
10839: }
10840:
10841: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10842: my ($courseid,@groups) = @_;
10843: @groups = sort(@groups);
1.691 raeburn 10844: return @groups;
10845: }
10846:
1.395 albertel 10847: sub packages_tab_default {
10848: my ($uri,$varname)=@_;
10849: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10850:
10851: my (@extension,@specifics,$do_default);
10852: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10853: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10854: if ($pack_type eq 'default') {
10855: $do_default=1;
10856: } elsif ($pack_type eq 'extension') {
10857: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10858: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10859: # only look at packages defaults for packages that this id is
1.738 albertel 10860: push(@specifics,[$package,$pack_type,$pack_part]);
10861: }
10862: }
10863: # first look for a package that matches the requested part id
10864: foreach my $package (@specifics) {
10865: my (undef,$pack_type,$pack_part)=@{$package};
10866: next if ($pack_part ne $part);
10867: if (defined($packagetab{"$pack_type&$name&default"})) {
10868: return $packagetab{"$pack_type&$name&default"};
10869: }
10870: }
10871: # look for any possible matching non extension_ package
10872: foreach my $package (@specifics) {
10873: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10874: if (defined($packagetab{"$pack_type&$name&default"})) {
10875: return $packagetab{"$pack_type&$name&default"};
10876: }
1.585 albertel 10877: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10878: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10879: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10880: }
10881: }
1.738 albertel 10882: # look for any posible extension_ match
10883: foreach my $package (@extension) {
10884: my ($package,$pack_type)=@{$package};
10885: if (defined($packagetab{"$pack_type&$name&default"})) {
10886: return $packagetab{"$pack_type&$name&default"};
10887: }
10888: if (defined($packagetab{$package."&$name&default"})) {
10889: return $packagetab{$package."&$name&default"};
10890: }
10891: }
10892: # look for a global default setting
10893: if ($do_default && defined($packagetab{"default&$name&default"})) {
10894: return $packagetab{"default&$name&default"};
10895: }
1.395 albertel 10896: return undef;
10897: }
10898:
1.334 albertel 10899: sub add_prefix_and_part {
10900: my ($prefix,$part)=@_;
10901: my $keyroot;
10902: if (defined($prefix) && $prefix !~ /^__/) {
10903: # prefix that has a part already
10904: $keyroot=$prefix;
10905: } elsif (defined($prefix)) {
10906: # prefix that is missing a part
10907: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10908: } else {
10909: # no prefix at all
10910: if (defined($part)) { $keyroot='_'.$part; }
10911: }
10912: return $keyroot;
10913: }
10914:
1.71 www 10915: # ---------------------------------------------------------------- Get metadata
10916:
1.599 albertel 10917: my %metaentry;
1.1070 www 10918: my %importedpartids;
1.71 www 10919: sub metadata {
1.176 www 10920: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10921: $uri=&declutter($uri);
1.288 albertel 10922: # if it is a non metadata possible uri return quickly
1.529 albertel 10923: if (($uri eq '') ||
10924: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10925: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10926: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10927: return undef;
10928: }
1.1172.2.49 raeburn 10929: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10930: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10931: return undef;
1.288 albertel 10932: }
1.73 www 10933: my $filename=$uri;
10934: $uri=~s/\.meta$//;
1.172 www 10935: #
10936: # Is the metadata already cached?
1.177 www 10937: # Look at timestamp of caching
1.172 www 10938: # Everything is cached by the main uri, libraries are never directly cached
10939: #
1.428 albertel 10940: if (!defined($liburi)) {
1.599 albertel 10941: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10942: if (defined($cached)) { return $result->{':'.$what}; }
10943: }
10944: {
1.1069 www 10945: # Imported parts would go here
1.1070 www 10946: my %importedids=();
10947: my @origfileimportpartids=();
1.1069 www 10948: my $importedparts=0;
1.172 www 10949: #
10950: # Is this a recursive call for a library?
10951: #
1.599 albertel 10952: # if (! exists($metacache{$uri})) {
10953: # $metacache{$uri}={};
10954: # }
1.924 albertel 10955: my $cachetime = 60*60;
1.171 www 10956: if ($liburi) {
10957: $liburi=&declutter($liburi);
10958: $filename=$liburi;
1.401 bowersj2 10959: } else {
1.599 albertel 10960: &devalidate_cache_new('meta',$uri);
10961: undef(%metaentry);
1.401 bowersj2 10962: }
1.140 www 10963: my %metathesekeys=();
1.73 www 10964: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10965: my $metastring;
1.1140 www 10966: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10967: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10968: $metastring =
1.929 albertel 10969: &Apache::lonnet::ssi_body($which,
1.924 albertel 10970: ('grade_target' => 'meta'));
10971: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10972: } elsif (($uri !~ m -^(editupload)/-) &&
10973: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10974: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10975: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10976: $metastring=&getfile($file);
1.489 albertel 10977: }
1.208 albertel 10978: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10979: my $token;
1.140 www 10980: undef %metathesekeys;
1.71 www 10981: while ($token=$parser->get_token) {
1.339 albertel 10982: if ($token->[0] eq 'S') {
10983: if (defined($token->[2]->{'package'})) {
1.172 www 10984: #
10985: # This is a package - get package info
10986: #
1.339 albertel 10987: my $package=$token->[2]->{'package'};
10988: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10989: if (defined($token->[2]->{'id'})) {
10990: $keyroot.='_'.$token->[2]->{'id'};
10991: }
1.599 albertel 10992: if ($metaentry{':packages'}) {
10993: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10994: } else {
1.599 albertel 10995: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10996: }
1.736 albertel 10997: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10998: my $part=$keyroot;
10999: $part=~s/^\_//;
1.736 albertel 11000: if ($pack_entry=~/^\Q$package\E\&/ ||
11001: $pack_entry=~/^\Q$package\E_0\&/) {
11002: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11003: # ignore package.tab specified default values
11004: # here &package_tab_default() will fetch those
11005: if ($subp eq 'default') { next; }
1.736 albertel 11006: my $value=$packagetab{$pack_entry};
1.432 albertel 11007: my $unikey;
11008: if ($pack =~ /_0$/) {
11009: $unikey='parameter_0_'.$name;
11010: $part=0;
11011: } else {
11012: $unikey='parameter'.$keyroot.'_'.$name;
11013: }
1.339 albertel 11014: if ($subp eq 'display') {
11015: $value.=' [Part: '.$part.']';
11016: }
1.599 albertel 11017: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11018: $metathesekeys{$unikey}=1;
1.599 albertel 11019: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11020: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11021: }
1.599 albertel 11022: if (defined($metaentry{':'.$unikey.'.default'})) {
11023: $metaentry{':'.$unikey}=
11024: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11025: }
1.339 albertel 11026: }
11027: }
11028: } else {
1.172 www 11029: #
11030: # This is not a package - some other kind of start tag
1.339 albertel 11031: #
11032: my $entry=$token->[1];
1.1068 www 11033: my $unikey='';
1.175 www 11034:
1.339 albertel 11035: if ($entry eq 'import') {
1.175 www 11036: #
11037: # Importing a library here
1.339 albertel 11038: #
1.1067 www 11039: my $location=$parser->get_text('/import');
11040: my $dir=$filename;
11041: $dir=~s|[^/]*$||;
11042: $location=&filelocation($dir,$location);
1.1069 www 11043:
1.1068 www 11044: my $importmode=$token->[2]->{'importmode'};
11045: if ($importmode eq 'problem') {
1.1069 www 11046: # Import as problem/response
1.1068 www 11047: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11048: } elsif ($importmode eq 'part') {
11049: # Import as part(s)
1.1069 www 11050: $importedparts=1;
11051: # We need to get the original file and the imported file to get the part order correct
11052: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11053: # Load and inspect original file
1.1070 www 11054: if ($#origfileimportpartids<0) {
11055: undef(%importedpartids);
11056: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11057: my $origfile=&getfile($origfilelocation);
11058: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11059: }
11060:
1.1069 www 11061: # Load and inspect imported file
11062: my $impfile=&getfile($location);
11063: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11064: if ($#impfilepartids>=0) {
11065: # This problem had parts
1.1070 www 11066: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11067: } else {
11068: # Importing by turning a single problem into a problem part
11069: # It gets the import-tags ID as part-ID
11070: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11071: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11072: }
1.1068 www 11073: } else {
11074: # Normal import
11075: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11076: if (defined($token->[2]->{'id'})) {
11077: $unikey.='_'.$token->[2]->{'id'};
11078: }
1.1067 www 11079: }
11080:
1.339 albertel 11081: if ($depthcount<20) {
1.736 albertel 11082: my $metadata =
11083: &metadata($uri,'keys', $location,$unikey,
11084: $depthcount+1);
11085: foreach my $meta (split(',',$metadata)) {
11086: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11087: $metathesekeys{$meta}=1;
1.339 albertel 11088: }
1.1068 www 11089:
11090: }
1.1067 www 11091: } else {
11092: #
11093: # Not importing, some other kind of non-package, non-library start tag
11094: #
11095: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11096: if (defined($token->[2]->{'id'})) {
11097: $unikey.='_'.$token->[2]->{'id'};
11098: }
1.339 albertel 11099: if (defined($token->[2]->{'name'})) {
11100: $unikey.='_'.$token->[2]->{'name'};
11101: }
11102: $metathesekeys{$unikey}=1;
1.736 albertel 11103: foreach my $param (@{$token->[3]}) {
11104: $metaentry{':'.$unikey.'.'.$param} =
11105: $token->[2]->{$param};
1.339 albertel 11106: }
11107: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11108: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11109: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11110: # only ws inside the tag, and not in default, so use default
11111: # as value
1.599 albertel 11112: $metaentry{':'.$unikey}=$default;
1.908 albertel 11113: } elsif ( $internaltext =~ /\S/ ) {
11114: # something interesting inside the tag
11115: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11116: } else {
1.908 albertel 11117: # no interesting values, don't set a default
1.339 albertel 11118: }
1.172 www 11119: # end of not-a-package not-a-library import
1.339 albertel 11120: }
1.172 www 11121: # end of not-a-package start tag
1.339 albertel 11122: }
1.172 www 11123: # the next is the end of "start tag"
1.339 albertel 11124: }
11125: }
1.483 albertel 11126: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11127: $extension = lc($extension);
11128: if ($extension eq 'htm') { $extension='html'; }
11129:
1.737 albertel 11130: foreach my $key (keys(%packagetab)) {
1.483 albertel 11131: #no specific packages #how's our extension
11132: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11133: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11134: \%metathesekeys);
11135: }
1.883 albertel 11136:
11137: if (!exists($metaentry{':packages'})
11138: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11139: foreach my $key (keys(%packagetab)) {
1.483 albertel 11140: #no specific packages well let's get default then
11141: if ($key!~/^default&/) { next; }
1.488 albertel 11142: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11143: \%metathesekeys);
11144: }
11145: }
1.338 www 11146: # are there custom rights to evaluate
1.599 albertel 11147: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11148:
1.338 www 11149: #
11150: # Importing a rights file here
1.339 albertel 11151: #
11152: unless ($depthcount) {
1.599 albertel 11153: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11154: my $dir=$filename;
11155: $dir=~s|[^/]*$||;
11156: $location=&filelocation($dir,$location);
1.736 albertel 11157: my $rights_metadata =
11158: &metadata($uri,'keys',$location,'_rights',
11159: $depthcount+1);
11160: foreach my $rights (split(',',$rights_metadata)) {
11161: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11162: $metathesekeys{$rights}=1;
1.339 albertel 11163: }
11164: }
11165: }
1.737 albertel 11166: # uniqifiy package listing
11167: my %seen;
11168: my @uniq_packages =
11169: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11170: $metaentry{':packages'} = join(',',@uniq_packages);
11171:
1.1070 www 11172: if ($importedparts) {
11173: # We had imported parts and need to rebuild partorder
11174: $metaentry{':partorder'}='';
11175: $metathesekeys{'partorder'}=1;
11176: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11177: if ($origfileimportpartids[$index] eq 'part') {
11178: # original part, part of the problem
11179: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11180: } else {
11181: # we have imported parts at this position
11182: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11183: }
11184: }
11185: $metaentry{':partorder'}=~s/^\,//;
11186: }
11187:
1.737 albertel 11188: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11189: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11190: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11191: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11192: # this is the end of "was not already recently cached
1.71 www 11193: }
1.599 albertel 11194: return $metaentry{':'.$what};
1.261 albertel 11195: }
11196:
1.488 albertel 11197: sub metadata_create_package_def {
1.483 albertel 11198: my ($uri,$key,$package,$metathesekeys)=@_;
11199: my ($pack,$name,$subp)=split(/\&/,$key);
11200: if ($subp eq 'default') { next; }
11201:
1.599 albertel 11202: if (defined($metaentry{':packages'})) {
11203: $metaentry{':packages'}.=','.$package;
1.483 albertel 11204: } else {
1.599 albertel 11205: $metaentry{':packages'}=$package;
1.483 albertel 11206: }
11207: my $value=$packagetab{$key};
11208: my $unikey;
11209: $unikey='parameter_0_'.$name;
1.599 albertel 11210: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11211: $$metathesekeys{$unikey}=1;
1.599 albertel 11212: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11213: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11214: }
1.599 albertel 11215: if (defined($metaentry{':'.$unikey.'.default'})) {
11216: $metaentry{':'.$unikey}=
11217: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11218: }
11219: }
11220:
1.261 albertel 11221: sub metadata_generate_part0 {
11222: my ($metadata,$metacache,$uri) = @_;
11223: my %allnames;
1.737 albertel 11224: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11225: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11226: my $part=$$metacache{':'.$metakey.'.part'};
11227: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11228: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11229: $allnames{$name}=$part;
11230: }
11231: }
11232: }
11233: foreach my $name (keys(%allnames)) {
11234: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11235: my $key=":parameter_0_$name";
1.261 albertel 11236: $$metacache{"$key.part"}='0';
11237: $$metacache{"$key.name"}=$name;
1.428 albertel 11238: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11239: $allnames{$name}.'_'.$name.
11240: '.type'};
1.428 albertel 11241: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11242: '.display'};
1.644 www 11243: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11244: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11245: $$metacache{"$key.display"}=$olddis;
11246: }
1.71 www 11247: }
11248:
1.764 albertel 11249: # ------------------------------------------------------ Devalidate title cache
11250:
11251: sub devalidate_title_cache {
11252: my ($url)=@_;
11253: if (!$env{'request.course.id'}) { return; }
11254: my $symb=&symbread($url);
11255: if (!$symb) { return; }
11256: my $key=$env{'request.course.id'}."\0".$symb;
11257: &devalidate_cache_new('title',$key);
11258: }
11259:
1.1014 droeschl 11260: # ------------------------------------------------- Get the title of a course
11261:
11262: sub current_course_title {
11263: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11264: }
1.301 www 11265: # ------------------------------------------------- Get the title of a resource
11266:
11267: sub gettitle {
11268: my $urlsymb=shift;
11269: my $symb=&symbread($urlsymb);
1.534 albertel 11270: if ($symb) {
1.620 albertel 11271: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11272: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11273: if (defined($cached)) {
11274: return $result;
11275: }
1.534 albertel 11276: my ($map,$resid,$url)=&decode_symb($symb);
11277: my $title='';
1.907 albertel 11278: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11279: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11280: } else {
11281: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11282: &GDBM_READER(),0640)) {
11283: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11284: $title=$bighash{'title_'.$mapid.'.'.$resid};
11285: untie(%bighash);
11286: }
1.534 albertel 11287: }
11288: $title=~s/\&colon\;/\:/gs;
11289: if ($title) {
1.1159 www 11290: # Remember both $symb and $title for dynamic metadata
11291: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11292: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11293: # Cache this title and then return it
1.599 albertel 11294: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11295: }
11296: $urlsymb=$url;
11297: }
11298: my $title=&metadata($urlsymb,'title');
11299: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11300: return $title;
1.301 www 11301: }
1.613 albertel 11302:
1.614 albertel 11303: sub get_slot {
11304: my ($which,$cnum,$cdom)=@_;
11305: if (!$cnum || !$cdom) {
1.790 albertel 11306: (undef,my $courseid)=&whichuser();
1.620 albertel 11307: $cdom=$env{'course.'.$courseid.'.domain'};
11308: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11309: }
1.703 albertel 11310: my $key=join("\0",'slots',$cdom,$cnum,$which);
11311: my %slotinfo;
11312: if (exists($remembered{$key})) {
11313: $slotinfo{$which} = $remembered{$key};
11314: } else {
11315: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11316: &Apache::lonhomework::showhash(%slotinfo);
11317: my ($tmp)=keys(%slotinfo);
11318: if ($tmp=~/^error:/) { return (); }
11319: $remembered{$key} = $slotinfo{$which};
11320: }
1.616 albertel 11321: if (ref($slotinfo{$which}) eq 'HASH') {
11322: return %{$slotinfo{$which}};
11323: }
11324: return $slotinfo{$which};
1.614 albertel 11325: }
1.1150 raeburn 11326:
11327: sub get_reservable_slots {
11328: my ($cnum,$cdom,$uname,$udom) = @_;
11329: my $now = time;
11330: my $reservable_info;
11331: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11332: if (exists($remembered{$key})) {
11333: $reservable_info = $remembered{$key};
11334: } else {
11335: my %resv;
11336: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11337: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11338: $reservable_info = \%resv;
11339: $remembered{$key} = $reservable_info;
11340: }
11341: return $reservable_info;
11342: }
11343:
11344: sub get_course_slots {
11345: my ($cnum,$cdom) = @_;
11346: my $hashid=$cnum.':'.$cdom;
11347: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11348: if (defined($cached)) {
11349: if (ref($result) eq 'HASH') {
11350: return %{$result};
11351: }
11352: } else {
11353: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11354: my ($tmp) = keys(%slots);
11355: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11356: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11357: return %slots;
11358: }
11359: }
11360: return;
11361: }
11362:
11363: sub devalidate_slots_cache {
11364: my ($cnum,$cdom)=@_;
11365: my $hashid=$cnum.':'.$cdom;
11366: &devalidate_cache_new('allslots',$hashid);
11367: }
11368:
1.1172.2.8 raeburn 11369: sub get_coursechange {
11370: my ($cdom,$cnum) = @_;
11371: if ($cdom eq '' || $cnum eq '') {
11372: return unless ($env{'request.course.id'});
11373: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11374: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11375: }
11376: my $hashid=$cdom.'_'.$cnum;
11377: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11378: if ((defined($cached)) && ($change ne '')) {
11379: return $change;
11380: } else {
11381: my %crshash;
11382: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11383: if ($crshash{'internal.contentchange'} eq '') {
11384: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11385: if ($change eq '') {
11386: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11387: $change = $crshash{'internal.created'};
11388: }
11389: } else {
11390: $change = $crshash{'internal.contentchange'};
11391: }
11392: my $cachetime = 600;
11393: &do_cache_new('crschange',$hashid,$change,$cachetime);
11394: }
11395: return $change;
11396: }
11397:
11398: sub devalidate_coursechange_cache {
11399: my ($cnum,$cdom)=@_;
11400: my $hashid=$cnum.':'.$cdom;
11401: &devalidate_cache_new('crschange',$hashid);
11402: }
11403:
1.31 www 11404: # ------------------------------------------------- Update symbolic store links
11405:
11406: sub symblist {
11407: my ($mapname,%newhash)=@_;
1.438 www 11408: $mapname=&deversion(&declutter($mapname));
1.31 www 11409: my %hash;
1.620 albertel 11410: if (($env{'request.course.fn'}) && (%newhash)) {
11411: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11412: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11413: foreach my $url (keys(%newhash)) {
1.711 albertel 11414: next if ($url eq 'last_known'
11415: && $env{'form.no_update_last_known'});
11416: $hash{declutter($url)}=&encode_symb($mapname,
11417: $newhash{$url}->[1],
11418: $newhash{$url}->[0]);
1.191 harris41 11419: }
1.31 www 11420: if (untie(%hash)) {
11421: return 'ok';
11422: }
11423: }
11424: }
11425: return 'error';
1.212 www 11426: }
11427:
11428: # --------------------------------------------------------------- Verify a symb
11429:
11430: sub symbverify {
1.1172.2.11 raeburn 11431: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11432: my $thisfn=$thisurl;
1.439 www 11433: $thisfn=&declutter($thisfn);
1.215 www 11434: # direct jump to resource in page or to a sequence - will construct own symbs
11435: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11436: # check URL part
1.409 www 11437: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11438:
1.431 www 11439: unless ($url eq $thisfn) { return 0; }
1.213 www 11440:
1.216 www 11441: $symb=&symbclean($symb);
1.510 www 11442: $thisurl=&deversion($thisurl);
1.439 www 11443: $thisfn=&deversion($thisfn);
1.213 www 11444:
11445: my %bighash;
11446: my $okay=0;
1.431 www 11447:
1.620 albertel 11448: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11449: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11450: my $noclutter;
1.1032 raeburn 11451: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11452: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11453: if ($map =~ m{^uploaded/.+\.page$}) {
11454: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11455: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11456: $noclutter = 1;
11457: }
11458: }
11459: my $ids;
11460: if ($noclutter) {
11461: $ids=$bighash{'ids_'.$thisurl};
11462: } else {
11463: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11464: }
1.1102 raeburn 11465: unless ($ids) {
1.1172.2.13 raeburn 11466: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11467: $ids=$bighash{$idkey};
1.216 www 11468: }
11469: if ($ids) {
11470: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11471: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11472: $symb =~ s/\?.+$//;
11473: }
1.800 albertel 11474: foreach my $id (split(/\,/,$ids)) {
11475: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11476: if (
11477: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11478: eq $symb) {
1.1172.2.11 raeburn 11479: if (ref($encstate)) {
11480: $$encstate = $bighash{'encrypted_'.$id};
11481: }
1.1172.2.13 raeburn 11482: if (($env{'request.role.adv'}) ||
11483: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11484: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11485: $okay=1;
11486: last;
11487: }
11488: }
11489: }
1.216 www 11490: }
1.213 www 11491: untie(%bighash);
11492: }
11493: return $okay;
1.31 www 11494: }
11495:
1.210 www 11496: # --------------------------------------------------------------- Clean-up symb
11497:
11498: sub symbclean {
11499: my $symb=shift;
1.568 albertel 11500: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11501: # remove version from map
11502: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11503:
1.210 www 11504: # remove version from URL
11505: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11506:
1.507 www 11507: # remove wrapper
11508:
1.510 www 11509: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11510: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11511: return $symb;
1.409 www 11512: }
11513:
11514: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11515:
11516: sub encode_symb {
11517: my ($map,$resid,$url)=@_;
11518: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11519: }
1.409 www 11520:
11521: sub decode_symb {
1.568 albertel 11522: my $symb=shift;
11523: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11524: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11525: return (&fixversion($map),$resid,&fixversion($url));
11526: }
11527:
11528: sub fixversion {
11529: my $fn=shift;
1.609 banghart 11530: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11531: my %bighash;
11532: my $uri=&clutter($fn);
1.620 albertel 11533: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11534: # is this cached?
1.599 albertel 11535: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11536: if (defined($cached)) { return $result; }
11537: # unfortunately not cached, or expired
1.620 albertel 11538: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11539: &GDBM_READER(),0640)) {
11540: if ($bighash{'version_'.$uri}) {
11541: my $version=$bighash{'version_'.$uri};
1.444 www 11542: unless (($version eq 'mostrecent') ||
11543: ($version==&getversion($uri))) {
1.440 www 11544: $uri=~s/\.(\w+)$/\.$version\.$1/;
11545: }
11546: }
11547: untie %bighash;
1.413 www 11548: }
1.599 albertel 11549: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11550: }
11551:
11552: sub deversion {
11553: my $url=shift;
11554: $url=~s/\.\d+\.(\w+)$/\.$1/;
11555: return $url;
1.210 www 11556: }
11557:
1.31 www 11558: # ------------------------------------------------------ Return symb list entry
11559:
11560: sub symbread {
1.1172.2.66 raeburn 11561: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11562: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11563: if (defined($env{$cache_str})) {
11564: if ($ignorecachednull) {
11565: return $env{$cache_str} unless ($env{$cache_str} eq '');
11566: } else {
11567: return $env{$cache_str};
11568: }
11569: }
1.242 www 11570: # no filename provided? try from environment
1.1172.2.54 raeburn 11571: unless ($thisfn) {
1.620 albertel 11572: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11573: return $env{$cache_str}=&symbclean($env{'request.symb'});
11574: }
11575: $thisfn=$env{'request.filename'};
1.44 www 11576: }
1.569 albertel 11577: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11578: # is that filename actually a symb? Verify, clean, and return
11579: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11580: if (&symbverify($thisfn,$1)) {
1.620 albertel 11581: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11582: }
1.242 www 11583: }
1.44 www 11584: $thisfn=declutter($thisfn);
1.31 www 11585: my %hash;
1.37 www 11586: my %bighash;
11587: my $syval='';
1.620 albertel 11588: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11589: my $targetfn = $thisfn;
1.609 banghart 11590: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11591: $targetfn = 'adm/wrapper/'.$thisfn;
11592: }
1.687 albertel 11593: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11594: $targetfn=$1;
11595: }
1.620 albertel 11596: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11597: &GDBM_READER(),0640)) {
1.481 raeburn 11598: $syval=$hash{$targetfn};
1.37 www 11599: untie(%hash);
11600: }
11601: # ---------------------------------------------------------- There was an entry
11602: if ($syval) {
1.601 albertel 11603: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11604: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11605: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11606: #return $env{$cache_str}='';
1.601 albertel 11607: #}
11608: #$syval.=$1;
11609: #}
1.37 www 11610: } else {
11611: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11612: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11613: &GDBM_READER(),0640)) {
1.37 www 11614: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11615: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11616: unless ($ids) {
11617: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11618: }
11619: unless ($ids) {
11620: # alias?
11621: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11622: }
1.37 www 11623: if ($ids) {
11624: # ------------------------------------------------------------------- Has ID(s)
11625: my @possibilities=split(/\,/,$ids);
1.39 www 11626: if ($#possibilities==0) {
11627: # ----------------------------------------------- There is only one possibility
1.37 www 11628: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11629: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11630: $resid,$thisfn);
1.1172.2.66 raeburn 11631: if (ref($possibles) eq 'HASH') {
11632: $possibles->{$syval} = 1;
11633: }
11634: if ($checkforblock) {
11635: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11636: if (@blockers) {
11637: $syval = '';
11638: return;
11639: }
11640: }
11641: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11642: # ------------------------------------------ There is more than one possibility
11643: my $realpossible=0;
1.800 albertel 11644: foreach my $id (@possibilities) {
11645: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11646: my $canaccess;
11647: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11648: $canaccess = 1;
11649: } else {
11650: $canaccess = &allowed('bre',$file);
11651: }
11652: if ($canaccess) {
11653: my ($mapid,$resid)=split(/\./,$id);
11654: if ($bighash{'map_type_'.$mapid} ne 'page') {
11655: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11656: $resid,$thisfn);
11657: if (ref($possibles) eq 'HASH') {
11658: $possibles->{$syval} = 1;
11659: }
11660: if ($checkforblock) {
11661: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11662: unless (@blockers > 0) {
11663: $syval = $poss_syval;
11664: $realpossible++;
11665: }
11666: } else {
11667: $syval = $poss_syval;
11668: $realpossible++;
11669: }
11670: }
1.39 www 11671: }
1.191 harris41 11672: }
1.39 www 11673: if ($realpossible!=1) { $syval=''; }
1.249 www 11674: } else {
11675: $syval='';
1.37 www 11676: }
11677: }
1.1172.2.66 raeburn 11678: untie(%bighash);
1.481 raeburn 11679: }
1.31 www 11680: }
1.62 www 11681: if ($syval) {
1.620 albertel 11682: return $env{$cache_str}=$syval;
1.62 www 11683: }
1.31 www 11684: }
1.949 raeburn 11685: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11686: return $env{$cache_str}='';
1.31 www 11687: }
11688:
11689: # ---------------------------------------------------------- Return random seed
11690:
1.32 www 11691: sub numval {
11692: my $txt=shift;
11693: $txt=~tr/A-J/0-9/;
11694: $txt=~tr/a-j/0-9/;
11695: $txt=~tr/K-T/0-9/;
11696: $txt=~tr/k-t/0-9/;
11697: $txt=~tr/U-Z/0-5/;
11698: $txt=~tr/u-z/0-5/;
11699: $txt=~s/\D//g;
1.564 albertel 11700: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11701: return int($txt);
1.368 albertel 11702: }
11703:
1.484 albertel 11704: sub numval2 {
11705: my $txt=shift;
11706: $txt=~tr/A-J/0-9/;
11707: $txt=~tr/a-j/0-9/;
11708: $txt=~tr/K-T/0-9/;
11709: $txt=~tr/k-t/0-9/;
11710: $txt=~tr/U-Z/0-5/;
11711: $txt=~tr/u-z/0-5/;
11712: $txt=~s/\D//g;
11713: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11714: my $total;
11715: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11716: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11717: return int($total);
11718: }
11719:
1.575 albertel 11720: sub numval3 {
11721: use integer;
11722: my $txt=shift;
11723: $txt=~tr/A-J/0-9/;
11724: $txt=~tr/a-j/0-9/;
11725: $txt=~tr/K-T/0-9/;
11726: $txt=~tr/k-t/0-9/;
11727: $txt=~tr/U-Z/0-5/;
11728: $txt=~tr/u-z/0-5/;
11729: $txt=~s/\D//g;
11730: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11731: my $total;
11732: foreach my $val (@txts) { $total+=$val; }
11733: if ($_64bit) { $total=(($total<<32)>>32); }
11734: return $total;
11735: }
11736:
1.675 albertel 11737: sub digest {
11738: my ($data)=@_;
11739: my $digest=&Digest::MD5::md5($data);
11740: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11741: my ($e,$f);
11742: {
11743: use integer;
11744: $e=($a+$b);
11745: $f=($c+$d);
11746: if ($_64bit) {
11747: $e=(($e<<32)>>32);
11748: $f=(($f<<32)>>32);
11749: }
11750: }
11751: if (wantarray) {
11752: return ($e,$f);
11753: } else {
11754: my $g;
11755: {
11756: use integer;
11757: $g=($e+$f);
11758: if ($_64bit) {
11759: $g=(($g<<32)>>32);
11760: }
11761: }
11762: return $g;
11763: }
11764: }
11765:
1.368 albertel 11766: sub latest_rnd_algorithm_id {
1.675 albertel 11767: return '64bit5';
1.366 albertel 11768: }
1.32 www 11769:
1.503 albertel 11770: sub get_rand_alg {
11771: my ($courseid)=@_;
1.790 albertel 11772: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11773: if ($courseid) {
1.620 albertel 11774: return $env{"course.$courseid.rndseed"};
1.503 albertel 11775: }
11776: return &latest_rnd_algorithm_id();
11777: }
11778:
1.562 albertel 11779: sub validCODE {
11780: my ($CODE)=@_;
11781: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11782: return 0;
11783: }
11784:
1.491 albertel 11785: sub getCODE {
1.620 albertel 11786: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11787: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11788: defined($Apache::lonhomework::parsing_a_task) ) &&
11789: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11790: return $Apache::lonhomework::history{'resource.CODE'};
11791: }
11792: return undef;
11793: }
1.1133 foxr 11794: #
11795: # Determines the random seed for a specific context:
11796: #
11797: # parameters:
11798: # symb - in course context the symb for the seed.
11799: # course_id - The course id of the form domain_coursenum.
11800: # domain - Domain for the user.
11801: # course - Course for the user.
11802: # cenv - environment of the course.
11803: #
11804: # NOTE:
11805: # All parameters are picked out of the environment if missing
11806: # or not defined.
11807: # If a symb cannot be determined the current time is used instead.
11808: #
11809: # For a given well defined symb, courside, domain, username,
11810: # and course environment, the seed is reproducible.
11811: #
1.31 www 11812: sub rndseed {
1.1133 foxr 11813: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11814: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11815: if (!defined($symb)) {
1.366 albertel 11816: unless ($symb=$wsymb) { return time; }
11817: }
1.1146 foxr 11818: if (!defined $courseid) {
11819: $courseid=$wcourseid;
11820: }
11821: if (!defined $domain) { $domain=$wdomain; }
11822: if (!defined $username) { $username=$wusername }
1.1133 foxr 11823:
11824: my $which;
11825: if (defined($cenv->{'rndseed'})) {
11826: $which = $cenv->{'rndseed'};
11827: } else {
11828: $which =&get_rand_alg($courseid);
11829: }
1.491 albertel 11830: if (defined(&getCODE())) {
1.675 albertel 11831: if ($which eq '64bit5') {
11832: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11833: } elsif ($which eq '64bit4') {
1.575 albertel 11834: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11835: } else {
11836: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11837: }
1.675 albertel 11838: } elsif ($which eq '64bit5') {
11839: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11840: } elsif ($which eq '64bit4') {
11841: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11842: } elsif ($which eq '64bit3') {
11843: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11844: } elsif ($which eq '64bit2') {
11845: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11846: } elsif ($which eq '64bit') {
11847: return &rndseed_64bit($symb,$courseid,$domain,$username);
11848: }
11849: return &rndseed_32bit($symb,$courseid,$domain,$username);
11850: }
11851:
11852: sub rndseed_32bit {
11853: my ($symb,$courseid,$domain,$username)=@_;
11854: {
11855: use integer;
11856: my $symbchck=unpack("%32C*",$symb) << 27;
11857: my $symbseed=numval($symb) << 22;
11858: my $namechck=unpack("%32C*",$username) << 17;
11859: my $nameseed=numval($username) << 12;
11860: my $domainseed=unpack("%32C*",$domain) << 7;
11861: my $courseseed=unpack("%32C*",$courseid);
11862: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11863: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11864: #&logthis("rndseed :$num:$symb");
1.564 albertel 11865: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11866: return $num;
11867: }
11868: }
11869:
11870: sub rndseed_64bit {
11871: my ($symb,$courseid,$domain,$username)=@_;
11872: {
11873: use integer;
11874: my $symbchck=unpack("%32S*",$symb) << 21;
11875: my $symbseed=numval($symb) << 10;
11876: my $namechck=unpack("%32S*",$username);
11877:
11878: my $nameseed=numval($username) << 21;
11879: my $domainseed=unpack("%32S*",$domain) << 10;
11880: my $courseseed=unpack("%32S*",$courseid);
11881:
11882: my $num1=$symbchck+$symbseed+$namechck;
11883: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11884: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11885: #&logthis("rndseed :$num:$symb");
1.564 albertel 11886: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11887: return "$num1,$num2";
1.155 albertel 11888: }
1.366 albertel 11889: }
11890:
1.443 albertel 11891: sub rndseed_64bit2 {
11892: my ($symb,$courseid,$domain,$username)=@_;
11893: {
11894: use integer;
11895: # strings need to be an even # of cahracters long, it it is odd the
11896: # last characters gets thrown away
11897: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11898: my $symbseed=numval($symb) << 10;
11899: my $namechck=unpack("%32S*",$username.' ');
11900:
11901: my $nameseed=numval($username) << 21;
1.501 albertel 11902: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11903: my $courseseed=unpack("%32S*",$courseid.' ');
11904:
11905: my $num1=$symbchck+$symbseed+$namechck;
11906: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11907: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11908: #&logthis("rndseed :$num:$symb");
1.803 albertel 11909: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11910: return "$num1,$num2";
11911: }
11912: }
11913:
11914: sub rndseed_64bit3 {
11915: my ($symb,$courseid,$domain,$username)=@_;
11916: {
11917: use integer;
11918: # strings need to be an even # of cahracters long, it it is odd the
11919: # last characters gets thrown away
11920: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11921: my $symbseed=numval2($symb) << 10;
11922: my $namechck=unpack("%32S*",$username.' ');
11923:
11924: my $nameseed=numval2($username) << 21;
1.443 albertel 11925: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11926: my $courseseed=unpack("%32S*",$courseid.' ');
11927:
11928: my $num1=$symbchck+$symbseed+$namechck;
11929: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11930: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11931: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11932: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11933:
1.503 albertel 11934: return "$num1:$num2";
1.443 albertel 11935: }
11936: }
11937:
1.575 albertel 11938: sub rndseed_64bit4 {
11939: my ($symb,$courseid,$domain,$username)=@_;
11940: {
11941: use integer;
11942: # strings need to be an even # of cahracters long, it it is odd the
11943: # last characters gets thrown away
11944: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11945: my $symbseed=numval3($symb) << 10;
11946: my $namechck=unpack("%32S*",$username.' ');
11947:
11948: my $nameseed=numval3($username) << 21;
11949: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11950: my $courseseed=unpack("%32S*",$courseid.' ');
11951:
11952: my $num1=$symbchck+$symbseed+$namechck;
11953: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11954: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11955: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11956: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11957:
1.575 albertel 11958: return "$num1:$num2";
11959: }
11960: }
11961:
1.675 albertel 11962: sub rndseed_64bit5 {
11963: my ($symb,$courseid,$domain,$username)=@_;
11964: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11965: return "$num1:$num2";
11966: }
11967:
1.366 albertel 11968: sub rndseed_CODE_64bit {
11969: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11970: {
1.366 albertel 11971: use integer;
1.443 albertel 11972: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11973: my $symbseed=numval2($symb);
1.491 albertel 11974: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11975: my $CODEseed=numval(&getCODE());
1.443 albertel 11976: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11977: my $num1=$symbseed+$CODEchck;
11978: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11979: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11980: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11981: if ($_64bit) { $num1=(($num1<<32)>>32); }
11982: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11983: return "$num1:$num2";
1.366 albertel 11984: }
11985: }
11986:
1.575 albertel 11987: sub rndseed_CODE_64bit4 {
11988: my ($symb,$courseid,$domain,$username)=@_;
11989: {
11990: use integer;
11991: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11992: my $symbseed=numval3($symb);
11993: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11994: my $CODEseed=numval3(&getCODE());
11995: my $courseseed=unpack("%32S*",$courseid.' ');
11996: my $num1=$symbseed+$CODEchck;
11997: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11998: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11999: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12000: if ($_64bit) { $num1=(($num1<<32)>>32); }
12001: if ($_64bit) { $num2=(($num2<<32)>>32); }
12002: return "$num1:$num2";
12003: }
12004: }
12005:
1.675 albertel 12006: sub rndseed_CODE_64bit5 {
12007: my ($symb,$courseid,$domain,$username)=@_;
12008: my $code = &getCODE();
12009: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12010: return "$num1:$num2";
12011: }
12012:
1.366 albertel 12013: sub setup_random_from_rndseed {
12014: my ($rndseed)=@_;
1.503 albertel 12015: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12016: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12017: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12018: &Math::Random::random_set_seed_from_phrase($rndseed);
12019: } else {
12020: &Math::Random::random_set_seed($num1,$num2);
12021: }
1.366 albertel 12022: } else {
12023: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12024: }
1.36 albertel 12025: }
12026:
1.474 albertel 12027: sub latest_receipt_algorithm_id {
1.835 albertel 12028: return 'receipt3';
1.474 albertel 12029: }
12030:
1.480 www 12031: sub recunique {
12032: my $fucourseid=shift;
12033: my $unique;
1.835 albertel 12034: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12035: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12036: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12037: } else {
12038: $unique=$perlvar{'lonReceipt'};
12039: }
12040: return unpack("%32C*",$unique);
12041: }
12042:
12043: sub recprefix {
12044: my $fucourseid=shift;
12045: my $prefix;
1.835 albertel 12046: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12047: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12048: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12049: } else {
12050: $prefix=$perlvar{'lonHostID'};
12051: }
12052: return unpack("%32C*",$prefix);
12053: }
12054:
1.76 www 12055: sub ireceipt {
1.474 albertel 12056: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12057:
12058: my $return =&recprefix($fucourseid).'-';
12059:
12060: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12061: $env{'request.state'} eq 'construct') {
12062: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12063: return $return;
12064: }
12065:
1.76 www 12066: my $cuname=unpack("%32C*",$funame);
12067: my $cudom=unpack("%32C*",$fudom);
12068: my $cucourseid=unpack("%32C*",$fucourseid);
12069: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12070: my $cunique=&recunique($fucourseid);
1.474 albertel 12071: my $cpart=unpack("%32S*",$part);
1.835 albertel 12072: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12073:
1.790 albertel 12074: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12075:
12076: $return.= ($cunique%$cuname+
12077: $cunique%$cudom+
12078: $cusymb%$cuname+
12079: $cusymb%$cudom+
12080: $cucourseid%$cuname+
12081: $cucourseid%$cudom+
12082: $cpart%$cuname+
12083: $cpart%$cudom);
12084: } else {
12085: $return.= ($cunique%$cuname+
12086: $cunique%$cudom+
12087: $cusymb%$cuname+
12088: $cusymb%$cudom+
12089: $cucourseid%$cuname+
12090: $cucourseid%$cudom);
12091: }
12092: return $return;
1.76 www 12093: }
12094:
12095: sub receipt {
1.474 albertel 12096: my ($part)=@_;
1.790 albertel 12097: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12098: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12099: }
1.260 ng 12100:
1.790 albertel 12101: sub whichuser {
12102: my ($passedsymb)=@_;
12103: my ($symb,$courseid,$domain,$name,$publicuser);
12104: if (defined($env{'form.grade_symb'})) {
12105: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12106: my $allowed=&allowed('vgr',$tmp_courseid);
12107: if (!$allowed &&
12108: exists($env{'request.course.sec'}) &&
12109: $env{'request.course.sec'} !~ /^\s*$/) {
12110: $allowed=&allowed('vgr',$tmp_courseid.
12111: '/'.$env{'request.course.sec'});
12112: }
12113: if ($allowed) {
12114: ($symb)=&get_env_multiple('form.grade_symb');
12115: $courseid=$tmp_courseid;
12116: ($domain)=&get_env_multiple('form.grade_domain');
12117: ($name)=&get_env_multiple('form.grade_username');
12118: return ($symb,$courseid,$domain,$name,$publicuser);
12119: }
12120: }
12121: if (!$passedsymb) {
12122: $symb=&symbread();
12123: } else {
12124: $symb=$passedsymb;
12125: }
12126: $courseid=$env{'request.course.id'};
12127: $domain=$env{'user.domain'};
12128: $name=$env{'user.name'};
12129: if ($name eq 'public' && $domain eq 'public') {
12130: if (!defined($env{'form.username'})) {
12131: $env{'form.username'}.=time.rand(10000000);
12132: }
12133: $name.=$env{'form.username'};
12134: }
12135: return ($symb,$courseid,$domain,$name,$publicuser);
12136:
12137: }
12138:
1.36 albertel 12139: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12140: # returns either the contents of the file or
12141: # -1 if the file doesn't exist
1.481 raeburn 12142: #
12143: # if the target is a file that was uploaded via DOCS,
12144: # a check will be made to see if a current copy exists on the local server,
12145: # if it does this will be served, otherwise a copy will be retrieved from
12146: # the home server for the course and stored in /home/httpd/html/userfiles on
12147: # the local server.
1.472 albertel 12148:
1.36 albertel 12149: sub getfile {
1.538 albertel 12150: my ($file) = @_;
1.609 banghart 12151: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12152: &repcopy($file);
12153: return &readfile($file);
12154: }
12155:
12156: sub repcopy_userfile {
12157: my ($file)=@_;
1.1142 raeburn 12158: my $londocroot = $perlvar{'lonDocRoot'};
12159: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12160: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12161: my ($cdom,$cnum,$filename) =
1.811 albertel 12162: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12163: my $uri="/uploaded/$cdom/$cnum/$filename";
12164: if (-e "$file") {
1.828 www 12165: # we already have a local copy, check it out
1.538 albertel 12166: my @fileinfo = stat($file);
1.828 www 12167: my $rtncode;
12168: my $info;
1.538 albertel 12169: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12170: if ($lwpresp ne 'ok') {
1.828 www 12171: # there is no such file anymore, even though we had a local copy
1.482 albertel 12172: if ($rtncode eq '404') {
1.538 albertel 12173: unlink($file);
1.482 albertel 12174: }
12175: return -1;
12176: }
12177: if ($info < $fileinfo[9]) {
1.828 www 12178: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12179: return 'ok';
1.828 www 12180: } else {
12181: # the file is outdated, get rid of it
12182: unlink($file);
1.482 albertel 12183: }
1.828 www 12184: }
12185: # one way or the other, at this point, we don't have the file
12186: # construct the correct path for the file
12187: my @parts = ($cdom,$cnum);
12188: if ($filename =~ m|^(.+)/[^/]+$|) {
12189: push @parts, split(/\//,$1);
12190: }
12191: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12192: foreach my $part (@parts) {
12193: $path .= '/'.$part;
12194: if (!-e $path) {
12195: mkdir($path,0770);
1.482 albertel 12196: }
12197: }
1.828 www 12198: # now the path exists for sure
12199: # get a user agent
12200: my $ua=new LWP::UserAgent;
12201: my $transferfile=$file.'.in.transfer';
12202: # FIXME: this should flock
12203: if (-e $transferfile) { return 'ok'; }
12204: my $request;
12205: $uri=~s/^\///;
1.980 raeburn 12206: my $homeserver = &homeserver($cnum,$cdom);
12207: my $protocol = $protocol{$homeserver};
12208: $protocol = 'http' if ($protocol ne 'https');
12209: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12210: my $response=$ua->request($request,$transferfile);
12211: # did it work?
12212: if ($response->is_error()) {
12213: unlink($transferfile);
12214: &logthis("Userfile repcopy failed for $uri");
12215: return -1;
12216: }
12217: # worked, rename the transfer file
12218: rename($transferfile,$file);
1.607 raeburn 12219: return 'ok';
1.481 raeburn 12220: }
12221:
1.517 albertel 12222: sub tokenwrapper {
12223: my $uri=shift;
1.980 raeburn 12224: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12225: $uri=~s|^/||;
1.620 albertel 12226: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12227: my $token=$1;
1.552 albertel 12228: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12229: if ($udom && $uname && $file) {
12230: $file=~s|(\?\.*)*$||;
1.949 raeburn 12231: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12232: my $homeserver = &homeserver($uname,$udom);
12233: my $protocol = $protocol{$homeserver};
12234: $protocol = 'http' if ($protocol ne 'https');
12235: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12236: (($uri=~/\?/)?'&':'?').'token='.$token.
12237: '&tokenissued='.$perlvar{'lonHostID'};
12238: } else {
12239: return '/adm/notfound.html';
12240: }
12241: }
12242:
1.828 www 12243: # call with reqtype HEAD: get last modification time
12244: # call with reqtype GET: get the file contents
12245: # Do not call this with reqtype GET for large files! It loads everything into memory
12246: #
1.481 raeburn 12247: sub getuploaded {
12248: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12249: $uri=~s/^\///;
1.980 raeburn 12250: my $homeserver = &homeserver($cnum,$cdom);
12251: my $protocol = $protocol{$homeserver};
12252: $protocol = 'http' if ($protocol ne 'https');
12253: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12254: my $ua=new LWP::UserAgent;
12255: my $request=new HTTP::Request($reqtype,$uri);
12256: my $response=$ua->request($request);
12257: $$rtncode = $response->code;
1.482 albertel 12258: if (! $response->is_success()) {
12259: return 'failed';
12260: }
12261: if ($reqtype eq 'HEAD') {
1.486 www 12262: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12263: } elsif ($reqtype eq 'GET') {
12264: $$info = $response->content;
1.472 albertel 12265: }
1.482 albertel 12266: return 'ok';
1.36 albertel 12267: }
12268:
1.481 raeburn 12269: sub readfile {
12270: my $file = shift;
12271: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12272: my $fh;
12273: open($fh,"<$file");
12274: my $a='';
1.800 albertel 12275: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12276: return $a;
12277: }
12278:
1.36 albertel 12279: sub filelocation {
1.590 banghart 12280: my ($dir,$file) = @_;
12281: my $location;
12282: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12283:
12284: if ($file =~ m-^/adm/-) {
12285: $file=~s-^/adm/wrapper/-/-;
12286: $file=~s-^/adm/coursedocs/showdoc/-/-;
12287: }
1.882 albertel 12288:
1.1139 www 12289: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12290: $location = $file;
1.609 banghart 12291: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12292: my ($udom,$uname,$filename)=
1.811 albertel 12293: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12294: my $home=&homeserver($uname,$udom);
12295: my $is_me=0;
12296: my @ids=¤t_machine_ids();
12297: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12298: if ($is_me) {
1.1117 foxr 12299: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12300: } else {
12301: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12302: $udom.'/'.$uname.'/'.$filename;
12303: }
1.882 albertel 12304: } elsif ($file =~ m-^/adm/-) {
12305: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12306: } else {
12307: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12308: $file=~s:^/(res|priv)/:/:;
12309: my $space=$1;
1.590 banghart 12310: if ( !( $file =~ m:^/:) ) {
12311: $location = $dir. '/'.$file;
12312: } else {
1.1142 raeburn 12313: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12314: }
1.59 albertel 12315: }
1.590 banghart 12316: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12317: while ($location=~m{/\.\./}) {
12318: if ($location =~ m{/[^/]+/\.\./}) {
12319: $location=~ s{/[^/]+/\.\./}{/}g;
12320: } else {
12321: $location=~ s{/\.\./}{/}g;
12322: }
12323: } #remove dir/..
1.590 banghart 12324: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12325: return $location;
1.46 www 12326: }
1.36 albertel 12327:
1.46 www 12328: sub hreflocation {
12329: my ($dir,$file)=@_;
1.980 raeburn 12330: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12331: $file=filelocation($dir,$file);
1.700 albertel 12332: } elsif ($file=~m-^/adm/-) {
12333: $file=~s-^/adm/wrapper/-/-;
12334: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12335: }
12336: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12337: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12338: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12339: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12340: {/uploaded/$1/$2/}x;
1.46 www 12341: }
1.913 albertel 12342: if ($file=~ m{^/userfiles/}) {
12343: $file =~ s{^/userfiles/}{/uploaded/};
12344: }
1.462 albertel 12345: return $file;
1.465 albertel 12346: }
12347:
1.1139 www 12348:
12349:
12350:
12351:
1.465 albertel 12352: sub current_machine_domains {
1.853 albertel 12353: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12354: }
12355:
12356: sub machine_domains {
12357: my ($hostname) = @_;
1.465 albertel 12358: my @domains;
1.838 albertel 12359: my %hostname = &all_hostnames();
1.465 albertel 12360: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12361: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12362: if ($hostname eq $name) {
1.844 albertel 12363: push(@domains,&host_domain($id));
1.465 albertel 12364: }
12365: }
12366: return @domains;
12367: }
12368:
12369: sub current_machine_ids {
1.853 albertel 12370: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12371: }
12372:
12373: sub machine_ids {
12374: my ($hostname) = @_;
12375: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12376: my @ids;
1.888 albertel 12377: my %name_to_host = &all_names();
1.889 albertel 12378: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12379: return @{ $name_to_host{$hostname} };
12380: }
12381: return;
1.31 www 12382: }
12383:
1.824 raeburn 12384: sub additional_machine_domains {
12385: my @domains;
12386: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12387: while( my $line = <$fh>) {
12388: $line =~ s/\s//g;
12389: push(@domains,$line);
12390: }
12391: return @domains;
12392: }
12393:
12394: sub default_login_domain {
12395: my $domain = $perlvar{'lonDefDomain'};
12396: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12397: foreach my $posdom (¤t_machine_domains(),
12398: &additional_machine_domains()) {
12399: if (lc($posdom) eq lc($testdomain)) {
12400: $domain=$posdom;
12401: last;
12402: }
12403: }
12404: return $domain;
12405: }
12406:
1.31 www 12407: # ------------------------------------------------------------- Declutters URLs
12408:
12409: sub declutter {
12410: my $thisfn=shift;
1.569 albertel 12411: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12412: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12413: $thisfn=~s{^/home/httpd/html}{};
12414: }
1.31 www 12415: $thisfn=~s/^\///;
1.697 albertel 12416: $thisfn=~s|^adm/wrapper/||;
12417: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12418: $thisfn=~s/^res\///;
1.1172 bisitz 12419: $thisfn=~s/^priv\///;
1.1032 raeburn 12420: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12421: $thisfn=~s/\?.+$//;
12422: }
1.268 www 12423: return $thisfn;
12424: }
12425:
12426: # ------------------------------------------------------------- Clutter up URLs
12427:
12428: sub clutter {
12429: my $thisfn='/'.&declutter(shift);
1.887 albertel 12430: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12431: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12432: $thisfn='/res'.$thisfn;
12433: }
1.1031 raeburn 12434: if ($thisfn !~m|^/adm|) {
12435: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12436: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12437: } else {
12438: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12439: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12440: if ($embstyle eq 'ssi'
12441: || ($embstyle eq 'hdn')
12442: || ($embstyle eq 'rat')
12443: || ($embstyle eq 'prv')
12444: || ($embstyle eq 'ign')) {
12445: #do nothing with these
12446: } elsif (($embstyle eq 'img')
1.695 albertel 12447: || ($embstyle eq 'emb')
12448: || ($embstyle eq 'wrp')) {
12449: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12450: } elsif ($embstyle eq 'unk'
12451: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12452: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12453: } else {
1.718 www 12454: # &logthis("Got a blank emb style");
1.695 albertel 12455: }
1.694 albertel 12456: }
12457: }
1.31 www 12458: return $thisfn;
1.12 www 12459: }
12460:
1.787 albertel 12461: sub clutter_with_no_wrapper {
12462: my $uri = &clutter(shift);
12463: if ($uri =~ m-^/adm/-) {
12464: $uri =~ s-^/adm/wrapper/-/-;
12465: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12466: }
12467: return $uri;
12468: }
12469:
1.557 albertel 12470: sub freeze_escape {
12471: my ($value)=@_;
12472: if (ref($value)) {
12473: $value=&nfreeze($value);
12474: return '__FROZEN__'.&escape($value);
12475: }
12476: return &escape($value);
12477: }
12478:
1.11 www 12479:
1.557 albertel 12480: sub thaw_unescape {
12481: my ($value)=@_;
12482: if ($value =~ /^__FROZEN__/) {
12483: substr($value,0,10,undef);
12484: $value=&unescape($value);
12485: return &thaw($value);
12486: }
12487: return &unescape($value);
12488: }
12489:
1.436 albertel 12490: sub correct_line_ends {
12491: my ($result)=@_;
12492: $$result =~s/\r\n/\n/mg;
12493: $$result =~s/\r/\n/mg;
1.415 albertel 12494: }
1.1 albertel 12495: # ================================================================ Main Program
12496:
1.184 www 12497: sub goodbye {
1.204 albertel 12498: &logthis("Starting Shut down");
1.443 albertel 12499: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12500: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12501: #converted
1.599 albertel 12502: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12503: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12504: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12505: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12506: #1.1 only
1.870 albertel 12507: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12508: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12509: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12510: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12511: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12512: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12513: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12514: &flushcourselogs();
12515: &logthis("Shutting down");
12516: }
12517:
1.852 albertel 12518: sub get_dns {
1.1172.2.17 raeburn 12519: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12520: if (!$ignore_cache) {
12521: my ($content,$cached)=
12522: &Apache::lonnet::is_cached_new('dns',$url);
12523: if ($cached) {
1.1172.2.17 raeburn 12524: &$func($content,$hashref);
1.869 albertel 12525: return;
12526: }
12527: }
12528:
12529: my %alldns;
1.852 albertel 12530: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12531: foreach my $dns (<$config>) {
12532: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12533: my $line = $1;
12534: my ($host,$protocol) = split(/:/,$line);
12535: if ($protocol ne 'https') {
12536: $protocol = 'http';
12537: }
12538: $alldns{$host} = $protocol;
1.869 albertel 12539: }
12540: while (%alldns) {
1.1172.2.52 raeburn 12541: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12542: my $ua=new LWP::UserAgent;
1.1134 raeburn 12543: $ua->timeout(30);
1.979 raeburn 12544: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12545: my $response=$ua->request($request);
1.979 raeburn 12546: delete($alldns{$dns});
1.852 albertel 12547: next if ($response->is_error());
12548: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12549: unless ($nocache) {
1.1172.2.23 raeburn 12550: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12551: }
12552: &$func(\@content,$hashref);
1.869 albertel 12553: return;
1.852 albertel 12554: }
12555: close($config);
1.871 albertel 12556: my $which = (split('/',$url))[3];
12557: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12558: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12559: my @content = <$config>;
1.1172.2.17 raeburn 12560: &$func(\@content,$hashref);
12561: return;
12562: }
12563:
12564: # ------------------------------------------------------Get DNS checksums file
12565: sub parse_dns_checksums_tab {
12566: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12567: my $lonhost = $perlvar{'lonHostID'};
12568: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12569: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12570: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12571: my $webconfdir = '/etc/httpd/conf';
12572: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12573: $webconfdir = '/etc/apache2';
12574: } elsif ($distro =~ /^sles(\d+)$/) {
12575: if ($1 >= 10) {
12576: $webconfdir = '/etc/apache2';
12577: }
12578: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12579: if ($1 >= 10.0) {
12580: $webconfdir = '/etc/apache2';
12581: }
12582: }
1.1172.2.17 raeburn 12583: my ($release,$timestamp) = split(/\-/,$loncaparev);
12584: my (%chksum,%revnum);
12585: if (ref($lines) eq 'ARRAY') {
12586: chomp(@{$lines});
1.1172.2.34 raeburn 12587: my $version = shift(@{$lines});
12588: if ($version eq $release) {
1.1172.2.17 raeburn 12589: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12590: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12591: if ($file =~ m{^/etc/httpd/conf}) {
12592: if ($webconfdir eq '/etc/apache2') {
12593: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12594: }
12595: }
1.1172.2.34 raeburn 12596: $chksum{$file} = $shasum;
12597: $revnum{$file} = $version;
1.1172.2.17 raeburn 12598: }
12599: if (ref($hashref) eq 'HASH') {
12600: %{$hashref} = (
12601: sums => \%chksum,
12602: versions => \%revnum,
12603: );
12604: }
12605: }
12606: }
1.869 albertel 12607: return;
1.852 albertel 12608: }
1.1172.2.17 raeburn 12609:
12610: sub fetch_dns_checksums {
12611: my %checksums;
1.1172.2.34 raeburn 12612: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12613: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12614: my ($release,$timestamp) = split(/\-/,$loncaparev);
12615: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12616: \%checksums);
12617: return \%checksums;
12618: }
12619:
1.327 albertel 12620: # ------------------------------------------------------------ Read domain file
12621: {
1.852 albertel 12622: my $loaded;
1.846 albertel 12623: my %domain;
12624:
1.852 albertel 12625: sub parse_domain_tab {
12626: my ($lines) = @_;
12627: foreach my $line (@$lines) {
12628: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12629:
1.846 albertel 12630: chomp($line);
1.852 albertel 12631: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12632: my %this_domain;
12633: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12634: 'lang_def', 'city', 'longi', 'lati',
12635: 'primary') {
12636: $this_domain{$field} = shift(@elements);
12637: }
12638: $domain{$name} = \%this_domain;
1.852 albertel 12639: }
12640: }
1.864 albertel 12641:
12642: sub reset_domain_info {
12643: undef($loaded);
12644: undef(%domain);
12645: }
12646:
1.852 albertel 12647: sub load_domain_tab {
1.1172.2.70 raeburn 12648: my ($ignore_cache,$nocache) = @_;
12649: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12650: my $fh;
12651: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12652: my @lines = <$fh>;
12653: &parse_domain_tab(\@lines);
1.448 albertel 12654: }
1.852 albertel 12655: close($fh);
12656: $loaded = 1;
1.327 albertel 12657: }
1.846 albertel 12658:
12659: sub domain {
1.852 albertel 12660: &load_domain_tab() if (!$loaded);
12661:
1.846 albertel 12662: my ($name,$what) = @_;
12663: return if ( !exists($domain{$name}) );
12664:
12665: if (!$what) {
12666: return $domain{$name}{'description'};
12667: }
12668: return $domain{$name}{$what};
12669: }
1.974 raeburn 12670:
12671: sub domain_info {
12672: &load_domain_tab() if (!$loaded);
12673: return %domain;
12674: }
12675:
1.327 albertel 12676: }
12677:
12678:
1.1 albertel 12679: # ------------------------------------------------------------- Read hosts file
12680: {
1.838 albertel 12681: my %hostname;
1.844 albertel 12682: my %hostdom;
1.845 albertel 12683: my %libserv;
1.852 albertel 12684: my $loaded;
1.888 albertel 12685: my %name_to_host;
1.1074 raeburn 12686: my %internetdom;
1.1107 raeburn 12687: my %LC_dns_serv;
1.852 albertel 12688:
12689: sub parse_hosts_tab {
12690: my ($file) = @_;
12691: foreach my $configline (@$file) {
12692: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12693: chomp($configline);
12694: if ($configline =~ /^\^/) {
12695: if ($configline =~ /^\^([\w.\-]+)/) {
12696: $LC_dns_serv{$1} = 1;
12697: }
12698: next;
12699: }
1.1074 raeburn 12700: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12701: $name=~s/\s//g;
12702: if ($id && $domain && $role && $name) {
12703: $hostname{$id}=$name;
1.888 albertel 12704: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12705: $hostdom{$id}=$domain;
12706: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12707: if (defined($protocol)) {
12708: if ($protocol eq 'https') {
12709: $protocol{$id} = $protocol;
12710: } else {
12711: $protocol{$id} = 'http';
12712: }
1.968 raeburn 12713: } else {
1.969 raeburn 12714: $protocol{$id} = 'http';
1.968 raeburn 12715: }
1.1074 raeburn 12716: if (defined($intdom)) {
12717: $internetdom{$id} = $intdom;
12718: }
1.852 albertel 12719: }
12720: }
12721: }
1.864 albertel 12722:
12723: sub reset_hosts_info {
1.897 albertel 12724: &purge_remembered();
1.864 albertel 12725: &reset_domain_info();
12726: &reset_hosts_ip_info();
1.892 albertel 12727: undef(%name_to_host);
1.864 albertel 12728: undef(%hostname);
12729: undef(%hostdom);
12730: undef(%libserv);
12731: undef($loaded);
12732: }
1.1 albertel 12733:
1.852 albertel 12734: sub load_hosts_tab {
1.1172.2.70 raeburn 12735: my ($ignore_cache,$nocache) = @_;
12736: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12737: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12738: my @config = <$config>;
12739: &parse_hosts_tab(\@config);
12740: close($config);
12741: $loaded=1;
1.1 albertel 12742: }
1.852 albertel 12743:
1.838 albertel 12744: sub hostname {
1.852 albertel 12745: &load_hosts_tab() if (!$loaded);
12746:
1.838 albertel 12747: my ($lonid) = @_;
12748: return $hostname{$lonid};
12749: }
1.845 albertel 12750:
1.838 albertel 12751: sub all_hostnames {
1.852 albertel 12752: &load_hosts_tab() if (!$loaded);
12753:
1.838 albertel 12754: return %hostname;
12755: }
1.845 albertel 12756:
1.888 albertel 12757: sub all_names {
1.1172.2.70 raeburn 12758: my ($ignore_cache,$nocache) = @_;
12759: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12760:
12761: return %name_to_host;
12762: }
12763:
1.974 raeburn 12764: sub all_host_domain {
12765: &load_hosts_tab() if (!$loaded);
12766: return %hostdom;
12767: }
12768:
1.845 albertel 12769: sub is_library {
1.852 albertel 12770: &load_hosts_tab() if (!$loaded);
12771:
1.845 albertel 12772: return exists($libserv{$_[0]});
12773: }
12774:
12775: sub all_library {
1.852 albertel 12776: &load_hosts_tab() if (!$loaded);
12777:
1.845 albertel 12778: return %libserv;
12779: }
12780:
1.1062 droeschl 12781: sub unique_library {
12782: #2x reverse removes all hostnames that appear more than once
12783: my %unique = reverse &all_library();
12784: return reverse %unique;
12785: }
12786:
1.841 albertel 12787: sub get_servers {
1.852 albertel 12788: &load_hosts_tab() if (!$loaded);
12789:
1.841 albertel 12790: my ($domain,$type) = @_;
12791: my %possible_hosts = ($type eq 'library') ? %libserv
12792: : %hostname;
12793: my %result;
1.842 albertel 12794: if (ref($domain) eq 'ARRAY') {
12795: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12796: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12797: $result{$host} = $hostname;
12798: }
12799: }
12800: } else {
12801: while ( my ($host,$hostname) = each(%possible_hosts)) {
12802: if ($hostdom{$host} eq $domain) {
12803: $result{$host} = $hostname;
12804: }
1.841 albertel 12805: }
12806: }
12807: return %result;
12808: }
1.845 albertel 12809:
1.1062 droeschl 12810: sub get_unique_servers {
12811: my %unique = reverse &get_servers(@_);
12812: return reverse %unique;
12813: }
12814:
1.844 albertel 12815: sub host_domain {
1.852 albertel 12816: &load_hosts_tab() if (!$loaded);
12817:
1.844 albertel 12818: my ($lonid) = @_;
12819: return $hostdom{$lonid};
12820: }
12821:
1.841 albertel 12822: sub all_domains {
1.852 albertel 12823: &load_hosts_tab() if (!$loaded);
12824:
1.841 albertel 12825: my %seen;
12826: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12827: return @uniq;
12828: }
1.1074 raeburn 12829:
12830: sub internet_dom {
12831: &load_hosts_tab() if (!$loaded);
12832:
12833: my ($lonid) = @_;
12834: return $internetdom{$lonid};
12835: }
1.1107 raeburn 12836:
12837: sub is_LC_dns {
12838: &load_hosts_tab() if (!$loaded);
12839:
12840: my ($hostname) = @_;
12841: return exists($LC_dns_serv{$hostname});
12842: }
12843:
1.1 albertel 12844: }
12845:
1.847 albertel 12846: {
12847: my %iphost;
1.856 albertel 12848: my %name_to_ip;
12849: my %lonid_to_ip;
1.869 albertel 12850:
1.847 albertel 12851: sub get_hosts_from_ip {
12852: my ($ip) = @_;
12853: my %iphosts = &get_iphost();
12854: if (ref($iphosts{$ip})) {
12855: return @{$iphosts{$ip}};
12856: }
12857: return;
1.839 albertel 12858: }
1.864 albertel 12859:
12860: sub reset_hosts_ip_info {
12861: undef(%iphost);
12862: undef(%name_to_ip);
12863: undef(%lonid_to_ip);
12864: }
1.856 albertel 12865:
12866: sub get_host_ip {
12867: my ($lonid) = @_;
12868: if (exists($lonid_to_ip{$lonid})) {
12869: return $lonid_to_ip{$lonid};
12870: }
12871: my $name=&hostname($lonid);
12872: my $ip = gethostbyname($name);
12873: return if (!$ip || length($ip) ne 4);
12874: $ip=inet_ntoa($ip);
12875: $name_to_ip{$name} = $ip;
12876: $lonid_to_ip{$lonid} = $ip;
12877: return $ip;
12878: }
1.847 albertel 12879:
12880: sub get_iphost {
1.1172.2.70 raeburn 12881: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12882:
1.869 albertel 12883: if (!$ignore_cache) {
12884: if (%iphost) {
12885: return %iphost;
12886: }
12887: my ($ip_info,$cached)=
12888: &Apache::lonnet::is_cached_new('iphost','iphost');
12889: if ($cached) {
12890: %iphost = %{$ip_info->[0]};
12891: %name_to_ip = %{$ip_info->[1]};
12892: %lonid_to_ip = %{$ip_info->[2]};
12893: return %iphost;
12894: }
12895: }
1.894 albertel 12896:
12897: # get yesterday's info for fallback
12898: my %old_name_to_ip;
12899: my ($ip_info,$cached)=
12900: &Apache::lonnet::is_cached_new('iphost','iphost');
12901: if ($cached) {
12902: %old_name_to_ip = %{$ip_info->[1]};
12903: }
12904:
1.1172.2.70 raeburn 12905: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12906: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12907: my $ip;
12908: if (!exists($name_to_ip{$name})) {
12909: $ip = gethostbyname($name);
12910: if (!$ip || length($ip) ne 4) {
1.894 albertel 12911: if (defined($old_name_to_ip{$name})) {
12912: $ip = $old_name_to_ip{$name};
12913: &logthis("Can't find $name defaulting to old $ip");
12914: } else {
12915: &logthis("Name $name no IP found");
12916: next;
12917: }
12918: } else {
12919: $ip=inet_ntoa($ip);
1.847 albertel 12920: }
12921: $name_to_ip{$name} = $ip;
12922: } else {
12923: $ip = $name_to_ip{$name};
1.653 albertel 12924: }
1.888 albertel 12925: foreach my $id (@{ $name_to_host{$name} }) {
12926: $lonid_to_ip{$id} = $ip;
12927: }
12928: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12929: }
1.1172.2.70 raeburn 12930: unless ($nocache) {
12931: &do_cache_new('iphost','iphost',
12932: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12933: 48*60*60);
12934: }
1.869 albertel 12935:
1.847 albertel 12936: return %iphost;
1.598 albertel 12937: }
12938:
1.992 raeburn 12939: #
12940: # Given a DNS returns the loncapa host name for that DNS
12941: #
12942: sub host_from_dns {
12943: my ($dns) = @_;
12944: my @hosts;
12945: my $ip;
12946:
1.993 raeburn 12947: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12948: $ip = $name_to_ip{$dns};
12949: }
12950: if (!$ip) {
12951: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12952: if (length($ip) == 4) {
12953: $ip = &IO::Socket::inet_ntoa($ip);
12954: }
12955: }
12956: if ($ip) {
12957: @hosts = get_hosts_from_ip($ip);
12958: return $hosts[0];
12959: }
12960: return undef;
1.986 foxr 12961: }
1.992 raeburn 12962:
1.1074 raeburn 12963: sub get_internet_names {
12964: my ($lonid) = @_;
12965: return if ($lonid eq '');
12966: my ($idnref,$cached)=
12967: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12968: if ($cached) {
12969: return $idnref;
12970: }
12971: my $ip = &get_host_ip($lonid);
12972: my @hosts = &get_hosts_from_ip($ip);
12973: my %iphost = &get_iphost();
12974: my (@idns,%seen);
12975: foreach my $id (@hosts) {
12976: my $dom = &host_domain($id);
12977: my $prim_id = &domain($dom,'primary');
12978: my $prim_ip = &get_host_ip($prim_id);
12979: next if ($seen{$prim_ip});
12980: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12981: foreach my $id (@{$iphost{$prim_ip}}) {
12982: my $intdom = &internet_dom($id);
12983: unless (grep(/^\Q$intdom\E$/,@idns)) {
12984: push(@idns,$intdom);
12985: }
12986: }
12987: }
12988: $seen{$prim_ip} = 1;
12989: }
1.1172.2.23 raeburn 12990: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12991: }
12992:
1.986 foxr 12993: }
12994:
1.1079 raeburn 12995: sub all_loncaparevs {
1.1172.2.39 raeburn 12996: 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 12997: }
12998:
1.1172.2.27 raeburn 12999: # ------------------------------------------------------- Read loncaparev table
13000: {
13001: sub load_loncaparevs {
13002: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13003: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13004: while (my $configline=<$config>) {
13005: chomp($configline);
13006: my ($hostid,$loncaparev)=split(/:/,$configline);
13007: $loncaparevs{$hostid}=$loncaparev;
13008: }
13009: close($config);
13010: }
13011: }
13012: }
13013: }
13014:
13015: # ----------------------------------------------------- Read serverhostID table
13016: {
13017: sub load_serverhomeIDs {
13018: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13019: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13020: while (my $configline=<$config>) {
13021: chomp($configline);
13022: my ($name,$id)=split(/:/,$configline);
13023: $serverhomeIDs{$name}=$id;
13024: }
13025: close($config);
13026: }
13027: }
13028: }
13029: }
13030:
13031:
1.862 albertel 13032: BEGIN {
13033:
13034: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13035: unless ($readit) {
13036: {
13037: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13038: %perlvar = (%perlvar,%{$configvars});
13039: }
13040:
13041:
1.1 albertel 13042: # ------------------------------------------------------ Read spare server file
13043: {
1.448 albertel 13044: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13045:
13046: while (my $configline=<$config>) {
13047: chomp($configline);
1.284 matthew 13048: if ($configline) {
1.784 albertel 13049: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13050: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13051: push(@{ $spareid{$type} }, $host);
1.1 albertel 13052: }
13053: }
1.448 albertel 13054: close($config);
1.1 albertel 13055: }
1.11 www 13056: # ------------------------------------------------------------ Read permissions
13057: {
1.448 albertel 13058: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13059:
13060: while (my $configline=<$config>) {
1.448 albertel 13061: chomp($configline);
13062: if ($configline) {
13063: my ($role,$perm)=split(/ /,$configline);
13064: if ($perm ne '') { $pr{$role}=$perm; }
13065: }
1.11 www 13066: }
1.448 albertel 13067: close($config);
1.11 www 13068: }
13069:
13070: # -------------------------------------------- Read plain texts for permissions
13071: {
1.448 albertel 13072: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13073:
13074: while (my $configline=<$config>) {
1.448 albertel 13075: chomp($configline);
13076: if ($configline) {
1.742 raeburn 13077: my ($short,@plain)=split(/:/,$configline);
13078: %{$prp{$short}} = ();
13079: if (@plain > 0) {
13080: $prp{$short}{'std'} = $plain[0];
13081: for (my $i=1; $i<@plain; $i++) {
13082: $prp{$short}{'alt'.$i} = $plain[$i];
13083: }
13084: }
1.448 albertel 13085: }
1.135 www 13086: }
1.448 albertel 13087: close($config);
1.135 www 13088: }
13089:
13090: # ---------------------------------------------------------- Read package table
13091: {
1.448 albertel 13092: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13093:
13094: while (my $configline=<$config>) {
1.483 albertel 13095: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13096: chomp($configline);
13097: my ($short,$plain)=split(/:/,$configline);
13098: my ($pack,$name)=split(/\&/,$short);
13099: if ($plain ne '') {
13100: $packagetab{$pack.'&'.$name.'&name'}=$name;
13101: $packagetab{$short}=$plain;
13102: }
1.11 www 13103: }
1.448 albertel 13104: close($config);
1.329 matthew 13105: }
13106:
1.1172.2.27 raeburn 13107: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13108:
1.1172.2.27 raeburn 13109: &load_loncaparevs();
13110:
13111: # ------------------------------------------------------- Read serverhostID table
13112:
13113: &load_serverhomeIDs();
1.1074 raeburn 13114:
1.1172.2.27 raeburn 13115: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13116: {
13117: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13118: if (-e $file) {
13119: my $parser = HTML::LCParser->new($file);
13120: while (my $token = $parser->get_token()) {
13121: if ($token->[0] eq 'S') {
13122: my $item = $token->[1];
13123: my $name = $token->[2]{'name'};
13124: my $value = $token->[2]{'value'};
13125: if ($item ne '' && $name ne '' && $value ne '') {
13126: my $release = $parser->get_text();
13127: $release =~ s/(^\s*|\s*$ )//gx;
13128: $needsrelease{$item.':'.$name.':'.$value} = $release;
13129: }
13130: }
13131: }
13132: }
1.1073 raeburn 13133: }
13134:
1.1138 raeburn 13135: # ---------------------------------------------------------- Read managers table
13136: {
13137: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13138: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13139: while (my $configline=<$config>) {
13140: chomp($configline);
13141: next if ($configline =~ /^\#/);
13142: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13143: $managerstab{$configline} = 1;
13144: }
13145: }
13146: close($config);
13147: }
13148: }
13149: }
13150:
1.329 matthew 13151: # ------------- set up temporary directory
13152: {
1.1117 foxr 13153: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13154:
1.11 www 13155: }
13156:
1.794 albertel 13157: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13158: 'compress_threshold'=> 20_000,
13159: });
1.185 www 13160:
1.281 www 13161: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13162: $dumpcount=0;
1.958 www 13163: $locknum=0;
1.22 www 13164:
1.163 harris41 13165: &logtouch();
1.672 albertel 13166: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13167: $readit=1;
1.564 albertel 13168: {
13169: use integer;
13170: my $test=(2**32)+1;
1.568 albertel 13171: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13172: &logthis(" Detected 64bit platform ($_64bit)");
13173: }
1.195 www 13174: }
1.1 albertel 13175: }
1.179 www 13176:
1.1 albertel 13177: 1;
1.191 harris41 13178: __END__
13179:
1.243 albertel 13180: =pod
13181:
1.191 harris41 13182: =head1 NAME
13183:
1.243 albertel 13184: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13185:
13186: =head1 SYNOPSIS
13187:
1.243 albertel 13188: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13189:
13190: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13191:
1.243 albertel 13192: Common parameters:
13193:
13194: =over 4
13195:
13196: =item *
13197:
13198: $uname : an internal username (if $cname expecting a course Id specifically)
13199:
13200: =item *
13201:
13202: $udom : a domain (if $cdom expecting a course's domain specifically)
13203:
13204: =item *
13205:
13206: $symb : a resource instance identifier
13207:
13208: =item *
13209:
13210: $namespace : the name of a .db file that contains the data needed or
13211: being set.
13212:
13213: =back
13214:
1.394 bowersj2 13215: =head1 OVERVIEW
1.191 harris41 13216:
1.394 bowersj2 13217: lonnet provides subroutines which interact with the
13218: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13219: about classes, users, and resources.
1.243 albertel 13220:
13221: For many of these objects you can also use this to store data about
13222: them or modify them in various ways.
1.191 harris41 13223:
1.394 bowersj2 13224: =head2 Symbs
1.191 harris41 13225:
1.394 bowersj2 13226: To identify a specific instance of a resource, LON-CAPA uses symbols
13227: or "symbs"X<symb>. These identifiers are built from the URL of the
13228: map, the resource number of the resource in the map, and the URL of
13229: the resource itself. The latter is somewhat redundant, but might help
13230: if maps change.
13231:
13232: An example is
13233:
13234: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13235:
13236: The respective map entry is
13237:
13238: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13239: title="Problem 2">
13240: </resource>
13241:
13242: Symbs are used by the random number generator, as well as to store and
13243: restore data specific to a certain instance of for example a problem.
13244:
13245: =head2 Storing And Retrieving Data
13246:
13247: X<store()>X<cstore()>X<restore()>Three of the most important functions
13248: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13249: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13250: is is the non-critical message twin of cstore. These functions are for
13251: handlers to store a perl hash to a user's permanent data space in an
13252: easy manner, and to retrieve it again on another call. It is expected
13253: that a handler would use this once at the beginning to retrieve data,
13254: and then again once at the end to send only the new data back.
13255:
13256: The data is stored in the user's data directory on the user's
13257: homeserver under the ID of the course.
13258:
13259: The hash that is returned by restore will have all of the previous
13260: value for all of the elements of the hash.
13261:
13262: Example:
13263:
13264: #creating a hash
13265: my %hash;
13266: $hash{'foo'}='bar';
13267:
13268: #storing it
13269: &Apache::lonnet::cstore(\%hash);
13270:
13271: #changing a value
13272: $hash{'foo'}='notbar';
13273:
13274: #adding a new value
13275: $hash{'bar'}='foo';
13276: &Apache::lonnet::cstore(\%hash);
13277:
13278: #retrieving the hash
13279: my %history=&Apache::lonnet::restore();
13280:
13281: #print the hash
13282: foreach my $key (sort(keys(%history))) {
13283: print("\%history{$key} = $history{$key}");
13284: }
13285:
13286: Will print out:
1.191 harris41 13287:
1.394 bowersj2 13288: %history{1:foo} = bar
13289: %history{1:keys} = foo:timestamp
13290: %history{1:timestamp} = 990455579
13291: %history{2:bar} = foo
13292: %history{2:foo} = notbar
13293: %history{2:keys} = foo:bar:timestamp
13294: %history{2:timestamp} = 990455580
13295: %history{bar} = foo
13296: %history{foo} = notbar
13297: %history{timestamp} = 990455580
13298: %history{version} = 2
13299:
13300: Note that the special hash entries C<keys>, C<version> and
13301: C<timestamp> were added to the hash. C<version> will be equal to the
13302: total number of versions of the data that have been stored. The
13303: C<timestamp> attribute will be the UNIX time the hash was
13304: stored. C<keys> is available in every historical section to list which
13305: keys were added or changed at a specific historical revision of a
13306: hash.
13307:
13308: B<Warning>: do not store the hash that restore returns directly. This
13309: will cause a mess since it will restore the historical keys as if the
13310: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13311:
1.394 bowersj2 13312: Calling convention:
1.191 harris41 13313:
1.1172.2.27 raeburn 13314: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13315: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13316:
1.394 bowersj2 13317: For more detailed information, see lonnet specific documentation.
1.191 harris41 13318:
1.394 bowersj2 13319: =head1 RETURN MESSAGES
1.191 harris41 13320:
1.394 bowersj2 13321: =over 4
1.191 harris41 13322:
1.394 bowersj2 13323: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13324:
1.394 bowersj2 13325: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13326: when the connection is brought back up
1.191 harris41 13327:
1.394 bowersj2 13328: =item * B<con_failed>: unable to contact remote host and unable to save message
13329: for later delivery
1.191 harris41 13330:
1.967 bisitz 13331: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13332:
1.394 bowersj2 13333: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13334: that was requested
1.191 harris41 13335:
1.243 albertel 13336: =back
1.191 harris41 13337:
1.243 albertel 13338: =head1 PUBLIC SUBROUTINES
1.191 harris41 13339:
1.243 albertel 13340: =head2 Session Environment Functions
1.191 harris41 13341:
1.243 albertel 13342: =over 4
1.191 harris41 13343:
1.394 bowersj2 13344: =item *
13345: X<appenv()>
1.949 raeburn 13346: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13347: the user envirnoment file, and will be restored for each access this
1.620 albertel 13348: user makes during this session, also modifies the %env for the current
1.949 raeburn 13349: process. Optional rolesarrayref - if defined contains a reference to an array
13350: of roles which are exempt from the restriction on modifying user.role entries
13351: in the user's environment.db and in %env.
1.191 harris41 13352:
13353: =item *
1.394 bowersj2 13354: X<delenv()>
1.987 raeburn 13355: B<delenv($delthis,$regexp)>: removes all items from the session
13356: environment file that begin with $delthis. If the
13357: optional second arg - $regexp - is true, $delthis is treated as a
13358: regular expression, otherwise \Q$delthis\E is used.
13359: The values are also deleted from the current processes %env.
1.191 harris41 13360:
1.795 albertel 13361: =item * get_env_multiple($name)
13362:
13363: gets $name from the %env hash, it seemlessly handles the cases where multiple
13364: values may be defined and end up as an array ref.
13365:
13366: returns an array of values
13367:
1.243 albertel 13368: =back
13369:
13370: =head2 User Information
1.191 harris41 13371:
1.243 albertel 13372: =over 4
1.191 harris41 13373:
13374: =item *
1.394 bowersj2 13375: X<queryauthenticate()>
13376: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13377: authentication scheme
13378:
13379: =item *
1.394 bowersj2 13380: X<authenticate()>
1.1073 raeburn 13381: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13382: authenticate user from domain's lib servers (first use the current
13383: one). C<$upass> should be the users password.
1.1073 raeburn 13384: $checkdefauth is optional (value is 1 if a check should be made to
13385: authenticate user using default authentication method, and allow
13386: account creation if username does not have account in the domain).
13387: $clientcancheckhost is optional (value is 1 if checking whether the
13388: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13389:
13390: =item *
1.394 bowersj2 13391: X<homeserver()>
13392: B<homeserver($uname,$udom)>: find the server which has
13393: the user's directory and files (there must be only one), this caches
13394: the answer, and also caches if there is a borken connection.
1.191 harris41 13395:
13396: =item *
1.394 bowersj2 13397: X<idget()>
13398: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13399: (IDs are a unique resource in a domain, there must be only 1 ID per
13400: username, and only 1 username per ID in a specific domain) (returns
13401: hash: id=>name,id=>name)
1.191 harris41 13402:
13403: =item *
1.394 bowersj2 13404: X<idrget()>
13405: B<idrget($udom,@unames)>: find the IDs behind a list of
13406: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13407:
13408: =item *
1.394 bowersj2 13409: X<idput()>
13410: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13411:
13412: =item *
1.394 bowersj2 13413: X<rolesinit()>
1.1169 droeschl 13414: B<rolesinit($udom,$username)>: get user privileges.
13415: returns user role, first access and timer interval hashes
1.243 albertel 13416:
13417: =item *
1.1171 droeschl 13418: X<privileged()>
13419: B<privileged($username,$domain)>: returns a true if user has a
13420: privileged and active role (i.e. su or dc), false otherwise.
13421:
13422: =item *
1.551 albertel 13423: X<getsection()>
13424: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13425: course $cname, return section name/number or '' for "not in course"
13426: and '-1' for "no section"
13427:
13428: =item *
1.394 bowersj2 13429: X<userenvironment()>
13430: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13431: passed in @what from the requested user's environment, returns a hash
13432:
1.858 raeburn 13433: =item *
13434: X<userlog_query()>
1.859 albertel 13435: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13436: activity.log file. %filters defines filters applied when parsing the
13437: log file. These can be start or end timestamps, or the type of action
13438: - log to look for Login or Logout events, check for Checkin or
13439: Checkout, role for role selection. The response is in the form
13440: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13441: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13442:
1.243 albertel 13443: =back
13444:
13445: =head2 User Roles
13446:
13447: =over 4
13448:
13449: =item *
13450:
1.1172.2.65 raeburn 13451: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13452: returns codes for allowed actions.
13453:
13454: The first argument is required, all others are optional.
13455:
13456: $priv is the privilege being checked.
13457: $uri contains additional information about what is being checked for access (e.g.,
13458: URL, course ID etc.).
13459: $symb is the unique resource instance identifier in a course; if needed,
13460: but not provided, it will be retrieved via a call to &symbread().
13461: $role is the role for which a priv is being checked (only used if priv is evb).
13462: $clientip is the user's IP address (only used when checking for access to portfolio
13463: files).
13464: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13465: prevents recursive calls to &allowed.
13466:
1.243 albertel 13467: F: full access
13468: U,I,K: authentication modes (cxx only)
13469: '': forbidden
13470: 1: user needs to choose course
13471: 2: browse allowed
1.766 albertel 13472: A: passphrase authentication needed
1.1172.2.65 raeburn 13473: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13474:
13475: =item *
13476:
1.1172.2.13 raeburn 13477: constructaccess($url,$setpriv) : check for access to construction space URL
13478:
13479: See if the owner domain and name in the URL match those in the
13480: expected environment. If so, return three element list
13481: ($ownername,$ownerdomain,$ownerhome).
13482:
13483: Otherwise return the null string.
13484:
13485: If second argument 'setpriv' is true, it assigns the privileges,
13486: and returns the same three element list, unless the owner has
13487: blocked "ad hoc" Domain Coordinator access to the Author Space,
13488: in which case the null string is returned.
13489:
13490: =item *
13491:
1.1172.2.84 raeburn 13492: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13493: define a custom role rolename set privileges in format of lonTabs/roles.tab
13494: for system, domain, and course level. $uname and $udom are optional (current
13495: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13496:
13497: =item *
13498:
1.988 raeburn 13499: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13500: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13501: $type is Course (default) or Community.
1.988 raeburn 13502: If $forcedefault evaluates to true, text returned will be default
13503: text for $type. Otherwise, if this is a course, the text returned
13504: will be a custom name for the role (if defined in the course's
13505: environment). If no custom name is defined the default is returned.
13506:
1.832 raeburn 13507: =item *
13508:
1.1172.2.23 raeburn 13509: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13510: All arguments are optional. Returns a hash of a roles, either for
13511: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13512: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13513: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13514: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13515: For each key, value is set to colon-separated start and end times for
13516: the role. If no username and domain are specified, will default to
1.934 raeburn 13517: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13518: of role statuses (active, future or previous), roles
13519: (e.g., cc,in, st etc.) and domains of the roles which can be used
13520: to restrict the list of roles reported. If no array ref is
13521: provided for types, will default to return only active roles.
1.834 albertel 13522:
1.1172.2.13 raeburn 13523: =item *
13524:
13525: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13526: user: $uname:$udom has a role in the course: $cdom_$cnum.
13527:
13528: Additional optional arguments are: $type (if role checking is to be restricted
13529: to certain user status types -- previous (expired roles), active (currently
13530: available roles) or future (roles available in the future), and
13531: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13532: have active Domain Coordinator role in course's domain or in additional
13533: domains (specified in 'Domains to check for privileged users' in course
13534: environment -- set via: Course Settings -> Classlists and staff listing).
13535:
13536: =item *
13537:
13538: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13539: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13540: $possdomains and $possroles are optional array refs -- to domains to check and
13541: roles to check. If $possdomains is not specified, a dump will be done of the
13542: users' roles.db to check for a dc or su role in any domain. This can be
13543: time consuming if &privileged is called repeatedly (e.g., when displaying a
13544: classlist), so in such cases, supplying a $possdomains array is preferred, as
13545: this then allows &privileged_by_domain() to be used, which caches the identity
13546: of privileged users, eliminating the need for repeated calls to &dump().
13547:
13548: =item *
13549:
13550: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13551: where the outer hash keys are domains specified in the $possdomains array ref,
13552: next inner hash keys are privileged roles specified in the $roles array ref,
13553: and the innermost hash contains key = value pairs for username:domain = end:start
13554: for active or future "privileged" users with that role in that domain. To avoid
13555: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13556: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13557:
1.243 albertel 13558: =back
13559:
13560: =head2 User Modification
13561:
13562: =over 4
13563:
13564: =item *
13565:
1.957 raeburn 13566: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13567: user for the level given by URL. Optional start and end dates (leave empty
13568: string or zero for "no date")
1.191 harris41 13569:
13570: =item *
13571:
1.243 albertel 13572: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13573: change a users, password, possible return values are: ok,
13574: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13575: refused
1.191 harris41 13576:
13577: =item *
13578:
1.243 albertel 13579: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13580:
13581: =item *
13582:
1.1058 raeburn 13583: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13584: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13585:
13586: will update user information (firstname,middlename,lastname,generation,
13587: permanentemail), and if forceid is true, student/employee ID also.
13588: A user's institutional affiliation(s) can also be updated.
13589: User information fields will not be overwritten with empty entries
13590: unless the field is included in the $candelete array reference.
13591: This array is included when a single user is modified via "Manage Users",
13592: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13593:
13594: =item *
13595:
1.286 matthew 13596: modifystudent
13597:
1.957 raeburn 13598: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13599: The course id is resolved based on the current user's environment.
13600: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13601: associated with a course.
13602:
1.297 matthew 13603: This call is essentially a wrapper for lonnet::modifyuser and
13604: lonnet::modify_student_enrollment
1.286 matthew 13605:
13606: Inputs:
13607:
13608: =over 4
13609:
1.957 raeburn 13610: =item B<$udom> Student's loncapa domain
1.286 matthew 13611:
1.957 raeburn 13612: =item B<$uname> Student's loncapa login name
1.286 matthew 13613:
1.964 bisitz 13614: =item B<$uid> Student/Employee ID
1.286 matthew 13615:
1.957 raeburn 13616: =item B<$umode> Student's authentication mode
1.286 matthew 13617:
1.957 raeburn 13618: =item B<$upass> Student's password
1.286 matthew 13619:
1.957 raeburn 13620: =item B<$first> Student's first name
1.286 matthew 13621:
1.957 raeburn 13622: =item B<$middle> Student's middle name
1.286 matthew 13623:
1.957 raeburn 13624: =item B<$last> Student's last name
1.286 matthew 13625:
1.957 raeburn 13626: =item B<$gene> Student's generation
1.286 matthew 13627:
1.957 raeburn 13628: =item B<$usec> Student's section in course
1.286 matthew 13629:
13630: =item B<$end> Unix time of the roles expiration
13631:
13632: =item B<$start> Unix time of the roles start date
13633:
13634: =item B<$forceid> If defined, allow $uid to be changed
13635:
13636: =item B<$desiredhome> server to use as home server for student
13637:
1.957 raeburn 13638: =item B<$email> Student's permanent e-mail address
13639:
13640: =item B<$type> Type of enrollment (auto or manual)
13641:
1.963 raeburn 13642: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13643:
13644: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13645:
1.963 raeburn 13646: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13647:
1.963 raeburn 13648: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13649:
1.1172.2.19 raeburn 13650: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13651:
13652: =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 13653:
1.286 matthew 13654: =back
1.297 matthew 13655:
13656: =item *
13657:
13658: modify_student_enrollment
13659:
1.1172.2.31 raeburn 13660: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13661: 'role.request.course' must be defined for this function to proceed.
13662:
13663: Inputs:
13664:
13665: =over 4
13666:
1.1172.2.31 raeburn 13667: =item $udom, student's domain
1.297 matthew 13668:
1.1172.2.31 raeburn 13669: =item $uname, student's name
1.297 matthew 13670:
1.1172.2.31 raeburn 13671: =item $uid, student's user id
1.297 matthew 13672:
1.1172.2.31 raeburn 13673: =item $first, student's first name
1.297 matthew 13674:
13675: =item $middle
13676:
13677: =item $last
13678:
13679: =item $gene
13680:
13681: =item $usec
13682:
13683: =item $end
13684:
13685: =item $start
13686:
1.957 raeburn 13687: =item $type
13688:
13689: =item $locktype
13690:
13691: =item $cid
13692:
13693: =item $selfenroll
13694:
13695: =item $context
13696:
1.1172.2.19 raeburn 13697: =item $credits, number of credits student will earn from this class
13698:
1.1172.2.76 raeburn 13699: =item $instsec, institutional course section code for student
13700:
1.297 matthew 13701: =back
13702:
1.191 harris41 13703:
13704: =item *
13705:
1.243 albertel 13706: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13707: custom role; give a custom role to a user for the level given by URL. Specify
13708: name and domain of role author, and role name
1.191 harris41 13709:
13710: =item *
13711:
1.243 albertel 13712: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13713:
13714: =item *
13715:
1.243 albertel 13716: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13717:
13718: =back
13719:
13720: =head2 Course Infomation
13721:
13722: =over 4
1.191 harris41 13723:
13724: =item *
13725:
1.1118 foxr 13726: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13727: specified course id, including all environment settings for the
13728: course, the description of the course will be in the hash under the
13729: key 'description'
1.191 harris41 13730:
1.1118 foxr 13731: $options is an optional parameter that if supplied is a hash reference that controls
13732: what how this function works. It has the following key/values:
13733:
13734: =over 4
13735:
13736: =item freshen_cache
13737:
13738: If defined, and the environment cache for the course is valid, it is
13739: returned in the returned hash.
13740:
13741: =item one_time
13742:
13743: If defined, the last cache time is set to _now_
13744:
13745: =item user
13746:
13747: If defined, the supplied username is used instead of the current user.
13748:
13749:
13750: =back
13751:
1.191 harris41 13752: =item *
13753:
1.624 albertel 13754: resdata($name,$domain,$type,@which) : request for current parameter
13755: setting for a specific $type, where $type is either 'course' or 'user',
13756: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13757: answers for 10 minutes.
1.243 albertel 13758:
1.877 foxr 13759: =item *
13760:
13761: get_courseresdata($courseid, $domain) : dump the entire course resource
13762: data base, returning a hash that is keyed by the resource name and has
13763: values that are the resource value. I believe that the timestamps and
13764: versions are also returned.
13765:
1.1172.2.31 raeburn 13766: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13767: supplemental content area. This routine caches the number of files for
13768: 10 minutes.
13769:
1.243 albertel 13770: =back
13771:
13772: =head2 Course Modification
13773:
13774: =over 4
1.191 harris41 13775:
13776: =item *
13777:
1.243 albertel 13778: writecoursepref($courseid,%prefs) : write preferences (environment
13779: database) for a course
1.191 harris41 13780:
13781: =item *
13782:
1.1011 raeburn 13783: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13784:
13785: =item *
13786:
1.1038 raeburn 13787: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13788:
1.1167 droeschl 13789: =item *
13790:
13791: is_course($courseid), is_course($cdom, $cnum)
13792:
13793: Accepts either a combined $courseid (in the form of domain_courseid) or the
13794: two component version $cdom, $cnum. It checks if the specified course exists.
13795:
13796: Returns:
13797: undef if the course doesn't exist, otherwise
13798: in scalar context the combined courseid.
13799: in list context the two components of the course identifier, domain and
13800: courseid.
13801:
1.243 albertel 13802: =back
13803:
13804: =head2 Resource Subroutines
13805:
13806: =over 4
1.191 harris41 13807:
13808: =item *
13809:
1.243 albertel 13810: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13811:
13812: =item *
13813:
1.243 albertel 13814: repcopy($filename) : subscribes to the requested file, and attempts to
13815: replicate from the owning library server, Might return
1.607 raeburn 13816: 'unavailable', 'not_found', 'forbidden', 'ok', or
13817: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13818: resource. Expects the local filesystem pathname
13819: (/home/httpd/html/res/....)
13820:
13821: =back
13822:
13823: =head2 Resource Information
13824:
13825: =over 4
1.191 harris41 13826:
13827: =item *
13828:
1.1172.2.28 raeburn 13829: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13830: and returns the value of a variety of different possible values,
13831: $varname should be a request string, and the other parameters can be
13832: used to specify who and what one is asking about. Ordinarily, $cid
13833: does not need to be specified, as it is retrived from
13834: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13835: within lonuserstate::loadmap() when initializing a course, before
13836: $env{'request.course.id'} has been set, so it needs to be provided
13837: in that one case.
1.243 albertel 13838:
13839: Possible values for $varname are environment.lastname (or other item
13840: from the envirnment hash), user.name (or someother aspect about the
13841: user), resource.0.maxtries (or some other part and parameter of a
13842: resource)
1.204 albertel 13843:
13844: =item *
13845:
1.243 albertel 13846: directcondval($number) : get current value of a condition; reads from a state
13847: string
1.204 albertel 13848:
13849: =item *
13850:
1.243 albertel 13851: condval($condidx) : value of condition index based on state
1.204 albertel 13852:
13853: =item *
13854:
1.243 albertel 13855: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13856: resource's metadata, $what should be either a specific key, or either
13857: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13858: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13859:
13860: this function automatically caches all requests
1.191 harris41 13861:
13862: =item *
13863:
1.243 albertel 13864: metadata_query($query,$custom,$customshow) : make a metadata query against the
13865: network of library servers; returns file handle of where SQL and regex results
13866: will be stored for query
1.191 harris41 13867:
13868: =item *
13869:
1.1172.2.66 raeburn 13870: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13871: return symbolic list entry (all arguments optional).
13872:
13873: Args: filename is the filename (including path) for the file for which a symb
13874: is required; donotrecurse, if true will prevent calls to allowed() being made
13875: to check access status if more than one resource was found in the bighash
13876: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13877: a randompick); ignorecachednull, if true will prevent a symb of '' being
13878: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13879: cause possible symbs to be checked to determine if they are subject to content
13880: blocking, if so they will not be included as possible symbs; possibles is a
13881: ref to a hash, which, as a side effect, will be populated with all possible
13882: symbs (content blocking not tested).
13883:
1.243 albertel 13884: returns the data handle
1.191 harris41 13885:
13886: =item *
13887:
1.1172.2.17 raeburn 13888: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13889: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13890: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13891: on failure, user must be in a course, as it assumes the existence of
13892: the course initial hash, and uses $env('request.course.id'}. The third
13893: arg is an optional reference to a scalar. If this arg is passed in the
13894: call to symbverify, it will be set to 1 if the symb has been set to be
13895: encrypted; otherwise it will be null.
1.243 albertel 13896:
1.191 harris41 13897: =item *
13898:
1.243 albertel 13899: symbclean($symb) : removes versions numbers from a symb, returns the
13900: cleaned symb
1.191 harris41 13901:
13902: =item *
13903:
1.243 albertel 13904: is_on_map($uri) : checks if the $uri is somewhere on the current
13905: course map, user must be in a course for it to work.
1.191 harris41 13906:
13907: =item *
13908:
1.243 albertel 13909: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13910:
13911: =item *
13912:
1.243 albertel 13913: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13914: a random seed, all arguments are optional, if they aren't sent it uses the
13915: environment to derive them. Note: if symb isn't sent and it can't get one
13916: from &symbread it will use the current time as its return value
1.191 harris41 13917:
13918: =item *
13919:
1.243 albertel 13920: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13921: unfakeable, receipt
1.191 harris41 13922:
13923: =item *
13924:
1.620 albertel 13925: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13926:
13927: =item *
13928:
1.243 albertel 13929: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13930:
13931: =item *
13932:
1.243 albertel 13933: 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 13934:
13935: =item *
13936:
1.243 albertel 13937: 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 13938:
13939: =item *
13940:
1.243 albertel 13941: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13942:
13943: =item *
13944:
1.243 albertel 13945: devalidate($symb) : devalidate temporary spreadsheet calculations,
13946: forcing spreadsheet to reevaluate the resource scores next time.
13947:
1.1172.2.13 raeburn 13948: =item *
13949:
13950: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13951: when viewing in course context.
13952:
13953: input: six args -- filename (decluttered), course number, course domain,
13954: url, symb (if registered) and group (if this is a
13955: group item -- e.g., bulletin board, group page etc.).
13956:
13957: output: array of five scalars --
13958: $cfile -- url for file editing if editable on current server
13959: $home -- homeserver of resource (i.e., for author if published,
13960: or course if uploaded.).
13961: $switchserver -- 1 if server switch will be needed.
13962: $forceedit -- 1 if icon/link should be to go to edit mode
13963: $forceview -- 1 if icon/link should be to go to view mode
13964:
13965: =item *
13966:
13967: is_course_upload($file,$cnum,$cdom)
13968:
13969: Used in course context to determine if current file was uploaded to
13970: the course (i.e., would be found in /userfiles/docs on the course's
13971: homeserver.
13972:
13973: input: 3 args -- filename (decluttered), course number and course domain.
13974: output: boolean -- 1 if file was uploaded.
13975:
1.243 albertel 13976: =back
13977:
13978: =head2 Storing/Retreiving Data
13979:
13980: =over 4
1.191 harris41 13981:
13982: =item *
13983:
1.1172.2.64 raeburn 13984: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13985: permanently for this url; hashref needs to be given and should be a \%hashname;
13986: the remaining args aren't required and if they aren't passed or are '' they will
13987: be derived from the env (with the exception of $laststore, which is an
13988: optional arg used when a user's submission is stored in grading).
13989: $laststore is $version=$timestamp, where $version is the most recent version
13990: number retrieved for the corresponding $symb in the $namespace db file, and
13991: $timestamp is the timestamp for that transaction (UNIX time).
13992: $laststore is currently only passed when cstore() is called by
13993: structuretags::finalize_storage().
1.191 harris41 13994:
13995: =item *
13996:
1.1172.2.64 raeburn 13997: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13998: but uses critical subroutine
1.191 harris41 13999:
14000: =item *
14001:
1.243 albertel 14002: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14003: all args are optional
1.191 harris41 14004:
14005: =item *
14006:
1.717 albertel 14007: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14008: dumps the complete (or key matching regexp) namespace into a hash
14009: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14010: normally &store()ed into
14011:
14012: $range should be either an integer '100' (give me the first 100
14013: matching records)
14014: or be two integers sperated by a - with no spaces
14015: '30-50' (give me the 30th through the 50th matching
14016: records)
14017:
14018:
14019: =item *
14020:
1.1172.2.59 raeburn 14021: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14022: replaces a &store() version of data with a replacement set of data
14023: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14024: reference. If $tolog is true, the transaction is logged in the courselog
14025: with an action=PUTSTORE.
1.717 albertel 14026:
14027: =item *
14028:
1.243 albertel 14029: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14030: works very similar to store/cstore, but all data is stored in a
14031: temporary location and can be reset using tmpreset, $storehash should
14032: be a hash reference, returns nothing on success
1.191 harris41 14033:
14034: =item *
14035:
1.243 albertel 14036: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14037: similar to restore, but all data is stored in a temporary location and
14038: can be reset using tmpreset. Returns a hash of values on success,
14039: error string otherwise.
1.191 harris41 14040:
14041: =item *
14042:
1.243 albertel 14043: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14044: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14045:
14046: =item *
14047:
1.243 albertel 14048: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14049: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14050:
14051: =item *
14052:
1.243 albertel 14053: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14054: namesp ($udom and $uname are optional)
1.191 harris41 14055:
14056: =item *
14057:
1.702 albertel 14058: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14059: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14060: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14061:
1.702 albertel 14062: $range should be either an integer '100' (give me the first 100
14063: matching records)
14064: or be two integers sperated by a - with no spaces
14065: '30-50' (give me the 30th through the 50th matching
14066: records)
1.449 matthew 14067: =item *
14068:
14069: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14070: $store can be a scalar, an array reference, or if the amount to be
14071: incremented is > 1, a hash reference.
14072:
14073: ($udom and $uname are optional)
1.191 harris41 14074:
14075: =item *
14076:
1.243 albertel 14077: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14078: ($udom and $uname are optional)
1.191 harris41 14079:
14080: =item *
14081:
1.243 albertel 14082: cput($namespace,$storehash,$udom,$uname) : critical put
14083: ($udom and $uname are optional)
1.191 harris41 14084:
14085: =item *
14086:
1.748 albertel 14087: newput($namespace,$storehash,$udom,$uname) :
14088:
14089: Attempts to store the items in the $storehash, but only if they don't
14090: currently exist, if this succeeds you can be certain that you have
14091: successfully created a new key value pair in the $namespace db.
14092:
14093:
14094: Args:
14095: $namespace: name of database to store values to
14096: $storehash: hashref to store to the db
14097: $udom: (optional) domain of user containing the db
14098: $uname: (optional) name of user caontaining the db
14099:
14100: Returns:
14101: 'ok' -> succeeded in storing all keys of $storehash
14102: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14103: least <key> already existed in the db (other
14104: requested keys may also already exist)
1.967 bisitz 14105: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14106: 'con_lost' -> unable to contact request server
14107: 'refused' -> action was not allowed by remote machine
14108:
14109:
14110: =item *
14111:
1.243 albertel 14112: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14113: reference filled in from namesp (encrypts the return communication)
14114: ($udom and $uname are optional)
1.191 harris41 14115:
14116: =item *
14117:
1.243 albertel 14118: log($udom,$name,$home,$message) : write to permanent log for user; use
14119: critical subroutine
14120:
1.806 raeburn 14121: =item *
14122:
1.860 raeburn 14123: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14124: array reference filled in from namespace found in domain level on either
14125: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14126:
14127: =item *
14128:
1.860 raeburn 14129: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14130: domain level either on specified domain server ($uhome) or primary domain
14131: server ($udom and $uhome are optional)
1.806 raeburn 14132:
1.943 raeburn 14133: =item *
14134:
1.1172.2.35 raeburn 14135: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14136: for: authentication, language, quotas, timezone, date locale, and portal URL in
14137: the target domain.
14138:
14139: May also include additional key => value pairs for the following groups:
14140:
14141: =over
14142:
14143: =item
14144: disk quotas (MB allocated by default to portfolios and authoring spaces).
14145:
14146: =over
14147:
14148: =item defaultquota, authorquota
14149:
14150: =back
14151:
14152: =item
14153: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14154: portfolio for users).
14155:
14156: =over
14157:
14158: =item
14159: aboutme, blog, webdav, portfolio
14160:
14161: =back
14162:
14163: =item
14164: requestcourses: ability to request courses, and how requests are processed.
14165:
14166: =over
14167:
14168: =item
1.1172.2.37 raeburn 14169: official, unofficial, community, textbook
1.1172.2.35 raeburn 14170:
14171: =back
14172:
14173: =item
14174: inststatus: types of institutional affiliation, and order in which they are displayed.
14175:
14176: =over
14177:
14178: =item
1.1172.2.44 raeburn 14179: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14180:
14181: =back
14182:
14183: =item
14184: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14185: for course's uploaded content.
14186:
14187: =over
14188:
14189: =item
1.1172.2.68 raeburn 14190: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14191: communityquota, textbookquota
1.1172.2.35 raeburn 14192:
14193: =back
14194:
14195: =item
14196: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14197: on your servers.
14198:
14199: =over
14200:
14201: =item
14202: remotesessions, hostedsessions
14203:
14204: =back
14205:
14206: =back
14207:
14208: In cases where a domain coordinator has never used the "Set Domain Configuration"
14209: utility to create a configuration.db file on a domain's primary library server
14210: only the following domain defaults: auth_def, auth_arg_def, lang_def
14211: -- corresponding values are authentication type (internal, krb4, krb5,
14212: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14213: will be available. Values are retrieved from cache (if current), unless the
14214: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14215: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14216:
14217: Typical usage:
1.943 raeburn 14218:
1.1172.2.35 raeburn 14219: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14220:
1.243 albertel 14221: =back
14222:
14223: =head2 Network Status Functions
14224:
14225: =over 4
1.191 harris41 14226:
14227: =item *
14228:
1.1137 raeburn 14229: dirlist() : return directory list based on URI (first arg).
14230:
14231: Inputs: 1 required, 5 optional.
14232:
14233: =over
14234:
14235: =item
14236: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14237:
14238: =item
14239: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14240:
14241: =item
14242: $username - username of user/course to be listed. Extracted from $uri if absent.
14243:
14244: =item
14245: $getpropath - boolean: 1 if prepend path using &propath().
14246:
14247: =item
14248: $getuserdir - boolean: 1 if prepend path for "userfiles".
14249:
14250: =item
14251: $alternateRoot - path to prepend in place of path from $uri.
14252:
14253: =back
14254:
14255: Returns: Array of up to two items.
14256:
14257: =over
14258:
14259: a reference to an array of files/subdirectories
14260:
14261: =over
14262:
14263: Each element in the array of files/subdirectories is a & separated list of
14264: item name and the result of running stat on the item. If dirlist was requested
14265: for a file instead of a directory, the item name will be ''. For a directory
14266: listing, if the item is a metadata file, the element will end &N&M
14267: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14268: default copyright set (1).
14269:
14270: =back
14271:
14272: a scalar containing error condition (if encountered).
14273:
14274: =over
14275:
14276: =item
14277: no_host (no homeserver identified for $username:$domain).
14278:
14279: =item
14280: no_such_host (server contacted for listing not identified as valid host).
14281:
14282: =item
14283: con_lost (connection to remote server failed).
14284:
14285: =item
14286: refused (invalid $username:$domain received on lond side).
14287:
14288: =item
14289: no_such_dir (directory at specified path on lond side does not exist).
14290:
14291: =item
14292: empty (directory at specified path on lond side is empty).
14293:
14294: =over
14295:
14296: This is currently not encountered because the &ls3, &ls2,
14297: &ls (_handler) routines on the lond side do not filter out
14298: . and .. from a directory listing.
14299:
14300: =back
14301:
14302: =back
14303:
14304: =back
1.191 harris41 14305:
14306: =item *
14307:
1.243 albertel 14308: spareserver() : find server with least workload from spare.tab
14309:
1.986 foxr 14310:
14311: =item *
14312:
14313: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14314: if there is no corresponding loncapa host.
14315:
1.243 albertel 14316: =back
14317:
1.986 foxr 14318:
1.243 albertel 14319: =head2 Apache Request
14320:
14321: =over 4
1.191 harris41 14322:
14323: =item *
14324:
1.243 albertel 14325: ssi($url,%hash) : server side include, does a complete request cycle on url to
14326: localhost, posts hash
14327:
14328: =back
14329:
14330: =head2 Data to String to Data
14331:
14332: =over 4
1.191 harris41 14333:
14334: =item *
14335:
1.243 albertel 14336: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14337: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14338:
14339: =item *
14340:
1.243 albertel 14341: hashref2str($hashref) : convert a hashref into a string complete with
14342: escaping and '=' and '&' separators, supports elements that are
14343: arrayrefs and hashrefs
1.191 harris41 14344:
14345: =item *
14346:
1.243 albertel 14347: arrayref2str($arrayref) : convert an arrayref into a string complete
14348: with escaping and '&' separators, supports elements that are arrayrefs
14349: and hashrefs
1.191 harris41 14350:
14351: =item *
14352:
1.243 albertel 14353: str2hash($string) : convert string to hash using unescaping and
14354: splitting on '=' and '&', supports elements that are arrayrefs and
14355: hashrefs
1.191 harris41 14356:
14357: =item *
14358:
1.243 albertel 14359: str2array($string) : convert string to hash using unescaping and
14360: splitting on '&', supports elements that are arrayrefs and hashrefs
14361:
14362: =back
14363:
14364: =head2 Logging Routines
14365:
14366:
14367: These routines allow one to make log messages in the lonnet.log and
14368: lonnet.perm logfiles.
1.191 harris41 14369:
1.1119 foxr 14370: =over 4
14371:
1.191 harris41 14372: =item *
14373:
1.243 albertel 14374: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14375:
14376: =item *
14377:
1.243 albertel 14378: logthis() : append message to the normal lonnet.log file, it gets
14379: preiodically rolled over and deleted.
1.191 harris41 14380:
14381: =item *
14382:
1.243 albertel 14383: logperm() : append a permanent message to lonnet.perm.log, this log
14384: file never gets deleted by any automated portion of the system, only
14385: messages of critical importance should go in here.
14386:
1.1119 foxr 14387:
1.243 albertel 14388: =back
14389:
14390: =head2 General File Helper Routines
14391:
14392: =over 4
1.191 harris41 14393:
14394: =item *
14395:
1.481 raeburn 14396: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14397: (a) files in /uploaded
14398: (i) If a local copy of the file exists -
14399: compares modification date of local copy with last-modified date for
14400: definitive version stored on home server for course. If local copy is
14401: stale, requests a new version from the home server and stores it.
14402: If the original has been removed from the home server, then local copy
14403: is unlinked.
14404: (ii) If local copy does not exist -
14405: requests the file from the home server and stores it.
14406:
14407: If $caller is 'uploadrep':
14408: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14409: for request for files originally uploaded via DOCS.
14410: - returns 'ok' if fresh local copy now available, -1 otherwise.
14411:
14412: Otherwise:
14413: This indicates a call from the content generation phase of the request.
14414: - returns the entire contents of the file or -1.
14415:
14416: (b) files in /res
14417: - returns the entire contents of a file or -1;
14418: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14419:
1.712 albertel 14420:
14421: =item *
14422:
14423: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14424: reference
14425:
14426: returns either a stat() list of data about the file or an empty list
14427: if the file doesn't exist or couldn't find out about it (connection
14428: problems or user unknown)
14429:
1.191 harris41 14430: =item *
14431:
1.243 albertel 14432: filelocation($dir,$file) : returns file system location of a file
14433: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14434: directory that relative $file lookups are to looked in ($dir of /a/dir
14435: and a file of ../bob will become /a/bob)
1.191 harris41 14436:
14437: =item *
14438:
14439: hreflocation($dir,$file) : returns file system location or a URL; same as
14440: filelocation except for hrefs
14441:
14442: =item *
14443:
1.1172.2.49 raeburn 14444: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14445: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14446:
1.243 albertel 14447: =back
14448:
1.608 albertel 14449: =head2 Usererfile file routines (/uploaded*)
14450:
14451: =over 4
14452:
14453: =item *
14454:
14455: userfileupload(): main rotine for putting a file in a user or course's
14456: filespace, arguments are,
14457:
1.620 albertel 14458: formname - required - this is the name of the element in $env where the
1.608 albertel 14459: filename, and the contents of the file to create/modifed exist
1.620 albertel 14460: the filename is in $env{'form.'.$formname.'.filename'} and the
14461: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14462: context - if coursedoc, store the file in the course of the active role
14463: of the current user;
14464: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14465: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14466: subdir - required - subdirectory to put the file in under ../userfiles/
14467: if undefined, it will be placed in "unknown"
14468:
14469: (This routine calls clean_filename() to remove any dangerous
14470: characters from the filename, and then calls finuserfileupload() to
14471: complete the transaction)
14472:
14473: returns either the url of the uploaded file (/uploaded/....) if successful
14474: and /adm/notfound.html if unsuccessful
14475:
14476: =item *
14477:
14478: clean_filename(): routine for cleaing a filename up for storage in
14479: userfile space, argument is:
14480:
14481: filename - proposed filename
14482:
14483: returns: the new clean filename
14484:
14485: =item *
14486:
1.1090 raeburn 14487: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14488: userspace, probably shouldn't be called directly
14489:
14490: docuname: username or courseid of destination for the file
14491: docudom: domain of user/course of destination for the file
14492: formname: same as for userfileupload()
1.1090 raeburn 14493: fname: filename (including subdirectories) for the file
14494: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14495: allfiles: reference to hash used to store objects found by parser
14496: codebase: reference to hash used for codebases of java objects found by parser
14497: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14498: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14499: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14500: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14501: context: if 'overwrite', will move the uploaded file from its temporary location to
14502: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14503: mimetype: reference to scalar to accommodate mime type determined
14504: from File::MMagic if $parser = parse.
1.608 albertel 14505:
14506: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14507: and /adm/notfound.html if unsuccessful (or an error message if context
14508: was 'overwrite').
14509:
1.608 albertel 14510:
14511: =item *
14512:
14513: renameuserfile(): renames an existing userfile to a new name
14514:
14515: Args:
14516: docuname: username or courseid of destination for the file
14517: docudom: domain of user/course of destination for the file
14518: old: current file name (including any subdirs under userfiles)
14519: new: desired file name (including any subdirs under userfiles)
14520:
14521: =item *
14522:
14523: mkdiruserfile(): creates a directory is a userfiles dir
14524:
14525: Args:
14526: docuname: username or courseid of destination for the file
14527: docudom: domain of user/course of destination for the file
14528: dir: dir to create (including any subdirs under userfiles)
14529:
14530: =item *
14531:
14532: removeuserfile(): removes a file that exists in userfiles
14533:
14534: Args:
14535: docuname: username or courseid of destination for the file
14536: docudom: domain of user/course of destination for the file
14537: fname: filname to delete (including any subdirs under userfiles)
14538:
14539: =item *
14540:
14541: removeuploadedurl(): convience function for removeuserfile()
14542:
14543: Args:
14544: url: a full /uploaded/... url to delete
14545:
1.747 albertel 14546: =item *
14547:
14548: get_portfile_permissions():
14549: Args:
14550: domain: domain of user or course contain the portfolio files
14551: user: name of user or num of course contain the portfolio files
14552: Returns:
14553: hashref of a dump of the proper file_permissions.db
14554:
14555:
14556: =item *
14557:
14558: get_access_controls():
14559:
14560: Args:
14561: current_permissions: the hash ref returned from get_portfile_permissions()
14562: group: (optional) the group you want the files associated with
14563: file: (optional) the file you want access info on
14564:
14565: Returns:
1.749 raeburn 14566: a hash (keys are file names) of hashes containing
14567: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14568: values are XML containing access control settings (see below)
1.747 albertel 14569:
14570: Internal notes:
14571:
1.749 raeburn 14572: access controls are stored in file_permissions.db as key=value pairs.
14573: key -> path to file/file_name\0uniqueID:scope_end_start
14574: where scope -> public,guest,course,group,domains or users.
14575: end -> UNIX time for end of access (0 -> no end date)
14576: start -> UNIX time for start of access
14577:
14578: value -> XML description of access control
14579: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14580: <start></start>
14581: <end></end>
14582:
14583: <password></password> for scope type = guest
14584:
14585: <domain></domain> for scope type = course or group
14586: <number></number>
14587: <roles id="">
14588: <role></role>
14589: <access></access>
14590: <section></section>
14591: <group></group>
14592: </roles>
14593:
14594: <dom></dom> for scope type = domains
14595:
14596: <users> for scope type = users
14597: <user>
14598: <uname></uname>
14599: <udom></udom>
14600: </user>
14601: </users>
14602: </scope>
14603:
14604: Access data is also aggregated for each file in an additional key=value pair:
14605: key -> path to file/file_name\0accesscontrol
14606: value -> reference to hash
14607: hash contains key = value pairs
14608: where key = uniqueID:scope_end_start
14609: value = UNIX time record was last updated
14610:
14611: Used to improve speed of look-ups of access controls for each file.
14612:
14613: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14614:
1.1172.2.13 raeburn 14615: =item *
14616:
1.749 raeburn 14617: modify_access_controls():
14618:
14619: Modifies access controls for a portfolio file
14620: Args
14621: 1. file name
14622: 2. reference to hash of required changes,
14623: 3. domain
14624: 4. username
14625: where domain,username are the domain of the portfolio owner
14626: (either a user or a course)
14627:
14628: Returns:
14629: 1. result of additions or updates ('ok' or 'error', with error message).
14630: 2. result of deletions ('ok' or 'error', with error message).
14631: 3. reference to hash of any new or updated access controls.
14632: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14633: key = integer (inbound ID)
1.1172.2.13 raeburn 14634: value = uniqueID
14635:
14636: =item *
14637:
14638: get_timebased_id():
14639:
14640: Attempts to get a unique timestamp-based suffix for use with items added to a
14641: course via the Course Editor (e.g., folders, composite pages,
14642: group bulletin boards).
14643:
14644: Args: (first three required; six others optional)
14645:
14646: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14647: docssequence, or name of group
14648:
14649: 2. keyid (alphanumeric): name of temporary locking key in hash,
14650: e.g., num, boardids
14651:
14652: 3. namespace: name of gdbm file used to store suffixes already assigned;
14653: file will be named nohist_namespace.db
14654:
14655: 4. cdom: domain of course; default is current course domain from %env
14656:
14657: 5. cnum: course number; default is current course number from %env
14658:
14659: 6. idtype: set to concat if an additional digit is to be appended to the
14660: unix timestamp to form the suffix, if the plain timestamp is already
14661: in use. Default is to not do this, but simply increment the unix
14662: timestamp by 1 until a unique key is obtained.
14663:
14664: 7. who: holder of locking key; defaults to user:domain for user.
14665:
14666: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14667: retrying); default is 3.
14668:
14669: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14670:
14671: Returns:
14672:
14673: 1. suffix obtained (numeric)
14674:
14675: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14676:
14677: 3. error: contains (localized) error message if an error occurred.
14678:
1.747 albertel 14679:
1.608 albertel 14680: =back
14681:
1.243 albertel 14682: =head2 HTTP Helper Routines
14683:
14684: =over 4
14685:
1.191 harris41 14686: =item *
14687:
14688: escape() : unpack non-word characters into CGI-compatible hex codes
14689:
14690: =item *
14691:
14692: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14693:
1.243 albertel 14694: =back
14695:
14696: =head1 PRIVATE SUBROUTINES
14697:
14698: =head2 Underlying communication routines (Shouldn't call)
14699:
14700: =over 4
14701:
14702: =item *
14703:
14704: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14705:
14706: =item *
14707:
14708: reply() : uses subreply to send a message to remote machine, logs all failures
14709:
14710: =item *
14711:
14712: critical() : passes a critical message to another server; if cannot
14713: get through then place message in connection buffer directory and
14714: returns con_delayed, if incapable of saving message, returns
14715: con_failed
14716:
14717: =item *
14718:
14719: reconlonc() : tries to reconnect lonc client processes.
14720:
14721: =back
14722:
14723: =head2 Resource Access Logging
14724:
14725: =over 4
14726:
14727: =item *
14728:
14729: flushcourselogs() : flush (save) buffer logs and access logs
14730:
14731: =item *
14732:
14733: courselog($what) : save message for course in hash
14734:
14735: =item *
14736:
14737: courseacclog($what) : save message for course using &courselog(). Perform
14738: special processing for specific resource types (problems, exams, quizzes, etc).
14739:
1.191 harris41 14740: =item *
14741:
14742: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14743: as a PerlChildExitHandler
1.243 albertel 14744:
14745: =back
14746:
14747: =head2 Other
14748:
14749: =over 4
14750:
14751: =item *
14752:
14753: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14754:
14755: =back
14756:
14757: =cut
1.877 foxr 14758:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>