Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.104
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.104! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.103 2019/02/15 15:37:24 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.104! raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
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") {
1.1172.2.96 raeburn 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.1172.2.96 raeburn 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.1172.2.96 raeburn 170: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 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.1172.2.96 raeburn 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;
1.1172.2.96 raeburn 479: if (open($dfh,">",$dfilename)) {
1.448 albertel 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;
1.1172.2.96 raeburn 488: if (open($dfh,"<",$dfilename)) {
1.448 albertel 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.96 raeburn 604: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.1172.2.96 raeburn 619: if (!-e "$lonidsdir/$handle.id") {
620: if ((ref($domref)) && ($name eq 'lonID') &&
621: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
622: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
623: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
624: $$domref = $possudom;
625: }
626: }
627: return undef;
628: }
1.916 albertel 629:
1.917 albertel 630: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
631: return undef if (!$opened);
1.916 albertel 632:
633: flock($idf,LOCK_SH);
634: my %disk_env;
635: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
636: &GDBM_READER(),0640)) {
637: return undef;
638: }
639:
640: if (!defined($disk_env{'user.name'})
641: || !defined($disk_env{'user.domain'})) {
642: return undef;
643: }
1.1172.2.18 raeburn 644:
1.1172.2.36 raeburn 645: if (ref($userhashref) eq 'HASH') {
646: $userhashref->{'name'} = $disk_env{'user.name'};
647: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 648: }
649:
1.916 albertel 650: return $handle;
651: }
652:
1.830 albertel 653: sub timed_flock {
654: my ($file,$lock_type) = @_;
655: my $failed=0;
656: eval {
657: local $SIG{__DIE__}='DEFAULT';
658: local $SIG{ALRM}=sub {
659: $failed=1;
660: die("failed lock");
661: };
662: alarm(13);
663: flock($file,$lock_type);
664: alarm(0);
665: };
666: if ($failed) {
667: return undef;
668: } else {
669: return 1;
670: }
671: }
672:
1.5 www 673: # ---------------------------------------------------------- Append Environment
674:
675: sub appenv {
1.949 raeburn 676: my ($newenv,$roles) = @_;
677: if (ref($newenv) eq 'HASH') {
678: foreach my $key (keys(%{$newenv})) {
679: my $refused = 0;
680: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
681: $refused = 1;
682: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 683: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 684: if (grep(/^\Q$role\E$/,@{$roles})) {
685: $refused = 0;
686: }
687: }
688: }
689: if ($refused) {
690: &logthis("<font color=\"blue\">WARNING: ".
691: "Attempt to modify environment ".$key." to ".$newenv->{$key}
692: .'</font>');
693: delete($newenv->{$key});
694: } else {
695: $env{$key}=$newenv->{$key};
696: }
697: }
1.1172.2.96 raeburn 698: my $lonids = $perlvar{'lonIDsDir'};
699: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
700: my $opened = open(my $env_file,'+<',$env{'user.environment'});
701: if ($opened
702: && &timed_flock($env_file,LOCK_EX)
703: &&
704: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
706: while (my ($key,$value) = each(%{$newenv})) {
707: $disk_env{$key} = $value;
708: }
709: untie(%disk_env);
710: }
1.35 www 711: }
1.191 harris41 712: }
1.56 www 713: return 'ok';
714: }
715: # ----------------------------------------------------- Delete from Environment
716:
717: sub delenv {
1.1104 raeburn 718: my ($delthis,$regexp,$roles) = @_;
719: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
720: my $refused = 1;
721: if (ref($roles) eq 'ARRAY') {
722: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
723: if (grep(/^\Q$role\E$/,@{$roles})) {
724: $refused = 0;
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to delete from environment ".$delthis);
730: return 'error';
731: }
1.56 www 732: }
1.917 albertel 733: my $opened = open(my $env_file,'+<',$env{'user.environment'});
734: if ($opened
1.915 albertel 735: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 736: &&
737: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
738: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 739: foreach my $key (keys(%disk_env)) {
1.987 raeburn 740: if ($regexp) {
741: if ($key=~/^$delthis/) {
742: delete($env{$key});
743: delete($disk_env{$key});
744: }
745: } else {
746: if ($key=~/^\Q$delthis\E/) {
747: delete($env{$key});
748: delete($disk_env{$key});
749: }
750: }
1.448 albertel 751: }
1.783 albertel 752: untie(%disk_env);
1.5 www 753: }
754: return 'ok';
1.369 albertel 755: }
756:
1.790 albertel 757: sub get_env_multiple {
758: my ($name) = @_;
759: my @values;
760: if (defined($env{$name})) {
761: # exists is it an array
762: if (ref($env{$name})) {
763: @values=@{ $env{$name} };
764: } else {
765: $values[0]=$env{$name};
766: }
767: }
768: return(@values);
769: }
770:
1.958 www 771: # ------------------------------------------------------------------- Locking
772:
773: sub set_lock {
774: my ($text)=@_;
775: $locknum++;
776: my $id=$$.'-'.$locknum;
777: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
778: 'session.lock.'.$id => $text});
779: return $id;
780: }
781:
782: sub get_locks {
783: my $num=0;
784: my %texts=();
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: $num++;
788: $texts{$lock}=$env{'session.lock.'.$lock};
789: }
790: }
791: return ($num,%texts);
792: }
793:
794: sub remove_lock {
795: my ($id)=@_;
796: my $newlocks='';
797: foreach my $lock (split(/\,/,$env{'session.locks'})) {
798: if (($lock=~/\w/) && ($lock ne $id)) {
799: $newlocks.=','.$lock;
800: }
801: }
802: &appenv({'session.locks' => $newlocks});
803: &delenv('session.lock.'.$id);
804: }
805:
806: sub remove_all_locks {
807: my $activelocks=$env{'session.locks'};
808: foreach my $lock (split(/\,/,$env{'session.locks'})) {
809: if ($lock=~/\w/) {
810: &remove_lock($lock);
811: }
812: }
813: }
814:
815:
1.369 albertel 816: # ------------------------------------------ Find out current server userload
817: sub userload {
818: my $numusers=0;
819: {
820: opendir(LONIDS,$perlvar{'lonIDsDir'});
821: my $filename;
822: my $curtime=time;
823: while ($filename=readdir(LONIDS)) {
1.925 albertel 824: next if ($filename eq '.' || $filename eq '..');
825: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 826: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 827: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 828: }
829: closedir(LONIDS);
830: }
831: my $userloadpercent=0;
832: my $maxuserload=$perlvar{'lonUserLoadLim'};
833: if ($maxuserload) {
1.371 albertel 834: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 835: }
1.372 albertel 836: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 837: return $userloadpercent;
1.283 www 838: }
839:
1.1 albertel 840: # ------------------------------ Find server with least workload from spare.tab
1.11 www 841:
1.1 albertel 842: sub spareserver {
1.1083 raeburn 843: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 844: my $spare_server;
1.370 albertel 845: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 846: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
847: : $userloadpercent;
1.1083 raeburn 848: my ($uint_dom,$remotesessions);
849: if (($udom ne '') && (&domain($udom) ne '')) {
850: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
851: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
852: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
853: $remotesessions = $udomdefaults{'remotesessions'};
854: }
1.1123 raeburn 855: my $spareshash = &this_host_spares($udom);
856: if (ref($spareshash) eq 'HASH') {
857: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
860: $try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
1.1083 raeburn 864: }
1.784 albertel 865:
1.1123 raeburn 866: my $found_server = ($spare_server ne '' && $lowest_load < 100);
867:
868: if (!$found_server) {
869: if (ref($spareshash->{'default'}) eq 'ARRAY') {
870: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 871: next unless (&spare_can_host($udom,$uint_dom,
872: $remotesessions,$try_server));
1.1123 raeburn 873: ($spare_server, $lowest_load) =
874: &compare_server_load($try_server, $spare_server, $lowest_load);
875: }
876: }
877: }
1.784 albertel 878: }
879:
880: if (!$want_server_name) {
1.968 raeburn 881: my $protocol = 'http';
882: if ($protocol{$spare_server} eq 'https') {
883: $protocol = $protocol{$spare_server};
884: }
1.1001 raeburn 885: if (defined($spare_server)) {
886: my $hostname = &hostname($spare_server);
1.1083 raeburn 887: if (defined($hostname)) {
1.1001 raeburn 888: $spare_server = $protocol.'://'.$hostname;
889: }
890: }
1.784 albertel 891: }
892: return $spare_server;
893: }
894:
895: sub compare_server_load {
1.1172.2.41 raeburn 896: my ($try_server, $spare_server, $lowest_load, $required) = @_;
897:
898: if ($required) {
899: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
900: my $remoterev = &get_server_loncaparev(undef,$try_server);
901: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
902: if (($major eq '' && $minor eq '') ||
903: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
904: return ($spare_server,$lowest_load);
905: }
906: }
1.784 albertel 907:
908: my $loadans = &reply('load', $try_server);
909: my $userloadans = &reply('userload',$try_server);
910:
911: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 912: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 913: }
914:
915: my $load;
916: if ($loadans =~ /\d/) {
917: if ($userloadans =~ /\d/) {
918: #both are numbers, pick the bigger one
919: $load = ($loadans > $userloadans) ? $loadans
920: : $userloadans;
1.411 albertel 921: } else {
1.784 albertel 922: $load = $loadans;
1.411 albertel 923: }
1.784 albertel 924: } else {
925: $load = $userloadans;
926: }
927:
928: if (($load =~ /\d/) && ($load < $lowest_load)) {
929: $spare_server = $try_server;
930: $lowest_load = $load;
1.370 albertel 931: }
1.784 albertel 932: return ($spare_server,$lowest_load);
1.202 matthew 933: }
1.914 albertel 934:
935: # --------------------------- ask offload servers if user already has a session
936: sub find_existing_session {
937: my ($udom,$uname) = @_;
1.1123 raeburn 938: my $spareshash = &this_host_spares($udom);
939: if (ref($spareshash) eq 'HASH') {
940: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
941: foreach my $try_server (@{ $spareshash->{'primary'} }) {
942: return $try_server if (&has_user_session($try_server, $udom, $uname));
943: }
944: }
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
947: return $try_server if (&has_user_session($try_server, $udom, $uname));
948: }
949: }
1.914 albertel 950: }
951: return;
952: }
953:
954: # -------------------------------- ask if server already has a session for user
955: sub has_user_session {
956: my ($lonid,$udom,$uname) = @_;
957: my $result = &reply(join(':','userhassession',
958: map {&escape($_)} ($udom,$uname)),$lonid);
959: return 1 if ($result eq 'ok');
960:
961: return 0;
962: }
963:
1.1076 raeburn 964: # --------- determine least loaded server in a user's domain which allows login
965:
966: sub choose_server {
1.1172.2.47 raeburn 967: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 968: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 969: my %servers = &get_servers($udom);
1.1076 raeburn 970: my $lowest_load = 30000;
1.1172.2.47 raeburn 971: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
972: if ($skiploadbal) {
973: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
974: unless (defined($cached)) {
975: my $cachetime = 60*60*24;
976: my %domconfig =
977: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
978: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
979: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
980: $cachetime);
981: }
982: }
983: }
1.1076 raeburn 984: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 985: my $loginvia;
1.1172.2.47 raeburn 986: if ($skiploadbal) {
987: if (ref($balancers) eq 'HASH') {
988: next if (exists($balancers->{$lonhost}));
989: }
990: }
1.1115 raeburn 991: if ($checkloginvia) {
992: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 993: if ($loginvia) {
994: my ($server,$path) = split(/:/,$loginvia);
995: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 996: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $server) {
998: $portal_path = $path;
1.1151 raeburn 999: $isredirect = 1;
1.1116 raeburn 1000: }
1001: } else {
1002: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1003: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1004: if ($login_host eq $lonhost) {
1005: $portal_path = '';
1.1151 raeburn 1006: $isredirect = '';
1.1116 raeburn 1007: }
1008: }
1009: } else {
1.1076 raeburn 1010: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1011: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1012: }
1013: }
1014: if ($login_host ne '') {
1.1116 raeburn 1015: $hostname = &hostname($login_host);
1.1076 raeburn 1016: }
1.1172.2.88 raeburn 1017: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1018: }
1019:
1.202 matthew 1020: # --------------------------------------------- Try to change a user's password
1021:
1022: sub changepass {
1.799 raeburn 1023: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1024: $currentpass = &escape($currentpass);
1025: $newpass = &escape($newpass);
1.1030 raeburn 1026: my $lonhost = $perlvar{'lonHostID'};
1027: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1028: $server);
1029: if (! $answer) {
1030: &logthis("No reply on password change request to $server ".
1031: "by $uname in domain $udom.");
1032: } elsif ($answer =~ "^ok") {
1033: &logthis("$uname in $udom successfully changed their password ".
1034: "on $server.");
1035: } elsif ($answer =~ "^pwchange_failure") {
1036: &logthis("$uname in $udom was unable to change their password ".
1037: "on $server. The action was blocked by either lcpasswd ".
1038: "or pwchange");
1039: } elsif ($answer =~ "^non_authorized") {
1040: &logthis("$uname in $udom did not get their password correct when ".
1041: "attempting to change it on $server.");
1042: } elsif ($answer =~ "^auth_mode_error") {
1043: &logthis("$uname in $udom attempted to change their password despite ".
1044: "not being locally or internally authenticated on $server.");
1045: } elsif ($answer =~ "^unknown_user") {
1046: &logthis("$uname in $udom attempted to change their password ".
1047: "on $server but were unable to because $server is not ".
1048: "their home server.");
1049: } elsif ($answer =~ "^refused") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1052: } elsif ($answer =~ "invalid_client") {
1053: &logthis("$server refused to change $uname in $udom password because ".
1054: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1055: }
1056: return $answer;
1.1 albertel 1057: }
1058:
1.169 harris41 1059: # ----------------------- Try to determine user's current authentication scheme
1060:
1061: sub queryauthenticate {
1062: my ($uname,$udom)=@_;
1.456 albertel 1063: my $uhome=&homeserver($uname,$udom);
1064: if (!$uhome) {
1065: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1066: return 'no_host';
1067: }
1068: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1069: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1070: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1071: }
1.456 albertel 1072: return $answer;
1.169 harris41 1073: }
1074:
1.1 albertel 1075: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1076:
1.1 albertel 1077: sub authenticate {
1.1073 raeburn 1078: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1079: $upass=&escape($upass);
1080: $uname= &LONCAPA::clean_username($uname);
1.836 www 1081: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1082: my $newhome;
1.836 www 1083: if ((!$uhome) || ($uhome eq 'no_host')) {
1084: # Maybe the machine was offline and only re-appeared again recently?
1085: &reconlonc();
1086: # One more
1.952 raeburn 1087: $uhome=&homeserver($uname,$udom,1);
1088: if (($uhome eq 'no_host') && $checkdefauth) {
1089: if (defined(&domain($udom,'primary'))) {
1090: $newhome=&domain($udom,'primary');
1091: }
1092: if ($newhome ne '') {
1093: $uhome = $newhome;
1094: }
1095: }
1.836 www 1096: if ((!$uhome) || ($uhome eq 'no_host')) {
1097: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1098: return 'no_host';
1099: }
1.1 albertel 1100: }
1.1073 raeburn 1101: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1102: if ($answer eq 'authorized') {
1.952 raeburn 1103: if ($newhome) {
1104: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1105: return 'no_account_on_host';
1106: } else {
1107: &logthis("User $uname at $udom authorized by $uhome");
1108: return $uhome;
1109: }
1.471 albertel 1110: }
1111: if ($answer eq 'non_authorized') {
1112: &logthis("User $uname at $udom rejected by $uhome");
1113: return 'no_host';
1.9 www 1114: }
1.471 albertel 1115: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1116: return 'no_host';
1117: }
1118:
1.1073 raeburn 1119: sub can_host_session {
1.1074 raeburn 1120: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1121: my $canhost = 1;
1.1074 raeburn 1122: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1123: if (ref($remotesessions) eq 'HASH') {
1124: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1126: $canhost = 0;
1127: } else {
1128: $canhost = 1;
1129: }
1130: }
1131: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1132: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1133: $canhost = 1;
1134: } else {
1135: $canhost = 0;
1136: }
1137: }
1138: if ($canhost) {
1139: if ($remotesessions->{'version'} ne '') {
1140: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1141: if ($reqmajor ne '' && $reqminor ne '') {
1142: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1143: my $major = $1;
1144: my $minor = $2;
1145: if (($major < $reqmajor ) ||
1146: (($major == $reqmajor) && ($minor < $reqminor))) {
1147: $canhost = 0;
1148: }
1149: } else {
1150: $canhost = 0;
1151: }
1152: }
1153: }
1154: }
1155: }
1156: if ($canhost) {
1157: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1158: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1159: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1160: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1161: if (($uint_dom ne '') &&
1162: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1163: $canhost = 0;
1164: } else {
1165: $canhost = 1;
1166: }
1167: }
1168: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1169: if (($uint_dom ne '') &&
1170: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1171: $canhost = 1;
1172: } else {
1173: $canhost = 0;
1174: }
1175: }
1176: }
1177: }
1178: return $canhost;
1179: }
1180:
1.1083 raeburn 1181: sub spare_can_host {
1182: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1183: my $canhost=1;
1.1172.2.62 raeburn 1184: my $try_server_hostname = &hostname($try_server);
1185: my $serverhomeID = &get_server_homeID($try_server_hostname);
1186: my $serverhomedom = &host_domain($serverhomeID);
1187: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1188: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1189: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1190: $canhost = 0;
1191: }
1192: }
1193: if (($canhost) && ($uint_dom)) {
1194: my @intdoms;
1195: my $internet_names = &get_internet_names($try_server);
1196: if (ref($internet_names) eq 'ARRAY') {
1197: @intdoms = @{$internet_names};
1198: }
1199: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1200: my $remoterev = &get_server_loncaparev(undef,$try_server);
1201: $canhost = &can_host_session($udom,$try_server,$remoterev,
1202: $remotesessions,
1203: $defdomdefaults{'hostedsessions'});
1204: }
1.1083 raeburn 1205: }
1206: return $canhost;
1207: }
1208:
1.1123 raeburn 1209: sub this_host_spares {
1210: my ($dom) = @_;
1.1126 raeburn 1211: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1212: my @hosts = ¤t_machine_ids();
1213: foreach my $lonhost (@hosts) {
1214: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1215: $dom_in_use = $dom;
1216: $lonhost_in_use = $lonhost;
1.1123 raeburn 1217: last;
1218: }
1219: }
1.1126 raeburn 1220: if ($dom_in_use ne '') {
1221: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1222: }
1223: if (ref($result) ne 'HASH') {
1224: $lonhost_in_use = $perlvar{'lonHostID'};
1225: $dom_in_use = &host_domain($lonhost_in_use);
1226: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1227: if (ref($result) ne 'HASH') {
1228: $result = \%spareid;
1229: }
1230: }
1231: return $result;
1232: }
1233:
1234: sub spares_for_offload {
1235: my ($dom_in_use,$lonhost_in_use) = @_;
1236: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1237: if (defined($cached)) {
1238: return $result;
1239: } else {
1.1126 raeburn 1240: my $cachetime = 60*60*24;
1241: my %domconfig =
1242: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1243: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1244: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1245: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1246: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1247: }
1248: }
1249: }
1250: }
1.1126 raeburn 1251: return;
1.1123 raeburn 1252: }
1253:
1.1129 raeburn 1254: sub get_lonbalancer_config {
1255: my ($servers) = @_;
1256: my ($currbalancer,$currtargets);
1257: if (ref($servers) eq 'HASH') {
1258: foreach my $server (keys(%{$servers})) {
1259: my %what = (
1260: spareid => 1,
1261: perlvar => 1,
1262: );
1263: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1264: if ($result eq 'ok') {
1265: if (ref($returnhash) eq 'HASH') {
1266: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1267: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1268: $currbalancer = $server;
1269: $currtargets = {};
1270: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1271: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1272: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1273: }
1274: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1275: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1276: }
1277: }
1278: last;
1279: }
1280: }
1281: }
1282: }
1283: }
1284: }
1285: return ($currbalancer,$currtargets);
1286: }
1287:
1288: sub check_loadbalancing {
1.1172.2.88 raeburn 1289: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1290: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1291: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1292: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1293: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1294: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1295: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1296: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1297: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1298: my $domneedscache;
1.1129 raeburn 1299: my $cachetime = 60*60*24;
1300:
1301: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1302: $dom_in_use = $udom;
1303: $homeintdom = 1;
1304: } else {
1305: $dom_in_use = $serverhomedom;
1306: }
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1313: } else {
1314: $domneedscache = $dom_in_use;
1.1129 raeburn 1315: }
1316: }
1317: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1318: ($is_balancer,$currtargets,$currrules) =
1319: &check_balancer_result($result,@hosts);
1.1129 raeburn 1320: if ($is_balancer) {
1321: if (ref($currrules) eq 'HASH') {
1322: if ($homeintdom) {
1323: if ($uname ne '') {
1324: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1325: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1326: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1327: $rule_in_effect = $currrules->{'_LC_author'};
1328: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1329: $rule_in_effect = $currrules->{'_LC_adv'}
1330: }
1331: }
1332: if ($rule_in_effect eq '') {
1333: my %userenv = &userenvironment($udom,$uname,'inststatus');
1334: if ($userenv{'inststatus'} ne '') {
1335: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1336: my ($othertitle,$usertypes,$types) =
1337: &Apache::loncommon::sorted_inst_types($udom);
1338: if (ref($types) eq 'ARRAY') {
1339: foreach my $type (@{$types}) {
1340: if (grep(/^\Q$type\E$/,@statuses)) {
1341: if (exists($currrules->{$type})) {
1342: $rule_in_effect = $currrules->{$type};
1343: }
1344: }
1345: }
1346: }
1347: } else {
1348: if (exists($currrules->{'default'})) {
1349: $rule_in_effect = $currrules->{'default'};
1350: }
1351: }
1352: }
1353: } else {
1354: if (exists($currrules->{'default'})) {
1355: $rule_in_effect = $currrules->{'default'};
1356: }
1357: }
1358: } else {
1359: if ($currrules->{'_LC_external'} ne '') {
1360: $rule_in_effect = $currrules->{'_LC_external'};
1361: }
1362: }
1363: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1364: $uname,$udom);
1365: }
1366: }
1367: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1368: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1369: unless (defined($cached)) {
1370: my %domconfig =
1371: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1372: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1373: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1374: } else {
1375: $domneedscache = $serverhomedom;
1.1129 raeburn 1376: }
1377: }
1378: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1379: ($is_balancer,$currtargets,$currrules) =
1380: &check_balancer_result($result,@hosts);
1381: if ($is_balancer) {
1.1129 raeburn 1382: if (ref($currrules) eq 'HASH') {
1383: if ($currrules->{'_LC_internetdom'} ne '') {
1384: $rule_in_effect = $currrules->{'_LC_internetdom'};
1385: }
1386: }
1387: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1388: $uname,$udom);
1389: }
1390: } else {
1391: if ($perlvar{'lonBalancer'} eq 'yes') {
1392: $is_balancer = 1;
1393: $offloadto = &this_host_spares($dom_in_use);
1394: }
1.1172.2.75 raeburn 1395: unless (defined($cached)) {
1396: $domneedscache = $serverhomedom;
1397: }
1.1129 raeburn 1398: }
1399: } else {
1400: if ($perlvar{'lonBalancer'} eq 'yes') {
1401: $is_balancer = 1;
1402: $offloadto = &this_host_spares($dom_in_use);
1403: }
1.1172.2.75 raeburn 1404: unless (defined($cached)) {
1405: $domneedscache = $serverhomedom;
1406: }
1407: }
1408: if ($domneedscache) {
1409: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1410: }
1.1172.2.5 raeburn 1411: if ($is_balancer) {
1412: my $lowest_load = 30000;
1413: if (ref($offloadto) eq 'HASH') {
1414: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1415: foreach my $try_server (@{$offloadto->{'primary'}}) {
1416: ($otherserver,$lowest_load) =
1417: &compare_server_load($try_server,$otherserver,$lowest_load);
1418: }
1.1129 raeburn 1419: }
1.1172.2.5 raeburn 1420: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1421:
1.1172.2.5 raeburn 1422: if (!$found_server) {
1423: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1424: foreach my $try_server (@{$offloadto->{'default'}}) {
1425: ($otherserver,$lowest_load) =
1426: &compare_server_load($try_server,$otherserver,$lowest_load);
1427: }
1428: }
1429: }
1430: } elsif (ref($offloadto) eq 'ARRAY') {
1431: if (@{$offloadto} == 1) {
1432: $otherserver = $offloadto->[0];
1433: } elsif (@{$offloadto} > 1) {
1434: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1435: ($otherserver,$lowest_load) =
1436: &compare_server_load($try_server,$otherserver,$lowest_load);
1437: }
1438: }
1439: }
1.1172.2.88 raeburn 1440: unless ($caller eq 'login') {
1441: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1442: $is_balancer = 0;
1443: if ($uname ne '' && $udom ne '') {
1444: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5 raeburn 1445:
1.1172.2.88 raeburn 1446: &appenv({'user.loadbalexempt' => $lonhost,
1447: 'user.loadbalcheck.time' => time});
1448: }
1.1172.2.5 raeburn 1449: }
1.1129 raeburn 1450: }
1451: }
1452: }
1453: return ($is_balancer,$otherserver);
1454: }
1455:
1.1172.2.12 raeburn 1456: sub check_balancer_result {
1457: my ($result,@hosts) = @_;
1458: my ($is_balancer,$currtargets,$currrules);
1459: if (ref($result) eq 'HASH') {
1460: if ($result->{'lonhost'} ne '') {
1461: my $currbalancer = $result->{'lonhost'};
1462: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1463: $is_balancer = 1;
1464: $currtargets = $result->{'targets'};
1465: $currrules = $result->{'rules'};
1466: }
1467: } else {
1468: foreach my $key (keys(%{$result})) {
1469: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1470: (ref($result->{$key}) eq 'HASH')) {
1471: $is_balancer = 1;
1472: $currrules = $result->{$key}{'rules'};
1473: $currtargets = $result->{$key}{'targets'};
1474: last;
1475: }
1476: }
1477: }
1478: }
1479: return ($is_balancer,$currtargets,$currrules);
1480: }
1481:
1.1129 raeburn 1482: sub get_loadbalancer_targets {
1483: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1484: my $offloadto;
1.1172.2.4 raeburn 1485: if ($rule_in_effect eq 'none') {
1486: return [$perlvar{'lonHostID'}];
1487: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1488: $offloadto = $currtargets;
1489: } else {
1490: if ($rule_in_effect eq 'homeserver') {
1491: my $homeserver = &homeserver($uname,$udom);
1492: if ($homeserver ne 'no_host') {
1493: $offloadto = [$homeserver];
1494: }
1495: } elsif ($rule_in_effect eq 'externalbalancer') {
1496: my %domconfig =
1497: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1498: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1499: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1500: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1501: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1502: }
1503: }
1504: } else {
1.1172.2.7 raeburn 1505: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1506: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1507: if (&hostname($remotebalancer) ne '') {
1508: $offloadto = [$remotebalancer];
1509: }
1510: }
1511: } elsif (&hostname($rule_in_effect) ne '') {
1512: $offloadto = [$rule_in_effect];
1513: }
1514: }
1515: return $offloadto;
1516: }
1517:
1.1127 raeburn 1518: sub internet_dom_servers {
1519: my ($dom) = @_;
1520: my (%uniqservers,%servers);
1521: my $primaryserver = &hostname(&domain($dom,'primary'));
1522: my @machinedoms = &machine_domains($primaryserver);
1523: foreach my $mdom (@machinedoms) {
1524: my %currservers = %servers;
1525: my %server = &get_servers($mdom);
1526: %servers = (%currservers,%server);
1527: }
1528: my %by_hostname;
1529: foreach my $id (keys(%servers)) {
1530: push(@{$by_hostname{$servers{$id}}},$id);
1531: }
1532: foreach my $hostname (sort(keys(%by_hostname))) {
1533: if (@{$by_hostname{$hostname}} > 1) {
1534: my $match = 0;
1535: foreach my $id (@{$by_hostname{$hostname}}) {
1536: if (&host_domain($id) eq $dom) {
1537: $uniqservers{$id} = $hostname;
1538: $match = 1;
1539: }
1540: }
1541: unless ($match) {
1542: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1543: }
1544: } else {
1545: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1546: }
1547: }
1548: return %uniqservers;
1549: }
1550:
1.1 albertel 1551: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1552:
1.599 albertel 1553: my %homecache;
1.1 albertel 1554: sub homeserver {
1.230 stredwic 1555: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1556: my $index="$uname:$udom";
1.426 albertel 1557:
1.599 albertel 1558: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1559:
1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1562: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1563: exists($badServerCache{$tryserver}));
1.841 albertel 1564:
1565: my $answer=reply("home:$udom:$uname",$tryserver);
1566: if ($answer eq 'found') {
1567: delete($badServerCache{$tryserver});
1568: return $homecache{$index}=$tryserver;
1569: } elsif ($answer eq 'no_host') {
1570: $badServerCache{$tryserver}=1;
1571: }
1.1 albertel 1572: }
1573: return 'no_host';
1.70 www 1574: }
1575:
1576: # ------------------------------------- Find the usernames behind a list of IDs
1577:
1578: sub idget {
1579: my ($udom,@ids)=@_;
1580: my %returnhash=();
1581:
1.841 albertel 1582: my %servers = &get_servers($udom,'library');
1583: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1584: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1585: $idlist=~tr/A-Z/a-z/;
1586: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1587: my @answer=();
1588: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1589: @answer=split(/\&/,$reply);
1590: } ;
1591: my $i;
1592: for ($i=0;$i<=$#ids;$i++) {
1593: if ($answer[$i]) {
1.1172.2.73 raeburn 1594: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1595: }
1596: }
1597: }
1.70 www 1598: return %returnhash;
1599: }
1600:
1601: # ------------------------------------- Find the IDs behind a list of usernames
1602:
1603: sub idrget {
1604: my ($udom,@unames)=@_;
1605: my %returnhash=();
1.800 albertel 1606: foreach my $uname (@unames) {
1607: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1608: }
1.70 www 1609: return %returnhash;
1610: }
1611:
1612: # ------------------------------- Store away a list of names and associated IDs
1613:
1614: sub idput {
1615: my ($udom,%ids)=@_;
1616: my %servers=();
1.800 albertel 1617: foreach my $uname (keys(%ids)) {
1618: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1619: my $uhom=&homeserver($uname,$udom);
1.70 www 1620: if ($uhom ne 'no_host') {
1.800 albertel 1621: my $id=&escape($ids{$uname});
1.70 www 1622: $id=~tr/A-Z/a-z/;
1.800 albertel 1623: my $esc_unam=&escape($uname);
1.70 www 1624: if ($servers{$uhom}) {
1.800 albertel 1625: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1626: } else {
1.800 albertel 1627: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1628: }
1629: }
1.191 harris41 1630: }
1.800 albertel 1631: foreach my $server (keys(%servers)) {
1632: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1633: }
1.344 www 1634: }
1635:
1.1172.2.30 raeburn 1636: # ---------------------------------------- Delete unwanted IDs from ids.db file
1637:
1638: sub iddel {
1639: my ($udom,$idshashref,$uhome)=@_;
1640: my %result=();
1641: unless (ref($idshashref) eq 'HASH') {
1642: return %result;
1643: }
1644: my %servers=();
1645: while (my ($id,$uname) = each(%{$idshashref})) {
1646: my $uhom;
1647: if ($uhome) {
1648: $uhom = $uhome;
1649: } else {
1650: $uhom=&homeserver($uname,$udom);
1651: }
1652: if ($uhom ne 'no_host') {
1653: if ($servers{$uhom}) {
1654: $servers{$uhom}.='&'.&escape($id);
1655: } else {
1656: $servers{$uhom}=&escape($id);
1657: }
1658: }
1659: }
1660: foreach my $server (keys(%servers)) {
1661: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1662: }
1663: return %result;
1664: }
1665:
1.1023 raeburn 1666: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1667: sub dump_dom {
1.1165 droeschl 1668: my ($namespace, $udom, $regexp) = @_;
1669:
1670: $udom ||= $env{'user.domain'};
1671:
1672: return () unless $udom;
1673:
1674: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1675: }
1676:
1.1023 raeburn 1677: # ------------------------------------------ get items from domain db files
1.806 raeburn 1678:
1679: sub get_dom {
1.860 raeburn 1680: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1681: return if ($udom eq 'public');
1.806 raeburn 1682: my $items='';
1683: foreach my $item (@$storearr) {
1684: $items.=&escape($item).'&';
1685: }
1686: $items=~s/\&$//;
1.860 raeburn 1687: if (!$udom) {
1688: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1689: return if ($udom eq 'public');
1.860 raeburn 1690: if (defined(&domain($udom,'primary'))) {
1691: $uhome=&domain($udom,'primary');
1692: } else {
1.874 albertel 1693: undef($uhome);
1.860 raeburn 1694: }
1695: } else {
1696: if (!$uhome) {
1697: if (defined(&domain($udom,'primary'))) {
1698: $uhome=&domain($udom,'primary');
1699: }
1700: }
1701: }
1702: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1703: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1704: my %returnhash;
1.875 albertel 1705: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1706: return %returnhash;
1707: }
1.806 raeburn 1708: my @pairs=split(/\&/,$rep);
1709: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1710: return @pairs;
1711: }
1712: my $i=0;
1713: foreach my $item (@$storearr) {
1714: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1715: $i++;
1716: }
1717: return %returnhash;
1718: } else {
1.880 banghart 1719: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1720: }
1721: }
1722:
1723: # -------------------------------------------- put items in domain db files
1724:
1725: sub put_dom {
1.860 raeburn 1726: my ($namespace,$storehash,$udom,$uhome)=@_;
1727: if (!$udom) {
1728: $udom=$env{'user.domain'};
1729: if (defined(&domain($udom,'primary'))) {
1730: $uhome=&domain($udom,'primary');
1731: } else {
1.874 albertel 1732: undef($uhome);
1.860 raeburn 1733: }
1734: } else {
1735: if (!$uhome) {
1736: if (defined(&domain($udom,'primary'))) {
1737: $uhome=&domain($udom,'primary');
1738: }
1739: }
1740: }
1741: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1742: my $items='';
1743: foreach my $item (keys(%$storehash)) {
1744: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1745: }
1746: $items=~s/\&$//;
1747: return &reply("putdom:$udom:$namespace:$items",$uhome);
1748: } else {
1.860 raeburn 1749: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1750: }
1751: }
1752:
1.1023 raeburn 1753: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1754: sub newput_dom {
1.1023 raeburn 1755: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1756: my $result;
1757: if (!$udom) {
1758: $udom=$env{'user.domain'};
1759: }
1.1023 raeburn 1760: if ($udom) {
1761: my $uname = &get_domainconfiguser($udom);
1762: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1763: }
1764: return $result;
1765: }
1766:
1.1023 raeburn 1767: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1768: sub del_dom {
1.1023 raeburn 1769: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1770: if (ref($storearr) eq 'ARRAY') {
1771: if (!$udom) {
1772: $udom=$env{'user.domain'};
1773: }
1.1023 raeburn 1774: if ($udom) {
1775: my $uname = &get_domainconfiguser($udom);
1776: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1777: }
1778: }
1779: }
1780:
1.1023 raeburn 1781: # ----------------------------------construct domainconfig user for a domain
1782: sub get_domainconfiguser {
1783: my ($udom) = @_;
1784: return $udom.'-domainconfig';
1785: }
1786:
1.837 raeburn 1787: sub retrieve_inst_usertypes {
1788: my ($udom) = @_;
1789: my (%returnhash,@order);
1.989 raeburn 1790: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1791: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1792: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1793: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1794: } else {
1795: if (defined(&domain($udom,'primary'))) {
1796: my $uhome=&domain($udom,'primary');
1797: my $rep=&reply("inst_usertypes:$udom",$uhome);
1798: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1799: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1800: return (\%returnhash,\@order);
1801: }
1802: my ($hashitems,$orderitems) = split(/:/,$rep);
1803: my @pairs=split(/\&/,$hashitems);
1804: foreach my $item (@pairs) {
1805: my ($key,$value)=split(/=/,$item,2);
1806: $key = &unescape($key);
1807: next if ($key =~ /^error: 2 /);
1808: $returnhash{$key}=&thaw_unescape($value);
1809: }
1810: my @esc_order = split(/\&/,$orderitems);
1811: foreach my $item (@esc_order) {
1812: push(@order,&unescape($item));
1813: }
1814: } else {
1.1172.2.44 raeburn 1815: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1816: }
1.1172.2.44 raeburn 1817: return (\%returnhash,\@order);
1.837 raeburn 1818: }
1819: }
1820:
1.868 raeburn 1821: sub is_domainimage {
1822: my ($url) = @_;
1.1172.2.74 raeburn 1823: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1824: if (&domain($1) ne '') {
1825: return '1';
1826: }
1827: }
1828: return;
1829: }
1830:
1.899 raeburn 1831: sub inst_directory_query {
1832: my ($srch) = @_;
1833: my $udom = $srch->{'srchdomain'};
1834: my %results;
1835: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1836: my $outcome;
1.899 raeburn 1837: if ($homeserver ne '') {
1.904 albertel 1838: my $queryid=&reply("querysend:instdirsearch:".
1839: &escape($srch->{'srchby'}).':'.
1840: &escape($srch->{'srchterm'}).':'.
1841: &escape($srch->{'srchtype'}),$homeserver);
1842: my $host=&hostname($homeserver);
1843: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 1844: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1845: return;
1846: }
1847: my $response = &get_query_reply($queryid);
1848: my $maxtries = 5;
1849: my $tries = 1;
1850: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1851: $response = &get_query_reply($queryid);
1852: $tries ++;
1853: }
1854:
1855: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1856: if ($response eq 'unavailable') {
1857: $outcome = $response;
1858: } else {
1859: $outcome = 'ok';
1860: my @matches = split(/\n/,$response);
1861: foreach my $match (@matches) {
1862: my ($key,$value) = split(/=/,$match);
1863: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1864: }
1.899 raeburn 1865: }
1866: }
1867: }
1.909 raeburn 1868: return ($outcome,%results);
1.899 raeburn 1869: }
1870:
1871: sub usersearch {
1872: my ($srch) = @_;
1873: my $dom = $srch->{'srchdomain'};
1874: my %results;
1875: my %libserv = &all_library();
1876: my $query = 'usersearch';
1877: foreach my $tryserver (keys(%libserv)) {
1878: if (&host_domain($tryserver) eq $dom) {
1879: my $host=&hostname($tryserver);
1880: my $queryid=
1.911 raeburn 1881: &reply("querysend:".&escape($query).':'.
1882: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1883: &escape($srch->{'srchtype'}).':'.
1884: &escape($srch->{'srchterm'}),$tryserver);
1885: if ($queryid !~/^\Q$host\E\_/) {
1886: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1887: next;
1.899 raeburn 1888: }
1889: my $reply = &get_query_reply($queryid);
1890: my $maxtries = 1;
1891: my $tries = 1;
1892: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1893: $reply = &get_query_reply($queryid);
1894: $tries ++;
1895: }
1896: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1897: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1898: } else {
1.911 raeburn 1899: my @matches;
1900: if ($reply =~ /\n/) {
1901: @matches = split(/\n/,$reply);
1902: } else {
1903: @matches = split(/\&/,$reply);
1904: }
1.899 raeburn 1905: foreach my $match (@matches) {
1906: my ($uname,$udom,%userhash);
1.911 raeburn 1907: foreach my $entry (split(/:/,$match)) {
1908: my ($key,$value) =
1909: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1910: $userhash{$key} = $value;
1911: if ($key eq 'username') {
1912: $uname = $value;
1913: } elsif ($key eq 'domain') {
1914: $udom = $value;
1.911 raeburn 1915: }
1.899 raeburn 1916: }
1917: $results{$uname.':'.$udom} = \%userhash;
1918: }
1919: }
1920: }
1921: }
1922: return %results;
1923: }
1924:
1.912 raeburn 1925: sub get_instuser {
1926: my ($udom,$uname,$id) = @_;
1927: my $homeserver = &domain($udom,'primary');
1928: my ($outcome,%results);
1929: if ($homeserver ne '') {
1930: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1931: &escape($id).':'.&escape($udom),$homeserver);
1932: my $host=&hostname($homeserver);
1933: if ($queryid !~/^\Q$host\E\_/) {
1934: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1935: return;
1936: }
1937: my $response = &get_query_reply($queryid);
1938: my $maxtries = 5;
1939: my $tries = 1;
1940: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1941: $response = &get_query_reply($queryid);
1942: $tries ++;
1943: }
1944: if (!&error($response) && $response ne 'refused') {
1945: if ($response eq 'unavailable') {
1946: $outcome = $response;
1947: } else {
1948: $outcome = 'ok';
1949: my @matches = split(/\n/,$response);
1950: foreach my $match (@matches) {
1951: my ($key,$value) = split(/=/,$match);
1952: $results{&unescape($key)} = &thaw_unescape($value);
1953: }
1954: }
1955: }
1956: }
1957: my %userinfo;
1958: if (ref($results{$uname}) eq 'HASH') {
1959: %userinfo = %{$results{$uname}};
1960: }
1961: return ($outcome,%userinfo);
1962: }
1963:
1.1172.2.69 raeburn 1964: sub get_multiple_instusers {
1965: my ($udom,$users,$caller) = @_;
1966: my ($outcome,$results);
1967: if (ref($users) eq 'HASH') {
1968: my $count = keys(%{$users});
1969: my $requested = &freeze_escape($users);
1970: my $homeserver = &domain($udom,'primary');
1971: if ($homeserver ne '') {
1972: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1973: my $host=&hostname($homeserver);
1974: if ($queryid !~/^\Q$host\E\_/) {
1975: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1976: ' for host: '.$homeserver.'in domain '.$udom);
1977: return ($outcome,$results);
1978: }
1979: my $response = &get_query_reply($queryid);
1980: my $maxtries = 5;
1981: if ($count > 100) {
1982: $maxtries = 1+int($count/20);
1983: }
1984: my $tries = 1;
1985: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1986: $response = &get_query_reply($queryid);
1987: $tries ++;
1988: }
1989: if ($response eq '') {
1990: $results = {};
1991: foreach my $key (keys(%{$users})) {
1992: my ($uname,$id);
1993: if ($caller eq 'id') {
1994: $id = $key;
1995: } else {
1996: $uname = $key;
1997: }
1998: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1999: $outcome = $resp;
2000: if ($resp eq 'ok') {
2001: %{$results} = (%{$results}, %info);
2002: } else {
2003: last;
2004: }
2005: }
2006: } elsif(!&error($response) && ($response ne 'refused')) {
2007: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2008: $outcome = $response;
2009: } else {
2010: ($outcome,my $userdata) = split(/=/,$response,2);
2011: if ($outcome eq 'ok') {
2012: $results = &thaw_unescape($userdata);
2013: }
2014: }
2015: }
2016: }
2017: }
2018: return ($outcome,$results);
2019: }
2020:
1.912 raeburn 2021: sub inst_rulecheck {
1.923 raeburn 2022: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2023: my %returnhash;
2024: if ($udom ne '') {
2025: if (ref($rules) eq 'ARRAY') {
2026: @{$rules} = map {&escape($_);} (@{$rules});
2027: my $rulestr = join(':',@{$rules});
2028: my $homeserver=&domain($udom,'primary');
2029: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2030: my $response;
2031: if ($item eq 'username') {
2032: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2033: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2034: $homeserver));
1.923 raeburn 2035: } elsif ($item eq 'id') {
2036: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2037: ':'.&escape($id).':'.$rulestr,
2038: $homeserver));
1.945 raeburn 2039: } elsif ($item eq 'selfcreate') {
2040: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2041: &escape($udom).':'.&escape($uname).
2042: ':'.$rulestr,$homeserver));
1.923 raeburn 2043: }
1.912 raeburn 2044: if ($response ne 'refused') {
2045: my @pairs=split(/\&/,$response);
2046: foreach my $item (@pairs) {
2047: my ($key,$value)=split(/=/,$item,2);
2048: $key = &unescape($key);
2049: next if ($key =~ /^error: 2 /);
2050: $returnhash{$key}=&thaw_unescape($value);
2051: }
2052: }
2053: }
2054: }
2055: }
2056: return %returnhash;
2057: }
2058:
2059: sub inst_userrules {
1.923 raeburn 2060: my ($udom,$check) = @_;
1.912 raeburn 2061: my (%ruleshash,@ruleorder);
2062: if ($udom ne '') {
2063: my $homeserver=&domain($udom,'primary');
2064: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2065: my $response;
2066: if ($check eq 'id') {
2067: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2068: $homeserver);
1.943 raeburn 2069: } elsif ($check eq 'email') {
2070: $response=&reply('instemailrules:'.&escape($udom),
2071: $homeserver);
1.923 raeburn 2072: } else {
2073: $response=&reply('instuserrules:'.&escape($udom),
2074: $homeserver);
2075: }
1.912 raeburn 2076: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2077: ($response ne 'unknown_cmd') &&
1.912 raeburn 2078: ($response ne 'no_such_host')) {
2079: my ($hashitems,$orderitems) = split(/:/,$response);
2080: my @pairs=split(/\&/,$hashitems);
2081: foreach my $item (@pairs) {
2082: my ($key,$value)=split(/=/,$item,2);
2083: $key = &unescape($key);
2084: next if ($key =~ /^error: 2 /);
2085: $ruleshash{$key}=&thaw_unescape($value);
2086: }
2087: my @esc_order = split(/\&/,$orderitems);
2088: foreach my $item (@esc_order) {
2089: push(@ruleorder,&unescape($item));
2090: }
2091: }
2092: }
2093: }
2094: return (\%ruleshash,\@ruleorder);
2095: }
2096:
1.976 raeburn 2097: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2098:
2099: sub get_domain_defaults {
1.1172.2.35 raeburn 2100: my ($domain,$ignore_cache) = @_;
2101: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2102: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2103: unless ($ignore_cache) {
2104: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2105: if (defined($cached)) {
2106: if (ref($result) eq 'HASH') {
2107: return %{$result};
2108: }
1.943 raeburn 2109: }
2110: }
2111: my %domdefaults;
2112: my %domconfig =
1.989 raeburn 2113: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2114: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2115: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2116: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2117: 'coursecategories','autoenroll',
2118: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2119: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2120: if (ref($domconfig{'defaults'}) eq 'HASH') {
2121: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2122: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2123: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2124: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2125: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2126: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2127: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2128: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2129: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2130: } else {
2131: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2132: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2133: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2134: }
1.976 raeburn 2135: if (ref($domconfig{'quotas'}) eq 'HASH') {
2136: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2137: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2138: } else {
2139: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2140: }
1.1172.2.6 raeburn 2141: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2142: foreach my $item (@usertools) {
2143: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2144: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2145: }
2146: }
1.1172.2.29 raeburn 2147: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2148: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2149: }
1.976 raeburn 2150: }
1.985 raeburn 2151: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2152: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2153: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2154: }
2155: }
1.1172.2.9 raeburn 2156: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2157: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2158: }
1.989 raeburn 2159: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2160: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2161: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2162: }
2163: }
1.1047 raeburn 2164: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2165: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2166: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2167: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2168: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2169: }
1.1172.2.41 raeburn 2170: foreach my $type (@coursetypes) {
2171: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2172: unless ($type eq 'community') {
2173: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2174: }
2175: }
2176: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2177: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2178: }
1.1172.2.60 raeburn 2179: if ($domdefaults{'postsubmit'} eq 'on') {
2180: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2181: $domdefaults{$type.'postsubtimeout'} =
2182: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2183: }
2184: }
1.1172.2.30 raeburn 2185: }
1.1172.2.67 raeburn 2186: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2187: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2188: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2189: if (@clonecodes) {
2190: $domdefaults{'canclone'} = join('+',@clonecodes);
2191: }
2192: }
2193: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2194: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2195: }
1.1172.2.103 raeburn 2196: if ($domconfig{'coursedefaults'}{'texengine'}) {
2197: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2198: }
1.1047 raeburn 2199: }
1.1073 raeburn 2200: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2201: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2202: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2203: }
2204: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2205: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2206: }
1.1172.2.62 raeburn 2207: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2208: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2209: }
1.1073 raeburn 2210: }
1.1172.2.41 raeburn 2211: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2212: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2213: my @settings = ('types','registered','enroll_dates','access_dates','section',
2214: 'approval','limit');
2215: foreach my $type (@coursetypes) {
2216: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2217: my @mgrdc = ();
2218: foreach my $item (@settings) {
2219: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2220: push(@mgrdc,$item);
2221: }
2222: }
2223: if (@mgrdc) {
2224: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2225: }
2226: }
2227: }
2228: }
2229: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2230: foreach my $type (@coursetypes) {
2231: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2232: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2233: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2234: }
2235: }
2236: }
2237: }
2238: }
1.1172.2.46 raeburn 2239: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2240: $domdefaults{'catauth'} = 'std';
2241: $domdefaults{'catunauth'} = 'std';
2242: if ($domconfig{'coursecategories'}{'auth'}) {
2243: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2244: }
2245: if ($domconfig{'coursecategories'}{'unauth'}) {
2246: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2247: }
2248: }
1.1172.2.76 raeburn 2249: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2250: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2251: }
1.1172.2.89 raeburn 2252: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2253: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2254: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2255: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2256: }
2257: }
1.1172.2.23 raeburn 2258: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2259: return %domdefaults;
2260: }
2261:
1.344 www 2262: # --------------------------------------------------- Assign a key to a student
2263:
2264: sub assign_access_key {
1.364 www 2265: #
2266: # a valid key looks like uname:udom#comments
2267: # comments are being appended
2268: #
1.498 www 2269: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2270: $kdom=
1.620 albertel 2271: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2272: $knum=
1.620 albertel 2273: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2274: $cdom=
1.620 albertel 2275: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2276: $cnum=
1.620 albertel 2277: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2278: $udom=$env{'user.name'} unless (defined($udom));
2279: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2280: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2281: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2282: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2283: # assigned to this person
2284: # - this should not happen,
1.345 www 2285: # unless something went wrong
2286: # the first time around
2287: # ready to assign
1.364 www 2288: $logentry=$1.'; '.$logentry;
1.496 www 2289: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2290: $kdom,$knum) eq 'ok') {
1.345 www 2291: # key now belongs to user
1.346 www 2292: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2293: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2294: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2295: return 'ok';
2296: } else {
2297: return
2298: 'error: Count not permanently assign key, will need to be re-entered later.';
2299: }
2300: } else {
2301: return 'error: Could not assign key, try again later.';
2302: }
1.364 www 2303: } elsif (!$existing{$ckey}) {
1.345 www 2304: # the key does not exist
2305: return 'error: The key does not exist';
2306: } else {
2307: # the key is somebody else's
2308: return 'error: The key is already in use';
2309: }
1.344 www 2310: }
2311:
1.364 www 2312: # ------------------------------------------ put an additional comment on a key
2313:
2314: sub comment_access_key {
2315: #
2316: # a valid key looks like uname:udom#comments
2317: # comments are being appended
2318: #
2319: my ($ckey,$cdom,$cnum,$logentry)=@_;
2320: $cdom=
1.620 albertel 2321: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2322: $cnum=
1.620 albertel 2323: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2324: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2325: if ($existing{$ckey}) {
2326: $existing{$ckey}.='; '.$logentry;
2327: # ready to assign
1.367 www 2328: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2329: $cdom,$cnum) eq 'ok') {
2330: return 'ok';
2331: } else {
2332: return 'error: Count not store comment.';
2333: }
2334: } else {
2335: # the key does not exist
2336: return 'error: The key does not exist';
2337: }
2338: }
2339:
1.344 www 2340: # ------------------------------------------------------ Generate a set of keys
2341:
2342: sub generate_access_keys {
1.364 www 2343: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2344: $cdom=
1.620 albertel 2345: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2346: $cnum=
1.620 albertel 2347: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2348: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2349: unless (($cdom) && ($cnum)) { return 0; }
2350: if ($number>10000) { return 0; }
2351: sleep(2); # make sure don't get same seed twice
2352: srand(time()^($$+($$<<15))); # from "Programming Perl"
2353: my $total=0;
2354: for (my $i=1;$i<=$number;$i++) {
2355: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2356: sprintf("%lx",int(100000*rand)).'-'.
2357: sprintf("%lx",int(100000*rand));
2358: $newkey=~s/1/g/g; # folks mix up 1 and l
2359: $newkey=~s/0/h/g; # and also 0 and O
2360: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2361: if ($existing{$newkey}) {
2362: $i--;
2363: } else {
1.364 www 2364: if (&put('accesskeys',
2365: { $newkey => '# generated '.localtime().
1.620 albertel 2366: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2367: '; '.$logentry },
2368: $cdom,$cnum) eq 'ok') {
1.344 www 2369: $total++;
2370: }
2371: }
2372: }
1.620 albertel 2373: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2374: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2375: return $total;
2376: }
2377:
2378: # ------------------------------------------------------- Validate an accesskey
2379:
2380: sub validate_access_key {
2381: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2382: $cdom=
1.620 albertel 2383: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2384: $cnum=
1.620 albertel 2385: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2386: $udom=$env{'user.domain'} unless (defined($udom));
2387: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2388: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2389: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2390: }
2391:
2392: # ------------------------------------- Find the section of student in a course
1.652 albertel 2393: sub devalidate_getsection_cache {
2394: my ($udom,$unam,$courseid)=@_;
2395: my $hashid="$udom:$unam:$courseid";
2396: &devalidate_cache_new('getsection',$hashid);
2397: }
1.298 matthew 2398:
1.815 albertel 2399: sub courseid_to_courseurl {
2400: my ($courseid) = @_;
2401: #already url style courseid
2402: return $courseid if ($courseid =~ m{^/});
2403:
2404: if (exists($env{'course.'.$courseid.'.num'})) {
2405: my $cnum = $env{'course.'.$courseid.'.num'};
2406: my $cdom = $env{'course.'.$courseid.'.domain'};
2407: return "/$cdom/$cnum";
2408: }
2409:
2410: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2411: if (exists($courseinfo{'num'})) {
2412: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2413: }
2414:
2415: return undef;
2416: }
2417:
1.298 matthew 2418: sub getsection {
2419: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2420: my $cachetime=1800;
1.551 albertel 2421:
2422: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2423: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2424: if (defined($cached)) { return $result; }
2425:
1.298 matthew 2426: my %Pending;
2427: my %Expired;
2428: #
2429: # Each role can either have not started yet (pending), be active,
2430: # or have expired.
2431: #
2432: # If there is an active role, we are done.
2433: #
2434: # If there is more than one role which has not started yet,
2435: # choose the one which will start sooner
2436: # If there is one role which has not started yet, return it.
2437: #
2438: # If there is more than one expired role, choose the one which ended last.
2439: # If there is a role which has expired, return it.
2440: #
1.815 albertel 2441: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2442: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2443: foreach my $key (keys(%roleshash)) {
1.479 albertel 2444: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2445: my $section=$1;
2446: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2447: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2448: my $now=time;
1.548 albertel 2449: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2450: $Expired{$end}=$section;
2451: next;
2452: }
1.548 albertel 2453: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2454: $Pending{$start}=$section;
2455: next;
2456: }
1.599 albertel 2457: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2458: }
2459: #
2460: # Presumedly there will be few matching roles from the above
2461: # loop and the sorting time will be negligible.
2462: if (scalar(keys(%Pending))) {
2463: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2464: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2465: }
2466: if (scalar(keys(%Expired))) {
2467: my @sorted = sort {$a <=> $b} keys(%Expired);
2468: my $time = pop(@sorted);
1.599 albertel 2469: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2470: }
1.599 albertel 2471: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2472: }
1.70 www 2473:
1.599 albertel 2474: sub save_cache {
2475: &purge_remembered();
1.722 albertel 2476: #&Apache::loncommon::validate_page();
1.620 albertel 2477: undef(%env);
1.780 albertel 2478: undef($env_loaded);
1.599 albertel 2479: }
1.452 albertel 2480:
1.599 albertel 2481: my $to_remember=-1;
2482: my %remembered;
2483: my %accessed;
2484: my $kicks=0;
2485: my $hits=0;
1.849 albertel 2486: sub make_key {
2487: my ($name,$id) = @_;
1.872 albertel 2488: if (length($id) > 65
2489: && length(&escape($id)) > 200) {
2490: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2491: }
1.849 albertel 2492: return &escape($name.':'.$id);
2493: }
2494:
1.599 albertel 2495: sub devalidate_cache_new {
2496: my ($name,$id,$debug) = @_;
2497: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2498: my $remembered_id=$name.':'.$id;
1.849 albertel 2499: $id=&make_key($name,$id);
1.599 albertel 2500: $memcache->delete($id);
1.1172.2.81 raeburn 2501: delete($remembered{$remembered_id});
2502: delete($accessed{$remembered_id});
1.599 albertel 2503: }
2504:
2505: sub is_cached_new {
2506: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2507: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2508: # keys in %remembered hash, which persists for
2509: # duration of request (no restriction on key length).
2510: if (exists($remembered{$remembered_id})) {
2511: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2512: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2513: $hits++;
1.1172.2.81 raeburn 2514: return ($remembered{$remembered_id},1);
1.599 albertel 2515: }
1.1172.2.81 raeburn 2516: $id=&make_key($name,$id);
1.599 albertel 2517: my $value = $memcache->get($id);
2518: if (!(defined($value))) {
2519: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2520: return (undef,undef);
1.416 albertel 2521: }
1.599 albertel 2522: if ($value eq '__undef__') {
2523: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2524: $value=undef;
2525: }
1.1172.2.81 raeburn 2526: &make_room($remembered_id,$value,$debug);
1.599 albertel 2527: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2528: return ($value,1);
2529: }
2530:
2531: sub do_cache_new {
2532: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2533: my $remembered_id=$name.':'.$id;
1.849 albertel 2534: $id=&make_key($name,$id);
1.599 albertel 2535: my $setvalue=$value;
2536: if (!defined($setvalue)) {
2537: $setvalue='__undef__';
2538: }
1.623 albertel 2539: if (!defined($time) ) {
2540: $time=600;
2541: }
1.599 albertel 2542: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2543: my $result = $memcache->set($id,$setvalue,$time);
2544: if (! $result) {
1.872 albertel 2545: &logthis("caching of id -> $id failed");
1.910 albertel 2546: $memcache->disconnect_all();
1.872 albertel 2547: }
1.600 albertel 2548: # need to make a copy of $value
1.1172.2.81 raeburn 2549: &make_room($remembered_id,$value,$debug);
1.599 albertel 2550: return $value;
2551: }
2552:
2553: sub make_room {
1.1172.2.81 raeburn 2554: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2555:
1.1172.2.81 raeburn 2556: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2557: : $value;
1.599 albertel 2558: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2559: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2560: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2561: my $to_kick;
2562: my $max_time=0;
2563: foreach my $other (keys(%accessed)) {
2564: if (&tv_interval($accessed{$other}) > $max_time) {
2565: $to_kick=$other;
2566: $max_time=&tv_interval($accessed{$other});
2567: }
2568: }
2569: delete($remembered{$to_kick});
2570: delete($accessed{$to_kick});
2571: $kicks++;
2572: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2573: return;
2574: }
2575:
1.599 albertel 2576: sub purge_remembered {
1.604 albertel 2577: #&logthis("Tossing ".scalar(keys(%remembered)));
2578: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2579: undef(%remembered);
2580: undef(%accessed);
1.428 albertel 2581: }
1.70 www 2582: # ------------------------------------- Read an entry from a user's environment
2583:
2584: sub userenvironment {
2585: my ($udom,$unam,@what)=@_;
1.976 raeburn 2586: my $items;
2587: foreach my $item (@what) {
2588: $items.=&escape($item).'&';
2589: }
2590: $items=~s/\&$//;
1.70 www 2591: my %returnhash=();
1.1009 raeburn 2592: my $uhome = &homeserver($unam,$udom);
2593: unless ($uhome eq 'no_host') {
2594: my @answer=split(/\&/,
2595: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2596: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2597: return %returnhash;
2598: }
1.1009 raeburn 2599: my $i;
2600: for ($i=0;$i<=$#what;$i++) {
2601: $returnhash{$what[$i]}=&unescape($answer[$i]);
2602: }
1.70 www 2603: }
2604: return %returnhash;
1.1 albertel 2605: }
2606:
1.617 albertel 2607: # ---------------------------------------------------------- Get a studentphoto
2608: sub studentphoto {
2609: my ($udom,$unam,$ext) = @_;
2610: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2611: if (defined($env{'request.course.id'})) {
1.708 raeburn 2612: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2613: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2614: return(&retrievestudentphoto($udom,$unam,$ext));
2615: } else {
2616: my ($result,$perm_reqd)=
1.707 albertel 2617: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2618: if ($result eq 'ok') {
2619: if (!($perm_reqd eq 'yes')) {
2620: return(&retrievestudentphoto($udom,$unam,$ext));
2621: }
2622: }
2623: }
2624: }
2625: } else {
2626: my ($result,$perm_reqd) =
1.707 albertel 2627: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2628: if ($result eq 'ok') {
2629: if (!($perm_reqd eq 'yes')) {
2630: return(&retrievestudentphoto($udom,$unam,$ext));
2631: }
2632: }
2633: }
2634: return '/adm/lonKaputt/lonlogo_broken.gif';
2635: }
2636:
2637: sub retrievestudentphoto {
2638: my ($udom,$unam,$ext,$type) = @_;
2639: my $home=&Apache::lonnet::homeserver($unam,$udom);
2640: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2641: if ($ret eq 'ok') {
2642: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2643: if ($type eq 'thumbnail') {
2644: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2645: }
2646: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2647: return $tokenurl;
2648: } else {
2649: if ($type eq 'thumbnail') {
2650: return '/adm/lonKaputt/genericstudent_tn.gif';
2651: } else {
2652: return '/adm/lonKaputt/lonlogo_broken.gif';
2653: }
1.617 albertel 2654: }
2655: }
2656:
1.263 www 2657: # -------------------------------------------------------------------- New chat
2658:
2659: sub chatsend {
1.724 raeburn 2660: my ($newentry,$anon,$group)=@_;
1.620 albertel 2661: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2662: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2663: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2664: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2665: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2666: &escape($newentry)).':'.$group,$chome);
1.292 www 2667: }
2668:
2669: # ------------------------------------------ Find current version of a resource
2670:
2671: sub getversion {
2672: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2673: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2674: return ¤tversion(&filelocation('',$fname));
2675: }
2676:
2677: sub currentversion {
2678: my $fname=shift;
2679: my $author=$fname;
2680: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2681: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2682: my $home=&homeserver($uname,$udom);
1.292 www 2683: if ($home eq 'no_host') {
2684: return -1;
2685: }
1.1112 www 2686: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2687: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2688: return -1;
2689: }
1.1112 www 2690: return $answer;
1.263 www 2691: }
2692:
1.1111 www 2693: #
2694: # Return special version number of resource if set by override, empty otherwise
2695: #
2696: sub usedversion {
2697: my $fname=shift;
2698: unless ($fname) { $fname=$env{'request.uri'}; }
2699: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2700: if ($urlversion) { return $urlversion; }
2701: return '';
2702: }
2703:
1.1 albertel 2704: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2705:
1.1 albertel 2706: sub subscribe {
2707: my $fname=shift;
1.761 raeburn 2708: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2709: $fname=~s/[\n\r]//g;
1.1 albertel 2710: my $author=$fname;
2711: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2712: my ($udom,$uname)=split(/\//,$author);
2713: my $home=homeserver($uname,$udom);
1.335 albertel 2714: if ($home eq 'no_host') {
2715: return 'not_found';
1.1 albertel 2716: }
2717: my $answer=reply("sub:$fname",$home);
1.64 www 2718: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2719: $answer.=' by '.$home;
2720: }
1.1 albertel 2721: return $answer;
2722: }
2723:
1.8 www 2724: # -------------------------------------------------------------- Replicate file
2725:
2726: sub repcopy {
2727: my $filename=shift;
1.23 www 2728: $filename=~s/\/+/\//g;
1.1142 raeburn 2729: my $londocroot = $perlvar{'lonDocRoot'};
2730: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2731: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2732: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2733: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2734: return &repcopy_userfile($filename);
2735: }
1.532 albertel 2736: $filename=~s/[\n\r]//g;
1.8 www 2737: my $transname="$filename.in.transfer";
1.828 www 2738: # FIXME: this should flock
1.607 raeburn 2739: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2740: my $remoteurl=subscribe($filename);
1.64 www 2741: if ($remoteurl =~ /^con_lost by/) {
2742: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2743: return 'unavailable';
1.8 www 2744: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2745: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2746: return 'not_found';
1.64 www 2747: } elsif ($remoteurl =~ /^rejected by/) {
2748: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2749: return 'forbidden';
1.20 www 2750: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2751: return 'ok';
1.8 www 2752: } else {
1.290 www 2753: my $author=$filename;
2754: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2755: my ($udom,$uname)=split(/\//,$author);
2756: my $home=homeserver($uname,$udom);
2757: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2758: my @parts=split(/\//,$filename);
2759: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2760: if ($path ne "$londocroot/res") {
1.8 www 2761: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2762: return 'bad_request';
1.8 www 2763: }
2764: my $count;
2765: for ($count=5;$count<$#parts;$count++) {
2766: $path.="/$parts[$count]";
2767: if ((-e $path)!=1) {
2768: mkdir($path,0777);
2769: }
2770: }
2771: my $ua=new LWP::UserAgent;
2772: my $request=new HTTP::Request('GET',"$remoteurl");
2773: my $response=$ua->request($request,$transname);
2774: if ($response->is_error()) {
2775: unlink($transname);
2776: my $message=$response->status_line;
1.672 albertel 2777: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2778: ." LWP get: $message: $filename</font>");
1.607 raeburn 2779: return 'unavailable';
1.8 www 2780: } else {
1.16 www 2781: if ($remoteurl!~/\.meta$/) {
2782: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2783: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2784: if ($mresponse->is_error()) {
2785: unlink($filename.'.meta');
2786: &logthis(
1.672 albertel 2787: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2788: }
2789: }
1.8 www 2790: rename($transname,$filename);
1.607 raeburn 2791: return 'ok';
1.8 www 2792: }
1.290 www 2793: }
1.8 www 2794: }
1.330 www 2795: }
2796:
2797: # ------------------------------------------------ Get server side include body
2798: sub ssi_body {
1.381 albertel 2799: my ($filelink,%form)=@_;
1.606 matthew 2800: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2801: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2802: }
1.953 www 2803: my $output='';
2804: my $response;
1.980 raeburn 2805: if ($filelink=~/^https?\:/) {
1.954 raeburn 2806: ($output,$response)=&externalssi($filelink);
1.953 www 2807: } else {
1.1004 droeschl 2808: $filelink .= $filelink=~/\?/ ? '&' : '?';
2809: $filelink .= 'inhibitmenu=yes';
1.953 www 2810: ($output,$response)=&ssi($filelink,%form);
2811: }
1.778 albertel 2812: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2813: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2814: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2815: if (wantarray) {
2816: return ($output, $response);
2817: } else {
2818: return $output;
2819: }
1.8 www 2820: }
2821:
1.15 www 2822: # --------------------------------------------------------- Server Side Include
2823:
1.782 albertel 2824: sub absolute_url {
2825: my ($host_name) = @_;
2826: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2827: if ($host_name eq '') {
2828: $host_name = $ENV{'SERVER_NAME'};
2829: }
2830: return $protocol.$host_name;
2831: }
2832:
1.942 foxr 2833: #
2834: # Server side include.
2835: # Parameters:
2836: # fn Possibly encrypted resource name/id.
2837: # form Hash that describes how the rendering should be done
2838: # and other things.
1.944 foxr 2839: # Returns:
1.950 raeburn 2840: # Scalar context: The content of the response.
2841: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2842: #
1.15 www 2843: sub ssi {
2844:
1.944 foxr 2845: my ($fn,%form)=@_;
1.1172.2.100 raeburn 2846: my ($request,$response);
1.711 albertel 2847:
2848: $form{'no_update_last_known'}=1;
1.895 albertel 2849: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2850: if (%form) {
1.782 albertel 2851: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2852: $request->content(join('&',map {
2853: my $name = escape($_);
2854: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2855: ? join("&$name=", map {escape($_) } @{$form{$_}})
2856: : &escape($form{$_}) );
2857: } keys(%form)));
1.23 www 2858: } else {
1.782 albertel 2859: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2860: }
2861:
1.15 www 2862: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 2863:
1.1172.2.101 raeburn 2864: if (($env{'request.course.id'}) &&
2865: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
2866: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
2867: ($form{'grade_symb'} ne '') &&
2868: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
2869: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 2870: if (LWP::UserAgent->VERSION >= 5.834) {
2871: my $ua=new LWP::UserAgent;
2872: $ua->local_address('127.0.0.1');
2873: $response = $ua->request($request);
2874: } else {
2875: {
2876: require LWP::Protocol::http;
2877: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
2878: my $ua=new LWP::UserAgent;
2879: $response = $ua->request($request);
2880: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
2881: }
2882: }
2883: } else {
2884: my $ua=new LWP::UserAgent;
2885: $response = $ua->request($request);
2886: }
1.944 foxr 2887: if (wantarray) {
1.1172.2.3 raeburn 2888: return ($response->content, $response);
1.944 foxr 2889: } else {
1.1172.2.3 raeburn 2890: return $response->content;
1.942 foxr 2891: }
1.324 www 2892: }
2893:
2894: sub externalssi {
2895: my ($url)=@_;
2896: my $ua=new LWP::UserAgent;
2897: my $request=new HTTP::Request('GET',$url);
2898: my $response=$ua->request($request);
1.954 raeburn 2899: if (wantarray) {
2900: return ($response->content, $response);
2901: } else {
2902: return $response->content;
2903: }
1.15 www 2904: }
1.254 www 2905:
1.1172.2.98 raeburn 2906: # If the local copy of a replicated resource is outdated, trigger a
2907: # connection from the homeserver to flush the delayed queue. If no update
2908: # happens, remove local copies of outdated resource (and corresponding
2909: # metadata file).
2910:
2911: sub remove_stale_resfile {
2912: my ($url) = @_;
2913: my $removed;
2914: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
2915: my $audom = $1;
2916: my $auname = $2;
2917: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
2918: my $homeserver = &homeserver($auname,$audom);
2919: unless (($homeserver eq 'no_host') ||
2920: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
2921: my $fname = &filelocation('',$url);
2922: if (-e $fname) {
2923: my $ua=new LWP::UserAgent;
2924: $ua->timeout(5);
2925: my $protocol = $protocol{$homeserver};
2926: $protocol = 'http' if ($protocol ne 'https');
2927: my $hostname = &hostname($homeserver);
2928: if ($hostname) {
2929: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
2930: my $request=new HTTP::Request('HEAD',$uri);
2931: my $response=$ua->request($request);
2932: if ($response->is_success()) {
2933: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
2934: my $locmodtime = (stat($fname))[9];
2935: if ($locmodtime < $remmodtime) {
2936: my $stale;
2937: my $answer = &reply('pong',$homeserver);
2938: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
2939: sleep(0.2);
2940: $locmodtime = (stat($fname))[9];
2941: if ($locmodtime < $remmodtime) {
2942: my $posstransfer = $fname.'.in.transfer';
2943: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
2944: $removed = 1;
2945: } else {
2946: $stale = 1;
2947: }
2948: } else {
2949: $removed = 1;
2950: }
2951: } else {
2952: $stale = 1;
2953: }
2954: if ($stale) {
2955: unlink($fname);
2956: if ($uri!~/\.meta$/) {
2957: unlink($fname.'.meta');
2958: }
2959: &reply("unsub:$fname",$homeserver);
2960: $removed = 1;
2961: }
2962: }
2963: }
2964: }
2965: }
2966: }
2967: }
2968: }
2969: return $removed;
2970: }
2971:
1.492 albertel 2972: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2973:
2974: sub allowuploaded {
2975: my ($srcurl,$url)=@_;
2976: $url=&clutter(&declutter($url));
2977: my $dir=$url;
2978: $dir=~s/\/[^\/]+$//;
2979: my %httpref=();
2980: my $httpurl=&hreflocation('',$url);
2981: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2982: &Apache::lonnet::appenv(\%httpref);
1.254 www 2983: }
1.477 raeburn 2984:
1.1172.2.13 raeburn 2985: #
2986: # Determine if the current user should be able to edit a particular resource,
2987: # when viewing in course context.
2988: # (a) When viewing resource used to determine if "Edit" item is included in
2989: # Functions.
2990: # (b) When displaying folder contents in course editor, used to determine if
2991: # "Edit" link will be displayed alongside resource.
2992: #
2993: # input: six args -- filename (decluttered), course number, course domain,
2994: # url, symb (if registered) and group (if this is a group
2995: # item -- e.g., bulletin board, group page etc.).
2996: # output: array of five scalars --
2997: # $cfile -- url for file editing if editable on current server
2998: # $home -- homeserver of resource (i.e., for author if published,
2999: # or course if uploaded.).
3000: # $switchserver -- 1 if server switch will be needed.
3001: # $forceedit -- 1 if icon/link should be to go to edit mode
3002: # $forceview -- 1 if icon/link should be to go to view mode
3003: #
3004:
3005: sub can_edit_resource {
3006: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3007: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3008: #
3009: # For aboutme pages user can only edit his/her own.
3010: #
3011: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3012: my ($sdom,$sname) = ($1,$2);
3013: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3014: $home = $env{'user.home'};
3015: $cfile = $resurl;
3016: if ($env{'form.forceedit'}) {
3017: $forceview = 1;
3018: } else {
3019: $forceedit = 1;
3020: }
3021: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3022: } else {
3023: return;
3024: }
3025: }
3026:
3027: if ($env{'request.course.id'}) {
3028: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3029: if ($group ne '') {
3030: # if this is a group homepage or group bulletin board, check group privs
3031: my $allowed = 0;
3032: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3033: if ((&allowed('mdg',$env{'request.course.id'}.
3034: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3035: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3036: $allowed = 1;
3037: }
3038: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3039: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3040: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3041: $allowed = 1;
3042: }
3043: }
3044: if ($allowed) {
3045: $home=&homeserver($cnum,$cdom);
3046: if ($env{'form.forceedit'}) {
3047: $forceview = 1;
3048: } else {
3049: $forceedit = 1;
3050: }
3051: $cfile = $resurl;
3052: } else {
3053: return;
3054: }
3055: } else {
1.1172.2.15 raeburn 3056: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3057: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3058: return;
3059: }
3060: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3061: #
3062: # No edit allowed where CC has switched to student role.
3063: #
3064: return;
3065: }
3066: }
3067: }
3068:
3069: if ($file ne '') {
3070: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3071: if (&is_course_upload($file,$cnum,$cdom)) {
3072: $uploaded = 1;
3073: $incourse = 1;
3074: if ($file =~/\.(htm|html|css|js|txt)$/) {
3075: $cfile = &hreflocation('',$file);
3076: if ($env{'form.forceedit'}) {
3077: $forceview = 1;
3078: } else {
3079: $forceedit = 1;
3080: }
3081: }
3082: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3083: $incourse = 1;
3084: if ($env{'form.forceedit'}) {
3085: $forceview = 1;
3086: } else {
3087: $forceedit = 1;
3088: }
3089: $cfile = $resurl;
3090: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3091: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3092: $incourse = 1;
3093: if ($env{'form.forceedit'}) {
3094: $forceview = 1;
3095: } else {
3096: $forceedit = 1;
3097: }
3098: $cfile = $resurl;
3099: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3100: $incourse = 1;
3101: $cfile = $resurl.'/smpedit';
3102: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3103: $incourse = 1;
3104: if ($env{'form.forceedit'}) {
3105: $forceview = 1;
3106: } else {
3107: $forceedit = 1;
3108: }
3109: $cfile = $resurl;
1.1172.2.15 raeburn 3110: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3111: $incourse = 1;
3112: if ($env{'form.forceedit'}) {
3113: $forceview = 1;
3114: } else {
3115: $forceedit = 1;
3116: }
3117: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3118: }
3119: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3120: my $template = '/res/lib/templates/simpleproblem.problem';
3121: if (&is_on_map($template)) {
3122: $incourse = 1;
3123: $forceview = 1;
3124: $cfile = $template;
3125: }
3126: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3127: $incourse = 1;
3128: if ($env{'form.forceedit'}) {
3129: $forceview = 1;
3130: } else {
3131: $forceedit = 1;
3132: }
3133: $cfile = $resurl;
3134: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3135: $incourse = 1;
3136: $forceview = 1;
3137: if ($symb) {
3138: my ($map,$id,$res)=&decode_symb($symb);
3139: $env{'request.symb'} = $symb;
3140: $cfile = &clutter($res);
3141: } else {
3142: $cfile = $env{'form.suppurl'};
3143: $cfile =~ s{^http://}{};
3144: $cfile = '/adm/wrapper/ext/'.$cfile;
3145: }
1.1172.2.31 raeburn 3146: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3147: if ($env{'form.forceedit'}) {
3148: $forceview = 1;
3149: } else {
3150: $forceedit = 1;
3151: }
3152: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3153: }
3154: }
3155: if ($uploaded || $incourse) {
3156: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3157: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3158: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3159: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3160: # Check that the user has permission to edit this resource
3161: my $setpriv = 1;
3162: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3163: if (defined($cfudom)) {
3164: $home=&homeserver($cfuname,$cfudom);
3165: $cfile=$file;
3166: }
3167: }
3168: if (($cfile ne '') && (!$incourse || $uploaded) &&
3169: (($home ne '') && ($home ne 'no_host'))) {
3170: my @ids=¤t_machine_ids();
3171: unless (grep(/^\Q$home\E$/,@ids)) {
3172: $switchserver=1;
3173: }
3174: }
3175: }
3176: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3177: }
3178:
3179: sub is_course_upload {
3180: my ($file,$cnum,$cdom) = @_;
3181: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3182: $uploadpath =~ s{^\/}{};
3183: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3184: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3185: return 1;
3186: }
3187: return;
3188: }
3189:
3190: sub in_course {
3191: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3192: if ($hideprivileged) {
3193: my $skipuser;
1.1172.2.23 raeburn 3194: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3195: my @possdoms = ($cdom);
3196: if ($coursehash{'checkforpriv'}) {
3197: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3198: }
3199: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3200: $skipuser = 1;
3201: if ($coursehash{'nothideprivileged'}) {
3202: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3203: my $user;
3204: if ($item =~ /:/) {
3205: $user = $item;
3206: } else {
3207: $user = join(':',split(/[\@]/,$item));
3208: }
3209: if ($user eq $uname.':'.$udom) {
3210: undef($skipuser);
3211: last;
3212: }
3213: }
3214: }
3215: if ($skipuser) {
3216: return 0;
3217: }
3218: }
3219: }
3220: $type ||= 'any';
3221: if (!defined($cdom) || !defined($cnum)) {
3222: my $cid = $env{'request.course.id'};
3223: $cdom = $env{'course.'.$cid.'.domain'};
3224: $cnum = $env{'course.'.$cid.'.num'};
3225: }
3226: my $typesref;
3227: if (($type eq 'any') || ($type eq 'all')) {
3228: $typesref = ['active','previous','future'];
3229: } elsif ($type eq 'previous' || $type eq 'future') {
3230: $typesref = [$type];
3231: }
3232: my %roles = &get_my_roles($uname,$udom,'userroles',
3233: $typesref,undef,[$cdom]);
3234: my ($tmp) = keys(%roles);
3235: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3236: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3237: if (@course_roles > 0) {
3238: return 1;
3239: }
3240: return 0;
3241: }
3242:
1.478 albertel 3243: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3244: # input: action, courseID, current domain, intended
1.637 raeburn 3245: # path to file, source of file, instruction to parse file for objects,
3246: # ref to hash for embedded objects,
3247: # ref to hash for codebase of java objects.
1.1095 raeburn 3248: # reference to scalar to accommodate mime type determined
3249: # from File::MMagic if $parser = parse.
1.637 raeburn 3250: #
1.485 raeburn 3251: # output: url to file (if action was uploaddoc),
3252: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3253: #
1.478 albertel 3254: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3255: # course.
1.477 raeburn 3256: #
1.478 albertel 3257: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3258: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3259: # course's home server.
1.477 raeburn 3260: #
1.478 albertel 3261: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3262: # be copied from $source (current location) to
3263: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3264: # and will then be copied to
3265: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3266: # course's home server.
1.485 raeburn 3267: #
1.481 raeburn 3268: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3269: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3270: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3271: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3272: # in course's home server.
1.637 raeburn 3273: #
1.477 raeburn 3274:
3275: sub process_coursefile {
1.1095 raeburn 3276: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3277: $mimetype)=@_;
1.477 raeburn 3278: my $fetchresult;
1.638 albertel 3279: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3280: if ($action eq 'propagate') {
1.638 albertel 3281: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3282: $home);
1.481 raeburn 3283: } else {
1.477 raeburn 3284: my $fpath = '';
3285: my $fname = $file;
1.478 albertel 3286: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3287: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3288: my $filepath = &build_filepath($fpath);
1.481 raeburn 3289: if ($action eq 'copy') {
3290: if ($source eq '') {
3291: $fetchresult = 'no source file';
3292: return $fetchresult;
3293: } else {
3294: my $destination = $filepath.'/'.$fname;
3295: rename($source,$destination);
3296: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3297: $home);
1.481 raeburn 3298: }
3299: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3300: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3301: print $fh $env{'form.'.$source};
1.481 raeburn 3302: close($fh);
1.637 raeburn 3303: if ($parser eq 'parse') {
1.1024 raeburn 3304: my $mm = new File::MMagic;
1.1095 raeburn 3305: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3306: if ($type eq 'text/html') {
1.1024 raeburn 3307: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3308: unless ($parse_result eq 'ok') {
3309: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3310: }
1.637 raeburn 3311: }
1.1095 raeburn 3312: if (ref($mimetype)) {
3313: $$mimetype = $type;
3314: }
1.637 raeburn 3315: }
1.477 raeburn 3316: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3317: $home);
1.481 raeburn 3318: if ($fetchresult eq 'ok') {
3319: return '/uploaded/'.$fpath.'/'.$fname;
3320: } else {
3321: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3322: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3323: return '/adm/notfound.html';
3324: }
1.477 raeburn 3325: }
3326: }
1.485 raeburn 3327: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3328: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3329: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3330: }
3331: return $fetchresult;
3332: }
3333:
1.637 raeburn 3334: sub build_filepath {
3335: my ($fpath) = @_;
3336: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3337: unless ($fpath eq '') {
3338: my @parts=split('/',$fpath);
3339: foreach my $part (@parts) {
3340: $filepath.= '/'.$part;
3341: if ((-e $filepath)!=1) {
3342: mkdir($filepath,0777);
3343: }
3344: }
3345: }
3346: return $filepath;
3347: }
3348:
3349: sub store_edited_file {
1.638 albertel 3350: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3351: my $file = $primary_url;
3352: $file =~ s#^/uploaded/$docudom/$docuname/##;
3353: my $fpath = '';
3354: my $fname = $file;
3355: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3356: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3357: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3358: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3359: print $fh $content;
3360: close($fh);
1.638 albertel 3361: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3362: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3363: $home);
1.637 raeburn 3364: if ($$fetchresult eq 'ok') {
3365: return '/uploaded/'.$fpath.'/'.$fname;
3366: } else {
1.638 albertel 3367: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3368: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3369: return '/adm/notfound.html';
3370: }
3371: }
3372:
1.531 albertel 3373: sub clean_filename {
1.831 albertel 3374: my ($fname,$args)=@_;
1.315 www 3375: # Replace Windows backslashes by forward slashes
1.257 www 3376: $fname=~s/\\/\//g;
1.831 albertel 3377: if (!$args->{'keep_path'}) {
3378: # Get rid of everything but the actual filename
3379: $fname=~s/^.*\/([^\/]+)$/$1/;
3380: }
1.315 www 3381: # Replace spaces by underscores
3382: $fname=~s/\s+/\_/g;
3383: # Replace all other weird characters by nothing
1.831 albertel 3384: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3385: # Replace all .\d. sequences with _\d. so they no longer look like version
3386: # numbers
3387: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3388: return $fname;
3389: }
1.1051 raeburn 3390: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3391: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3392: # image with the same aspect ratio as the original, but with dimensions which do
3393: # not exceed $resizewidth and $resizeheight.
3394:
1.984 neumanie 3395: sub resizeImage {
1.1051 raeburn 3396: my ($img_path,$resizewidth,$resizeheight) = @_;
3397: my $ima = Image::Magick->new;
3398: my $resized;
3399: if (-e $img_path) {
3400: $ima->Read($img_path);
3401: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3402: my $width = $ima->Get('width');
3403: my $height = $ima->Get('height');
3404: if ($width > $resizewidth) {
3405: my $factor = $width/$resizewidth;
3406: my $newheight = $height/$factor;
3407: $ima->Scale(width=>$resizewidth,height=>$newheight);
3408: $resized = 1;
3409: }
3410: }
3411: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3412: my $width = $ima->Get('width');
3413: my $height = $ima->Get('height');
3414: if ($height > $resizeheight) {
3415: my $factor = $height/$resizeheight;
3416: my $newwidth = $width/$factor;
3417: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3418: $resized = 1;
3419: }
3420: }
3421: if ($resized) {
3422: $ima->Write($img_path);
3423: }
3424: }
3425: return;
1.977 amueller 3426: }
3427:
1.608 albertel 3428: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3429: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3430: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3431: # $context - possible values: coursedoc, existingfile, overwrite,
3432: # canceloverwrite, or ''.
3433: # if 'coursedoc': upload to the current course
3434: # if 'existingfile': write file to tmp/overwrites directory
3435: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3436: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3437: # $subdir - directory in userfile to store the file into
1.858 raeburn 3438: # $parser - instruction to parse file for objects ($parser = parse)
3439: # $allfiles - reference to hash for embedded objects
3440: # $codebase - reference to hash for codebase of java objects
3441: # $desuname - username for permanent storage of uploaded file
3442: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3443: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3444: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3445: # $resizewidth - width (pixels) to which to resize uploaded image
3446: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3447: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3448: # from File::MMagic.
1.858 raeburn 3449: #
1.686 albertel 3450: # output: url of file in userspace, or error: <message>
3451: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3452:
1.531 albertel 3453: sub userfileupload {
1.1090 raeburn 3454: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3455: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3456: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3457: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3458: $fname=&clean_filename($fname);
1.1090 raeburn 3459: # See if there is anything left
1.257 www 3460: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3461: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3462: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3463: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3464: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3465: my $now = time;
1.1090 raeburn 3466: my $filepath;
1.1095 raeburn 3467: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3468: $filepath = 'tmp/helprequests/'.$now;
3469: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3470: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3471: '_'.$env{'user.domain'}.'/pending';
3472: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3473: my ($docuname,$docudom);
1.1172.2.96 raeburn 3474: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3475: $docudom = $destudom;
3476: } else {
3477: $docudom = $env{'user.domain'};
3478: }
1.1172.2.96 raeburn 3479: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3480: $docuname = $destuname;
3481: } else {
3482: $docuname = $env{'user.name'};
3483: }
3484: if (exists($env{'form.group'})) {
3485: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3486: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3487: }
3488: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3489: if ($context eq 'canceloverwrite') {
3490: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3491: if (-e $tempfile) {
3492: my @info = stat($tempfile);
3493: if ($info[9] eq $env{'form.timestamp'}) {
3494: unlink($tempfile);
3495: }
3496: }
3497: return;
1.523 raeburn 3498: }
3499: }
1.1090 raeburn 3500: # Create the directory if not present
1.741 raeburn 3501: my @parts=split(/\//,$filepath);
3502: my $fullpath = $perlvar{'lonDaemons'};
3503: for (my $i=0;$i<@parts;$i++) {
3504: $fullpath .= '/'.$parts[$i];
3505: if ((-e $fullpath)!=1) {
3506: mkdir($fullpath,0777);
3507: }
3508: }
1.1172.2.96 raeburn 3509: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3510: print $fh $env{'form.'.$formname};
3511: close($fh);
1.1090 raeburn 3512: if ($context eq 'existingfile') {
3513: my @info = stat($fullpath.'/'.$fname);
3514: return ($fullpath.'/'.$fname,$info[9]);
3515: } else {
3516: return $fullpath.'/'.$fname;
3517: }
1.523 raeburn 3518: }
1.995 raeburn 3519: if ($subdir eq 'scantron') {
3520: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3521: } else {
1.995 raeburn 3522: $fname="$subdir/$fname";
3523: }
1.1090 raeburn 3524: if ($context eq 'coursedoc') {
1.638 albertel 3525: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3526: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3527: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3528: return &finishuserfileupload($docuname,$docudom,
3529: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3530: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3531: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3532: } else {
1.1172.2.21 raeburn 3533: if ($env{'form.folder'}) {
3534: $fname=$env{'form.folder'}.'/'.$fname;
3535: }
1.638 albertel 3536: return &process_coursefile('uploaddoc',$docuname,$docudom,
3537: $fname,$formname,$parser,
1.1095 raeburn 3538: $allfiles,$codebase,$mimetype);
1.481 raeburn 3539: }
1.719 banghart 3540: } elsif (defined($destuname)) {
3541: my $docuname=$destuname;
3542: my $docudom=$destudom;
1.860 raeburn 3543: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3544: $parser,$allfiles,$codebase,
1.1051 raeburn 3545: $thumbwidth,$thumbheight,
1.1095 raeburn 3546: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3547: } else {
1.638 albertel 3548: my $docuname=$env{'user.name'};
3549: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3550: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3551: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3552: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3553: }
1.860 raeburn 3554: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3555: $parser,$allfiles,$codebase,
1.1051 raeburn 3556: $thumbwidth,$thumbheight,
1.1095 raeburn 3557: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3558: }
1.271 www 3559: }
3560:
3561: sub finishuserfileupload {
1.860 raeburn 3562: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3563: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3564: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3565: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3566:
1.860 raeburn 3567: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3568: $file=$fname;
3569: if ($fname=~m|/|) {
3570: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3571: $path.=$fnamepath.'/';
3572: }
1.259 www 3573: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3574: my $count;
3575: for ($count=4;$count<=$#parts;$count++) {
3576: $filepath.="/$parts[$count]";
3577: if ((-e $filepath)!=1) {
3578: mkdir($filepath,0777);
3579: }
3580: }
1.984 neumanie 3581:
1.258 www 3582: # Save the file
3583: {
1.1172.2.96 raeburn 3584: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3585: &logthis('Failed to create '.$filepath.'/'.$file);
3586: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3587: return '/adm/notfound.html';
3588: }
1.1090 raeburn 3589: if ($context eq 'overwrite') {
1.1117 foxr 3590: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3591: my $target = $filepath.'/'.$file;
3592: if (-e $source) {
3593: my @info = stat($source);
3594: if ($info[9] eq $env{'form.timestamp'}) {
3595: unless (&File::Copy::move($source,$target)) {
3596: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3597: return "Moving from $source failed";
3598: }
3599: } else {
3600: return "Temporary file: $source had unexpected date/time for last modification";
3601: }
3602: } else {
3603: return "Temporary file: $source missing";
3604: }
3605: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3606: &logthis('Failed to write to '.$filepath.'/'.$file);
3607: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3608: return '/adm/notfound.html';
3609: }
1.570 albertel 3610: close(FH);
1.1051 raeburn 3611: if ($resizewidth && $resizeheight) {
3612: my $mm = new File::MMagic;
3613: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3614: if ($mime_type =~ m{^image/}) {
3615: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3616: }
1.977 amueller 3617: }
1.258 www 3618: }
1.1152 raeburn 3619: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3620: if (ref($mimetype)) {
3621: if ($$mimetype eq '') {
3622: my $mm = new File::MMagic;
3623: my $type = $mm->checktype_filename($filepath.'/'.$file);
3624: $$mimetype = $type;
3625: }
3626: }
3627: }
1.637 raeburn 3628: if ($parser eq 'parse') {
1.1152 raeburn 3629: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3630: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3631: $allfiles,$codebase);
3632: unless ($parse_result eq 'ok') {
3633: &logthis('Failed to parse '.$filepath.$file.
3634: ' for embedded media: '.$parse_result);
3635: }
1.637 raeburn 3636: }
3637: }
1.860 raeburn 3638: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3639: my $input = $filepath.'/'.$file;
3640: my $output = $filepath.'/'.'tn-'.$file;
3641: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 3642: my @args = ('convert','-sample',$thumbsize,$input,$output);
3643: system({$args[0]} @args);
1.860 raeburn 3644: if (-e $filepath.'/'.'tn-'.$file) {
3645: $fetchthumb = 1;
3646: }
3647: }
1.858 raeburn 3648:
1.259 www 3649: # Notify homeserver to grep it
3650: #
1.984 neumanie 3651: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3652: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3653: if ($fetchresult eq 'ok') {
1.860 raeburn 3654: if ($fetchthumb) {
3655: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3656: if ($thumbresult ne 'ok') {
3657: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3658: $docuhome.': '.$thumbresult);
3659: }
3660: }
1.259 www 3661: #
1.258 www 3662: # Return the URL to it
1.494 albertel 3663: return '/uploaded/'.$path.$file;
1.263 www 3664: } else {
1.494 albertel 3665: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3666: ': '.$fetchresult);
1.263 www 3667: return '/adm/notfound.html';
1.858 raeburn 3668: }
1.493 albertel 3669: }
3670:
1.637 raeburn 3671: sub extract_embedded_items {
1.961 raeburn 3672: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3673: my @state = ();
1.1164 raeburn 3674: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3675: my %javafiles = (
3676: codebase => '',
3677: code => '',
3678: archive => ''
3679: );
3680: my %mediafiles = (
3681: src => '',
3682: movie => '',
3683: );
1.648 raeburn 3684: my $p;
3685: if ($content) {
3686: $p = HTML::LCParser->new($content);
3687: } else {
1.961 raeburn 3688: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3689: }
1.641 albertel 3690: while (my $t=$p->get_token()) {
1.640 albertel 3691: if ($t->[0] eq 'S') {
3692: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3693: push(@state, $tagname);
1.648 raeburn 3694: if (lc($tagname) eq 'allow') {
3695: &add_filetype($allfiles,$attr->{'src'},'src');
3696: }
1.640 albertel 3697: if (lc($tagname) eq 'img') {
3698: &add_filetype($allfiles,$attr->{'src'},'src');
3699: }
1.886 albertel 3700: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3701: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3702: &add_filetype($allfiles,$attr->{'href'},'href');
3703: }
1.886 albertel 3704: }
1.645 raeburn 3705: if (lc($tagname) eq 'script') {
1.1164 raeburn 3706: my $src;
1.645 raeburn 3707: if ($attr->{'archive'} =~ /\.jar$/i) {
3708: &add_filetype($allfiles,$attr->{'archive'},'archive');
3709: } else {
1.1164 raeburn 3710: if ($attr->{'src'} ne '') {
3711: $src = $attr->{'src'};
3712: &add_filetype($allfiles,$src,'src');
3713: }
3714: }
3715: my $text = $p->get_trimmed_text();
3716: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3717: my @swfargs = split(/,/,$1);
3718: foreach my $item (@swfargs) {
3719: $item =~ s/["']//g;
3720: $item =~ s/^\s+//;
3721: $item =~ s/\s+$//;
3722: }
3723: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3724: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3725: push(@{$related{$swfargs[0]}},$swfargs[2]);
3726: } else {
3727: $related{$swfargs[0]} = [$swfargs[2]];
3728: }
3729: }
1.645 raeburn 3730: }
3731: }
3732: if (lc($tagname) eq 'link') {
3733: if (lc($attr->{'rel'}) eq 'stylesheet') {
3734: &add_filetype($allfiles,$attr->{'href'},'href');
3735: }
3736: }
1.640 albertel 3737: if (lc($tagname) eq 'object' ||
3738: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3739: foreach my $item (keys(%javafiles)) {
3740: $javafiles{$item} = '';
3741: }
1.1164 raeburn 3742: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3743: $lastids{lc($tagname)} = $attr->{'id'};
3744: }
1.640 albertel 3745: }
3746: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3747: my $name = lc($attr->{'name'});
3748: foreach my $item (keys(%javafiles)) {
3749: if ($name eq $item) {
3750: $javafiles{$item} = $attr->{'value'};
3751: last;
3752: }
3753: }
1.1164 raeburn 3754: my $pathfrom;
1.640 albertel 3755: foreach my $item (keys(%mediafiles)) {
3756: if ($name eq $item) {
1.1164 raeburn 3757: $pathfrom = $attr->{'value'};
3758: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3759: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3760: last;
3761: }
3762: }
1.1164 raeburn 3763: if ($name eq 'flashvars') {
3764: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3765: }
3766: if ($pathfrom ne '') {
3767: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3768: $pathfrom);
3769: }
1.640 albertel 3770: }
3771: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3772: foreach my $item (keys(%javafiles)) {
3773: if ($attr->{$item}) {
3774: $javafiles{$item} = $attr->{$item};
3775: last;
3776: }
3777: }
3778: foreach my $item (keys(%mediafiles)) {
3779: if ($attr->{$item}) {
3780: &add_filetype($allfiles,$attr->{$item},$item);
3781: last;
3782: }
3783: }
1.1164 raeburn 3784: if (lc($tagname) eq 'embed') {
3785: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3786: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3787: $attr->{'src'});
3788: }
3789: }
1.640 albertel 3790: }
1.1172.2.35 raeburn 3791: if (lc($tagname) eq 'iframe') {
3792: my $src = $attr->{'src'} ;
3793: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3794: &add_filetype($allfiles,$src,'src');
3795: } elsif ($src =~ m{^/}) {
3796: if ($env{'request.course.id'}) {
3797: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3798: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3799: my $url = &hreflocation('',$fullpath);
3800: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3801: my $relpath = $1;
3802: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3803: &add_filetype($allfiles,$1,'src');
3804: }
3805: }
3806: }
3807: }
3808: }
1.1164 raeburn 3809: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3810: pop(@state);
1.1164 raeburn 3811: }
1.640 albertel 3812: } elsif ($t->[0] eq 'E') {
3813: my ($tagname) = ($t->[1]);
3814: if ($javafiles{'codebase'} ne '') {
3815: $javafiles{'codebase'} .= '/';
3816: }
3817: if (lc($tagname) eq 'applet' ||
3818: lc($tagname) eq 'object' ||
3819: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3820: ) {
3821: foreach my $item (keys(%javafiles)) {
3822: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3823: my $file=$javafiles{'codebase'}.$javafiles{$item};
3824: &add_filetype($allfiles,$file,$item);
3825: }
3826: }
3827: }
3828: pop @state;
3829: }
3830: }
1.1164 raeburn 3831: foreach my $id (sort(keys(%flashvars))) {
3832: if ($shockwave{$id} ne '') {
3833: my @pairs = split(/\&/,$flashvars{$id});
3834: foreach my $pair (@pairs) {
3835: my ($key,$value) = split(/\=/,$pair);
3836: if ($key eq 'thumb') {
3837: &add_filetype($allfiles,$value,$key);
3838: } elsif ($key eq 'content') {
3839: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3840: my ($ext) = ($value =~ /\.([^.]+)$/);
3841: if ($ext ne '') {
3842: &add_filetype($allfiles,$path.$value,$ext);
3843: }
3844: }
3845: }
3846: }
3847: }
1.637 raeburn 3848: return 'ok';
3849: }
3850:
1.639 albertel 3851: sub add_filetype {
3852: my ($allfiles,$file,$type)=@_;
3853: if (exists($allfiles->{$file})) {
3854: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3855: push(@{$allfiles->{$file}}, &escape($type));
3856: }
3857: } else {
3858: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3859: }
3860: }
3861:
1.1164 raeburn 3862: sub embedded_dependency {
3863: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3864: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3865: if (($identifier ne '') &&
3866: (ref($related->{$identifier}) eq 'ARRAY') &&
3867: ($pathfrom ne '')) {
3868: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3869: foreach my $dep (@{$related->{$identifier}}) {
3870: &add_filetype($allfiles,$path.$dep,'object');
3871: }
3872: }
3873: }
3874: return;
3875: }
3876:
1.493 albertel 3877: sub removeuploadedurl {
1.984 neumanie 3878: my ($url)=@_;
3879: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3880: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3881: }
3882:
3883: sub removeuserfile {
3884: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3885: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3886: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3887: if ($result eq 'ok') {
1.798 raeburn 3888: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3889: my $metafile = $fname.'.meta';
3890: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3891: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3892: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3893: my $sqlresult =
1.823 albertel 3894: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3895: 'portfolio_metadata',$group,
3896: 'delete');
1.798 raeburn 3897: }
3898: }
3899: return $result;
1.257 www 3900: }
1.15 www 3901:
1.530 albertel 3902: sub mkdiruserfile {
3903: my ($docuname,$docudom,$dir)=@_;
3904: my $home=&homeserver($docuname,$docudom);
3905: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3906: }
3907:
1.531 albertel 3908: sub renameuserfile {
3909: my ($docuname,$docudom,$old,$new)=@_;
3910: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3911: my $result = &reply("renameuserfile:$docudom:$docuname:".
3912: &escape("$old").':'.&escape("$new"),$home);
3913: if ($result eq 'ok') {
3914: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3915: my $oldmeta = $old.'.meta';
3916: my $newmeta = $new.'.meta';
3917: my $metaresult =
3918: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3919: my $url = "/uploaded/$docudom/$docuname/$old";
3920: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3921: my $sqlresult =
1.823 albertel 3922: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3923: 'portfolio_metadata',$group,
3924: 'delete');
1.798 raeburn 3925: }
3926: }
3927: return $result;
1.531 albertel 3928: }
3929:
1.14 www 3930: # ------------------------------------------------------------------------- Log
3931:
3932: sub log {
3933: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3934: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3935: }
3936:
3937: # ------------------------------------------------------------------ Course Log
1.352 www 3938: #
3939: # This routine flushes several buffers of non-mission-critical nature
3940: #
1.157 www 3941:
3942: sub flushcourselogs {
1.352 www 3943: &logthis('Flushing log buffers');
3944: #
3945: # course logs
3946: # This is a log of all transactions in a course, which can be used
3947: # for data mining purposes
3948: #
3949: # It also collects the courseid database, which lists last transaction
3950: # times and course titles for all courseids
3951: #
3952: my %courseidbuffer=();
1.921 raeburn 3953: foreach my $crsid (keys(%courselogs)) {
1.352 www 3954: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3955: &escape($courselogs{$crsid}),
3956: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3957: delete $courselogs{$crsid};
3958: } else {
3959: &logthis('Failed to flush log buffer for '.$crsid);
3960: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3961: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3962: " exceeded maximum size, deleting.</font>");
3963: delete $courselogs{$crsid};
3964: }
1.352 www 3965: }
1.920 raeburn 3966: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3967: 'description' => $coursedescrbuf{$crsid},
3968: 'inst_code' => $courseinstcodebuf{$crsid},
3969: 'type' => $coursetypebuf{$crsid},
3970: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3971: };
1.191 harris41 3972: }
1.352 www 3973: #
3974: # Write course id database (reverse lookup) to homeserver of courses
3975: # Is used in pickcourse
3976: #
1.840 albertel 3977: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3978: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3979: $courseidbuffer{$crs_home},
3980: $crs_home,'timeonly');
1.352 www 3981: }
3982: #
3983: # File accesses
3984: # Writes to the dynamic metadata of resources to get hit counts, etc.
3985: #
1.449 matthew 3986: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3987: if ($entry =~ /___count$/) {
3988: my ($dom,$name);
1.807 albertel 3989: ($dom,$name,undef)=
1.811 albertel 3990: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3991: if (! defined($dom) || $dom eq '' ||
3992: ! defined($name) || $name eq '') {
1.620 albertel 3993: my $cid = $env{'request.course.id'};
3994: $dom = $env{'request.'.$cid.'.domain'};
3995: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3996: }
1.450 matthew 3997: my $value = $accesshash{$entry};
3998: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3999: my %temphash=($url => $value);
1.449 matthew 4000: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4001: if ($result eq 'ok') {
4002: delete $accesshash{$entry};
4003: }
4004: } else {
1.811 albertel 4005: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4006: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4007: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4008: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4009: delete $accesshash{$entry};
4010: }
1.185 www 4011: }
1.191 harris41 4012: }
1.352 www 4013: #
4014: # Roles
4015: # Reverse lookup of user roles for course faculty/staff and co-authorship
4016: #
1.800 albertel 4017: foreach my $entry (keys(%userrolehash)) {
1.351 www 4018: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4019: split(/\:/,$entry);
4020: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4021: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4022: $rudom,$runame) eq 'ok') {
4023: delete $userrolehash{$entry};
4024: }
4025: }
1.662 raeburn 4026: #
1.1172.2.90 raeburn 4027: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4028: #
4029: my %domrolebuffer = ();
1.1000 raeburn 4030: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4031: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4032: if ($domrolebuffer{$rudom}) {
4033: $domrolebuffer{$rudom}.='&'.&escape($entry).
4034: '='.&escape($domainrolehash{$entry});
4035: } else {
4036: $domrolebuffer{$rudom}.=&escape($entry).
4037: '='.&escape($domainrolehash{$entry});
4038: }
4039: delete $domainrolehash{$entry};
4040: }
4041: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4042: my %servers;
4043: if (defined(&domain($dom,'primary'))) {
4044: my $primary=&domain($dom,'primary');
4045: my $hostname=&hostname($primary);
4046: $servers{$primary} = $hostname;
4047: } else {
4048: %servers = &get_servers($dom,'library');
4049: }
1.841 albertel 4050: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4051: if (&reply('domroleput:'.$dom.':'.
4052: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4053: last;
4054: } else {
1.841 albertel 4055: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4056: }
1.662 raeburn 4057: }
4058: }
1.186 www 4059: $dumpcount++;
1.157 www 4060: }
4061:
4062: sub courselog {
4063: my $what=shift;
1.158 www 4064: $what=time.':'.$what;
1.620 albertel 4065: unless ($env{'request.course.id'}) { return ''; }
4066: $coursedombuf{$env{'request.course.id'}}=
4067: $env{'course.'.$env{'request.course.id'}.'.domain'};
4068: $coursenumbuf{$env{'request.course.id'}}=
4069: $env{'course.'.$env{'request.course.id'}.'.num'};
4070: $coursehombuf{$env{'request.course.id'}}=
4071: $env{'course.'.$env{'request.course.id'}.'.home'};
4072: $coursedescrbuf{$env{'request.course.id'}}=
4073: $env{'course.'.$env{'request.course.id'}.'.description'};
4074: $courseinstcodebuf{$env{'request.course.id'}}=
4075: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4076: $courseownerbuf{$env{'request.course.id'}}=
4077: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4078: $coursetypebuf{$env{'request.course.id'}}=
4079: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4080: if (defined $courselogs{$env{'request.course.id'}}) {
4081: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4082: } else {
1.620 albertel 4083: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4084: }
1.620 albertel 4085: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4086: &flushcourselogs();
4087: }
1.158 www 4088: }
4089:
4090: sub courseacclog {
4091: my $fnsymb=shift;
1.620 albertel 4092: unless ($env{'request.course.id'}) { return ''; }
4093: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4094: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4095: $what.=':POST';
1.583 matthew 4096: # FIXME: Probably ought to escape things....
1.800 albertel 4097: foreach my $key (keys(%env)) {
4098: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4099: my $formitem = $1;
4100: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4101: $what.=':'.$formitem.'='.$env{$key};
4102: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4103: $what.=':'.$formitem.'='.$env{$key};
4104: }
1.158 www 4105: }
1.191 harris41 4106: }
1.583 matthew 4107: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4108: # FIXME: We should not be depending on a form parameter that someone
4109: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4110: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4111: $what.= ':POST';
4112: # FIXME: Probably ought to escape things....
4113: foreach my $element ('courseexp','crsfulltext','crsrelated',
4114: 'crsdiscuss') {
1.620 albertel 4115: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4116: }
4117: }
1.158 www 4118: }
4119: &courselog($what);
1.149 www 4120: }
4121:
1.185 www 4122: sub countacc {
4123: my $url=&declutter(shift);
1.458 matthew 4124: return if (! defined($url) || $url eq '');
1.620 albertel 4125: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4126: #
4127: # Mark that this url was used in this course
4128: #
1.620 albertel 4129: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4130: #
4131: # Increase the access count for this resource in this child process
4132: #
1.281 www 4133: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4134: $accesshash{$key}++;
1.185 www 4135: }
1.349 www 4136:
1.361 www 4137: sub linklog {
4138: my ($from,$to)=@_;
4139: $from=&declutter($from);
4140: $to=&declutter($to);
4141: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4142: $accesshash{$to.'___'.$from.'___goto'}=1;
4143: }
1.1160 www 4144:
4145: sub statslog {
4146: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4147: if ($users<2) { return; }
4148: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4149: 'course' => $env{'request.course.id'},
4150: 'sections' => '"all"',
4151: 'num_students' => $users,
4152: 'part' => $part,
4153: 'symb' => $symb,
4154: 'mean_tries' => $av_attempts,
4155: 'deg_of_diff' => $degdiff});
4156: foreach my $key (keys(%dynstore)) {
4157: $accesshash{$key}=$dynstore{$key};
4158: }
4159: }
1.361 www 4160:
1.349 www 4161: sub userrolelog {
4162: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4163: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4164: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4165: $userrolehash
4166: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4167: =$tend.':'.$tstart;
1.662 raeburn 4168: }
1.1169 droeschl 4169: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4170: $userrolehash
4171: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4172: =$tend.':'.$tstart;
4173: }
1.1172.2.90 raeburn 4174: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4175: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4176: $domainrolehash
4177: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4178: = $tend.':'.$tstart;
4179: }
1.351 www 4180: }
4181:
1.957 raeburn 4182: sub courserolelog {
4183: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4184: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4185: my $cdom = $1;
4186: my $cnum = $2;
4187: my $sec = $3;
4188: my $namespace = 'rolelog';
4189: my %storehash = (
4190: role => $trole,
4191: start => $tstart,
4192: end => $tend,
4193: selfenroll => $selfenroll,
4194: context => $context,
4195: );
4196: if ($trole eq 'gr') {
4197: $namespace = 'groupslog';
4198: $storehash{'group'} = $sec;
4199: } else {
4200: $storehash{'section'} = $sec;
4201: }
4202: &write_log('course',$namespace,\%storehash,$delflag,$username,
4203: $domain,$cnum,$cdom);
4204: if (($trole ne 'st') || ($sec ne '')) {
4205: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4206: }
4207: }
4208: return;
4209: }
4210:
1.1172.2.9 raeburn 4211: sub domainrolelog {
4212: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4213: if ($area =~ m{^/($match_domain)/$}) {
4214: my $cdom = $1;
4215: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4216: my $namespace = 'rolelog';
4217: my %storehash = (
4218: role => $trole,
4219: start => $tstart,
4220: end => $tend,
4221: context => $context,
4222: );
4223: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4224: $domain,$domconfiguser,$cdom);
4225: }
4226: return;
4227:
4228: }
4229:
4230: sub coauthorrolelog {
4231: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4232: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4233: my $audom = $1;
4234: my $auname = $2;
4235: my $namespace = 'rolelog';
4236: my %storehash = (
4237: role => $trole,
4238: start => $tstart,
4239: end => $tend,
4240: context => $context,
4241: );
4242: &write_log('author',$namespace,\%storehash,$delflag,$username,
4243: $domain,$auname,$audom);
4244: }
4245: return;
4246: }
4247:
1.351 www 4248: sub get_course_adv_roles {
1.948 raeburn 4249: my ($cid,$codes) = @_;
1.620 albertel 4250: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4251: my %coursehash=&coursedescription($cid);
1.988 raeburn 4252: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4253: my %nothide=();
1.800 albertel 4254: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4255: if ($user !~ /:/) {
4256: $nothide{join(':',split(/[\@]/,$user))}=1;
4257: } else {
4258: $nothide{$user}=1;
4259: }
1.470 www 4260: }
1.1172.2.23 raeburn 4261: my @possdoms = ($coursehash{'domain'});
4262: if ($coursehash{'checkforpriv'}) {
4263: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4264: }
1.351 www 4265: my %returnhash=();
4266: my %dumphash=
4267: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4268: my $now=time;
1.997 raeburn 4269: my %privileged;
1.1000 raeburn 4270: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4271: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4272: if (($tstart) && ($tstart<0)) { next; }
4273: if (($tend) && ($tend<$now)) { next; }
4274: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4275: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4276: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4277: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4278: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4279: if ($role eq 'cr') { next; }
1.948 raeburn 4280: if ($codes) {
4281: if ($section) { $role .= ':'.$section; }
4282: if ($returnhash{$role}) {
4283: $returnhash{$role}.=','.$username.':'.$domain;
4284: } else {
4285: $returnhash{$role}=$username.':'.$domain;
4286: }
1.351 www 4287: } else {
1.988 raeburn 4288: my $key=&plaintext($role,$crstype);
1.973 bisitz 4289: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4290: if ($returnhash{$key}) {
4291: $returnhash{$key}.=','.$username.':'.$domain;
4292: } else {
4293: $returnhash{$key}=$username.':'.$domain;
4294: }
1.351 www 4295: }
1.948 raeburn 4296: }
1.400 www 4297: return %returnhash;
4298: }
4299:
4300: sub get_my_roles {
1.937 raeburn 4301: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4302: unless (defined($uname)) { $uname=$env{'user.name'}; }
4303: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4304: my (%dumphash,%nothide);
1.1086 raeburn 4305: if ($context eq 'userroles') {
1.1166 raeburn 4306: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4307: } else {
1.1172.2.23 raeburn 4308: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4309: if ($hidepriv) {
4310: my %coursehash=&coursedescription($udom.'_'.$uname);
4311: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4312: if ($user !~ /:/) {
4313: $nothide{join(':',split(/[\@]/,$user))} = 1;
4314: } else {
4315: $nothide{$user} = 1;
4316: }
4317: }
4318: }
1.858 raeburn 4319: }
1.400 www 4320: my %returnhash=();
4321: my $now=time;
1.999 raeburn 4322: my %privileged;
1.800 albertel 4323: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4324: my ($role,$tend,$tstart);
4325: if ($context eq 'userroles') {
1.1149 raeburn 4326: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4327: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4328: } else {
4329: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4330: }
1.400 www 4331: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4332: my $status = 'active';
1.939 raeburn 4333: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4334: $status = 'previous';
4335: }
4336: if (($tstart) && ($now<$tstart)) {
4337: $status = 'future';
4338: }
4339: if (ref($types) eq 'ARRAY') {
4340: if (!grep(/^\Q$status\E$/,@{$types})) {
4341: next;
4342: }
4343: } else {
4344: if ($status ne 'active') {
4345: next;
4346: }
4347: }
1.867 raeburn 4348: my ($rolecode,$username,$domain,$section,$area);
4349: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4350: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4351: (undef,$domain,$username,$section) = split(/\//,$area);
4352: } else {
4353: ($role,$username,$domain,$section) = split(/\:/,$entry);
4354: }
1.832 raeburn 4355: if (ref($roledoms) eq 'ARRAY') {
4356: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4357: next;
4358: }
4359: }
4360: if (ref($roles) eq 'ARRAY') {
4361: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4362: if ($role =~ /^cr\//) {
4363: if (!grep(/^cr$/,@{$roles})) {
4364: next;
4365: }
1.1104 raeburn 4366: } elsif ($role =~ /^gr\//) {
4367: if (!grep(/^gr$/,@{$roles})) {
4368: next;
4369: }
1.922 raeburn 4370: } else {
4371: next;
4372: }
1.832 raeburn 4373: }
1.867 raeburn 4374: }
1.937 raeburn 4375: if ($hidepriv) {
1.1172.2.23 raeburn 4376: my @privroles = ('dc','su');
1.999 raeburn 4377: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4378: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4379: } else {
1.1172.2.23 raeburn 4380: my $possdoms = [$domain];
4381: if (ref($roledoms) eq 'ARRAY') {
4382: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4383: }
1.1172.2.23 raeburn 4384: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4385: if (!$nothide{$username.':'.$domain}) {
4386: next;
4387: }
4388: }
1.937 raeburn 4389: }
4390: }
1.933 raeburn 4391: if ($withsec) {
4392: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4393: $tstart.':'.$tend;
4394: } else {
4395: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4396: }
1.832 raeburn 4397: }
1.373 www 4398: return %returnhash;
1.399 www 4399: }
4400:
1.1172.2.89 raeburn 4401: sub get_all_adhocroles {
4402: my ($dom) = @_;
4403: my @roles_by_num = ();
4404: my %domdefaults = &get_domain_defaults($dom);
4405: my (%description,%access_in_dom,%access_info);
4406: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4407: my $count = 0;
4408: my %domcurrent = %{$domdefaults{'adhocroles'}};
4409: my %ordered;
4410: foreach my $role (sort(keys(%domcurrent))) {
4411: my ($order,$desc,$access_in_dom);
4412: if (ref($domcurrent{$role}) eq 'HASH') {
4413: $order = $domcurrent{$role}{'order'};
4414: $desc = $domcurrent{$role}{'desc'};
4415: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4416: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4417: }
4418: if ($order eq '') {
4419: $order = $count;
4420: }
4421: $ordered{$order} = $role;
4422: if ($desc ne '') {
4423: $description{$role} = $desc;
4424: } else {
4425: $description{$role}= $role;
4426: }
4427: $count++;
4428: }
4429: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4430: push(@roles_by_num,$ordered{$item});
4431: }
4432: }
4433: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4434: }
4435:
4436: sub get_my_adhocroles {
4437: my ($cid,$checkreg) = @_;
4438: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4439: if ($env{'request.course.id'} eq $cid) {
4440: $cdom = $env{'course.'.$cid.'.domain'};
4441: $cnum = $env{'course.'.$cid.'.num'};
4442: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4443: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4444: $cdom = $1;
4445: $cnum = $2;
4446: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4447: $cdom,$cnum);
4448: }
4449: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4450: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4451: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4452: if ($rosterhash{$user} ne '') {
4453: my $type = (split(/:/,$rosterhash{$user}))[5];
4454: return ([],{}) if ($type eq 'auto');
4455: }
4456: }
4457: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 4458: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 4459: my $then=$env{'user.login.time'};
4460: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 4461: if (!$update) {
4462: $update = $then;
4463: }
4464: my @liveroles;
4465: foreach my $role ('dh','da') {
4466: if ($env{"user.role.$role./$cdom/"}) {
4467: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
4468: my $limit = $update;
4469: if ($env{'request.role'} eq "$role./$cdom/") {
4470: $limit = $then;
4471: }
4472: my $activerole = 1;
4473: if ($tstart && $tstart>$limit) { $activerole = 0; }
4474: if ($tend && $tend <$limit) { $activerole = 0; }
4475: if ($activerole) {
4476: push(@liveroles,$role);
4477: }
4478: }
4479: }
4480: if (@liveroles) {
1.1172.2.89 raeburn 4481: if (&homeserver($cnum,$cdom) ne 'no_host') {
4482: my ($accessref,$accessinfo,%access_in_dom);
4483: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4484: if (ref($roles_by_num) eq 'ARRAY') {
4485: if (@{$roles_by_num}) {
4486: my %settings;
4487: if ($env{'request.course.id'} eq $cid) {
4488: foreach my $envkey (keys(%env)) {
4489: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4490: $settings{$1} = $env{$envkey};
4491: }
4492: }
4493: } else {
4494: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4495: }
4496: my %setincrs;
4497: if ($settings{'internal.adhocaccess'}) {
4498: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4499: }
4500: my @statuses;
4501: if ($env{'environment.inststatus'}) {
4502: @statuses = split(/,/,$env{'environment.inststatus'});
4503: }
4504: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4505: if (ref($accessref) eq 'HASH') {
4506: %access_in_dom = %{$accessref};
4507: }
4508: foreach my $role (@{$roles_by_num}) {
4509: my ($curraccess,@okstatus,@personnel);
4510: if ($setincrs{$role}) {
4511: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4512: if ($curraccess eq 'status') {
4513: @okstatus = split(/\&/,$rest);
4514: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4515: @personnel = split(/\&/,$rest);
4516: }
4517: } else {
4518: $curraccess = $access_in_dom{$role};
4519: if (ref($accessinfo) eq 'HASH') {
4520: if ($curraccess eq 'status') {
4521: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4522: @okstatus = @{$accessinfo->{$role}};
4523: }
4524: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4525: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4526: @personnel = @{$accessinfo->{$role}};
4527: }
4528: }
4529: }
4530: }
4531: if ($curraccess eq 'none') {
4532: next;
4533: } elsif ($curraccess eq 'all') {
4534: push(@possroles,$role);
1.1172.2.90 raeburn 4535: } elsif ($curraccess eq 'dh') {
4536: if (grep(/^dh$/,@liveroles)) {
4537: push(@possroles,$role);
4538: } else {
4539: next;
4540: }
4541: } elsif ($curraccess eq 'da') {
4542: if (grep(/^da$/,@liveroles)) {
4543: push(@possroles,$role);
4544: } else {
4545: next;
4546: }
1.1172.2.89 raeburn 4547: } elsif ($curraccess eq 'status') {
4548: if (@okstatus) {
4549: if (!@statuses) {
4550: if (grep(/^default$/,@okstatus)) {
4551: push(@possroles,$role);
4552: }
4553: } else {
4554: foreach my $status (@okstatus) {
4555: if (grep(/^\Q$status\E$/,@statuses)) {
4556: push(@possroles,$role);
4557: last;
4558: }
4559: }
4560: }
4561: }
4562: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4563: if (grep(/^\Q$user\E$/,@personnel)) {
4564: if ($curraccess eq 'exc') {
4565: push(@possroles,$role);
4566: }
4567: } elsif ($curraccess eq 'inc') {
4568: push(@possroles,$role);
4569: }
4570: }
4571: }
4572: }
4573: }
4574: }
4575: }
4576: }
4577: }
4578: unless (ref($description) eq 'HASH') {
4579: if (ref($roles_by_num) eq 'ARRAY') {
4580: my %desc;
4581: map { $desc{$_} = $_; } (@{$roles_by_num});
4582: $description = \%desc;
4583: } else {
4584: $description = {};
4585: }
4586: }
4587: return (\@possroles,$description);
4588: }
4589:
1.399 www 4590: # ----------------------------------------------------- Frontpage Announcements
4591: #
4592: #
4593:
4594: sub postannounce {
4595: my ($server,$text)=@_;
1.844 albertel 4596: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4597: unless ($text=~/\w/) { $text=''; }
4598: return &reply('setannounce:'.&escape($text),$server);
4599: }
4600:
4601: sub getannounce {
1.448 albertel 4602:
1.1172.2.96 raeburn 4603: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4604: my $announcement='';
1.800 albertel 4605: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4606: close($fh);
1.399 www 4607: if ($announcement=~/\w/) {
4608: return
4609: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4610: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4611: } else {
4612: return '';
4613: }
4614: } else {
4615: return '';
4616: }
1.351 www 4617: }
1.353 www 4618:
4619: # ---------------------------------------------------------- Course ID routines
4620: # Deal with domain's nohist_courseid.db files
4621: #
4622:
4623: sub courseidput {
1.921 raeburn 4624: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4625: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4626: my $outcome;
4627: if ($caller eq 'timeonly') {
4628: my $cids = '';
4629: foreach my $item (keys(%$storehash)) {
4630: $cids.=&escape($item).'&';
4631: }
4632: $cids=~s/\&$//;
4633: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4634: $coursehome);
4635: } else {
4636: my $items = '';
4637: foreach my $item (keys(%$storehash)) {
4638: $items.= &escape($item).'='.
4639: &freeze_escape($$storehash{$item}).'&';
4640: }
4641: $items=~s/\&$//;
4642: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4643: $coursehome);
1.918 raeburn 4644: }
4645: if ($outcome eq 'unknown_cmd') {
4646: my $what;
4647: foreach my $cid (keys(%$storehash)) {
4648: $what .= &escape($cid).'=';
1.921 raeburn 4649: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4650: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4651: }
4652: $what =~ s/\:$/&/;
4653: }
4654: $what =~ s/\&$//;
4655: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4656: } else {
4657: return $outcome;
4658: }
1.353 www 4659: }
4660:
4661: sub courseiddump {
1.921 raeburn 4662: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4663: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4664: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4665: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4666: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4667: my $as_hash = 1;
4668: my %returnhash;
4669: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4670: my %libserv = &all_library();
4671: foreach my $tryserver (keys(%libserv)) {
4672: if ( ( $hostidflag == 1
4673: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4674: || (!defined($hostidflag)) ) {
4675:
1.918 raeburn 4676: if (($domfilter eq '') ||
4677: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4678: my $rep;
4679: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4680: $rep = &LONCAPA::Lond::dump_course_id_handler(
4681: join(":", (&host_domain($tryserver), $sincefilter,
4682: &escape($descfilter), &escape($instcodefilter),
4683: &escape($ownerfilter), &escape($coursefilter),
4684: &escape($typefilter), &escape($regexp_ok),
4685: $as_hash, &escape($selfenrollonly),
4686: &escape($catfilter), $showhidden, $caller,
4687: &escape($cloner), &escape($cc_clone), $cloneonly,
4688: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4689: &escape($creationcontext),$domcloner,$hasuniquecode,
4690: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4691: } else {
4692: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4693: $sincefilter.':'.&escape($descfilter).':'.
4694: &escape($instcodefilter).':'.&escape($ownerfilter).
4695: ':'.&escape($coursefilter).':'.&escape($typefilter).
4696: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4697: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4698: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4699: &escape($cc_clone).':'.$cloneonly.':'.
4700: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4701: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4702: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4703: }
4704:
1.918 raeburn 4705: my @pairs=split(/\&/,$rep);
4706: foreach my $item (@pairs) {
4707: my ($key,$value)=split(/\=/,$item,2);
4708: $key = &unescape($key);
4709: next if ($key =~ /^error: 2 /);
4710: my $result = &thaw_unescape($value);
4711: if (ref($result) eq 'HASH') {
4712: $returnhash{$key}=$result;
4713: } else {
1.921 raeburn 4714: my @responses = split(/:/,$value);
4715: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4716: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4717: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4718: }
1.1008 raeburn 4719: }
1.353 www 4720: }
4721: }
4722: }
4723: }
4724: return %returnhash;
4725: }
4726:
1.1055 raeburn 4727: sub courselastaccess {
4728: my ($cdom,$cnum,$hostidref) = @_;
4729: my %returnhash;
4730: if ($cdom && $cnum) {
4731: my $chome = &homeserver($cnum,$cdom);
4732: if ($chome ne 'no_host') {
4733: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4734: &extract_lastaccess(\%returnhash,$rep);
4735: }
4736: } else {
4737: if (!$cdom) { $cdom=''; }
4738: my %libserv = &all_library();
4739: foreach my $tryserver (keys(%libserv)) {
4740: if (ref($hostidref) eq 'ARRAY') {
4741: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4742: }
4743: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4744: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4745: &extract_lastaccess(\%returnhash,$rep);
4746: }
4747: }
4748: }
4749: return %returnhash;
4750: }
4751:
4752: sub extract_lastaccess {
4753: my ($returnhash,$rep) = @_;
4754: if (ref($returnhash) eq 'HASH') {
4755: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4756: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4757: $rep eq '') {
4758: my @pairs=split(/\&/,$rep);
4759: foreach my $item (@pairs) {
4760: my ($key,$value)=split(/\=/,$item,2);
4761: $key = &unescape($key);
4762: next if ($key =~ /^error: 2 /);
4763: $returnhash->{$key} = &thaw_unescape($value);
4764: }
4765: }
4766: }
4767: return;
4768: }
4769:
1.658 raeburn 4770: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4771:
4772: sub dcmailput {
1.685 raeburn 4773: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4774: my $status = &Apache::lonnet::critical(
1.740 www 4775: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4776: &escape($message),$server);
1.662 raeburn 4777: return $status;
4778: }
4779:
1.658 raeburn 4780: sub dcmaildump {
4781: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4782: my %returnhash=();
1.846 albertel 4783:
4784: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4785: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4786: &escape($enddate).':';
4787: my @esc_senders=map { &escape($_)} @$senders;
4788: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4789: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4790: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4791: if (($key) && ($value)) {
4792: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4793: }
4794: }
4795: }
4796: return %returnhash;
4797: }
1.662 raeburn 4798: # ---------------------------------------------------------- Domain roles
4799:
4800: sub get_domain_roles {
4801: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4802: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4803: $startdate = '.';
4804: }
1.1018 raeburn 4805: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4806: $enddate = '.';
4807: }
1.922 raeburn 4808: my $rolelist;
4809: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4810: $rolelist = join('&',@{$roles});
1.922 raeburn 4811: }
1.662 raeburn 4812: my %personnel = ();
1.841 albertel 4813:
4814: my %servers = &get_servers($dom,'library');
4815: foreach my $tryserver (keys(%servers)) {
4816: %{$personnel{$tryserver}}=();
4817: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4818: &escape($startdate).':'.
4819: &escape($enddate).':'.
4820: &escape($rolelist), $tryserver))) {
4821: my ($key,$value) = split(/\=/,$line,2);
4822: if (($key) && ($value)) {
4823: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4824: }
4825: }
1.662 raeburn 4826: }
4827: return %personnel;
4828: }
1.658 raeburn 4829:
1.1172.2.89 raeburn 4830: sub get_active_domroles {
4831: my ($dom,$roles) = @_;
4832: return () unless (ref($roles) eq 'ARRAY');
4833: my $now = time;
4834: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4835: my %domroles;
4836: foreach my $server (keys(%dompersonnel)) {
4837: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4838: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4839: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4840: }
4841: }
4842: return %domroles;
4843: }
4844:
1.1057 www 4845: # ----------------------------------------------------------- Interval timing
1.149 www 4846:
1.1153 www 4847: {
4848: # Caches needed for speedup of navmaps
4849: # We don't want to cache this for very long at all (5 seconds at most)
4850: #
4851: # The user for whom we cache
4852: my $cachedkey='';
4853: # The cached times for this user
4854: my %cachedtimes=();
4855: # When this was last done
1.1172.2.66 raeburn 4856: my $cachedtime='';
1.1153 www 4857:
4858: sub load_all_first_access {
1.1154 raeburn 4859: my ($uname,$udom)=@_;
1.1156 www 4860: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4861: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4862: return;
4863: }
4864: $cachedtime=time;
4865: $cachedkey=$uname.':'.$udom;
4866: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4867: }
4868:
1.504 albertel 4869: sub get_first_access {
1.1162 raeburn 4870: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4871: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4872: if ($argsymb) { $symb=$argsymb; }
4873: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4874: if ($argmap) { $map = $argmap; }
1.926 albertel 4875: if ($type eq 'course') {
4876: $res='course';
4877: } elsif ($type eq 'map') {
1.588 albertel 4878: $res=&symbread($map);
4879: } else {
4880: $res=$symb;
4881: }
1.1153 www 4882: &load_all_first_access($uname,$udom);
4883: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4884: }
4885:
4886: sub set_first_access {
1.1162 raeburn 4887: my ($type,$interval)=@_;
1.790 albertel 4888: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4889: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4890: if ($type eq 'course') {
4891: $res='course';
4892: } elsif ($type eq 'map') {
1.588 albertel 4893: $res=&symbread($map);
4894: } else {
4895: $res=$symb;
4896: }
1.1153 www 4897: $cachedkey='';
1.1162 raeburn 4898: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 4899: if ($firstaccess) {
4900: &logthis("First access time already set ($firstaccess) when attempting ".
4901: "to set new value (type: $type, extent: $res) for $uname:$udom ".
4902: "in $courseid");
4903: return 'already_set';
4904: } else {
1.1162 raeburn 4905: my $start = time;
4906: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4907: $udom,$uname);
4908: if ($putres eq 'ok') {
4909: &put('timerinterval',{"$courseid\0$res"=>$interval},
4910: $udom,$uname);
4911: &appenv(
4912: {
4913: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4914: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4915: }
4916: );
1.1172.2.97 raeburn 4917: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
4918: $cachedtimes{"$courseid\0$res"} = $start;
4919: }
1.1172.2.102 raeburn 4920: } elsif ($putres ne 'refused') {
4921: &logthis("Result: $putres when attempting to set first access time ".
4922: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 4923: }
4924: return $putres;
1.505 albertel 4925: }
4926: return 'already_set';
1.504 albertel 4927: }
1.1153 www 4928: }
1.1172.2.32 raeburn 4929:
4930: sub checkout {
4931: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4932: my $now=time;
4933: my $lonhost=$perlvar{'lonHostID'};
4934: my $infostr=&escape(
4935: 'CHECKOUTTOKEN&'.
4936: $tuname.'&'.
4937: $tudom.'&'.
4938: $tcrsid.'&'.
4939: $symb.'&'.
4940: $now.'&'.$ENV{'REMOTE_ADDR'});
4941: my $token=&reply('tmpput:'.$infostr,$lonhost);
4942: if ($token=~/^error\:/) {
4943: &logthis("<font color=\"blue\">WARNING: ".
4944: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4945: "</font>");
4946: return '';
4947: }
4948:
4949: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4950: $token=~tr/a-z/A-Z/;
4951:
4952: my %infohash=('resource.0.outtoken' => $token,
4953: 'resource.0.checkouttime' => $now,
4954: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4955:
4956: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4957: return '';
4958: } else {
4959: &logthis("<font color=\"blue\">WARNING: ".
4960: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4961: "</font>");
4962: }
4963:
4964: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4965: &escape('Checkout '.$infostr.' - '.
4966: $token)) ne 'ok') {
4967: return '';
4968: } else {
4969: &logthis("<font color=\"blue\">WARNING: ".
4970: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4971: "</font>");
4972: }
4973: return $token;
4974: }
4975:
4976: # ------------------------------------------------------------ Check in an item
4977:
4978: sub checkin {
4979: my $token=shift;
4980: my $now=time;
4981: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4982: $lonhost=~tr/A-Z/a-z/;
4983: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4984: $dtoken=~s/\W/\_/g;
4985: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4986: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4987:
4988: unless (($tuname) && ($tudom)) {
4989: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4990: return '';
4991: }
4992:
4993: unless (&allowed('mgr',$tcrsid)) {
4994: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4995: $env{'user.name'}.' - '.$env{'user.domain'});
4996: return '';
4997: }
4998:
4999: my %infohash=('resource.0.intoken' => $token,
5000: 'resource.0.checkintime' => $now,
5001: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
5002:
5003: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5004: return '';
5005: }
5006:
5007: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5008: &escape('Checkin - '.$token)) ne 'ok') {
5009: return '';
5010: }
5011:
5012: return ($symb,$tuname,$tudom,$tcrsid);
5013: }
5014:
1.110 www 5015: # --------------------------------------------- Set Expire Date for Spreadsheet
5016:
5017: sub expirespread {
5018: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5019: my $cid=$env{'request.course.id'};
1.110 www 5020: if ($cid) {
5021: my $now=time;
5022: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5023: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5024: $env{'course.'.$cid.'.num'}.
1.110 www 5025: ':nohist_expirationdates:'.
5026: &escape($key).'='.$now,
1.620 albertel 5027: $env{'course.'.$cid.'.home'})
1.110 www 5028: }
5029: return 'ok';
1.14 www 5030: }
5031:
1.109 www 5032: # ----------------------------------------------------- Devalidate Spreadsheets
5033:
5034: sub devalidate {
1.325 www 5035: my ($symb,$uname,$udom)=@_;
1.620 albertel 5036: my $cid=$env{'request.course.id'};
1.109 www 5037: if ($cid) {
1.391 matthew 5038: # delete the stored spreadsheets for
5039: # - the student level sheet of this user in course's homespace
5040: # - the assessment level sheet for this resource
5041: # for this user in user's homespace
1.553 albertel 5042: # - current conditional state info
1.325 www 5043: my $key=$uname.':'.$udom.':';
1.109 www 5044: my $status=
1.299 matthew 5045: &del('nohist_calculatedsheets',
1.391 matthew 5046: [$key.'studentcalc:'],
1.620 albertel 5047: $env{'course.'.$cid.'.domain'},
5048: $env{'course.'.$cid.'.num'})
1.133 albertel 5049: .' '.
5050: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5051: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5052: unless ($status eq 'ok ok') {
5053: &logthis('Could not devalidate spreadsheet '.
1.325 www 5054: $uname.' at '.$udom.' for '.
1.109 www 5055: $symb.': '.$status);
1.133 albertel 5056: }
1.553 albertel 5057: &delenv('user.state.'.$cid);
1.109 www 5058: }
5059: }
5060:
1.265 albertel 5061: sub get_scalar {
5062: my ($string,$end) = @_;
5063: my $value;
5064: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5065: $value = $1;
5066: } elsif ($$string =~ s/^([^&]*?)&//) {
5067: $value = $1;
5068: }
5069: return &unescape($value);
5070: }
5071:
5072: sub array2str {
5073: my (@array) = @_;
5074: my $result=&arrayref2str(\@array);
5075: $result=~s/^__ARRAY_REF__//;
5076: $result=~s/__END_ARRAY_REF__$//;
5077: return $result;
5078: }
5079:
1.204 albertel 5080: sub arrayref2str {
5081: my ($arrayref) = @_;
1.265 albertel 5082: my $result='__ARRAY_REF__';
1.204 albertel 5083: foreach my $elem (@$arrayref) {
1.265 albertel 5084: if(ref($elem) eq 'ARRAY') {
5085: $result.=&arrayref2str($elem).'&';
5086: } elsif(ref($elem) eq 'HASH') {
5087: $result.=&hashref2str($elem).'&';
5088: } elsif(ref($elem)) {
5089: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5090: } else {
5091: $result.=&escape($elem).'&';
5092: }
5093: }
5094: $result=~s/\&$//;
1.265 albertel 5095: $result .= '__END_ARRAY_REF__';
1.204 albertel 5096: return $result;
5097: }
5098:
1.168 albertel 5099: sub hash2str {
1.204 albertel 5100: my (%hash) = @_;
5101: my $result=&hashref2str(\%hash);
1.265 albertel 5102: $result=~s/^__HASH_REF__//;
5103: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5104: return $result;
5105: }
5106:
5107: sub hashref2str {
5108: my ($hashref)=@_;
1.265 albertel 5109: my $result='__HASH_REF__';
1.800 albertel 5110: foreach my $key (sort(keys(%$hashref))) {
5111: if (ref($key) eq 'ARRAY') {
5112: $result.=&arrayref2str($key).'=';
5113: } elsif (ref($key) eq 'HASH') {
5114: $result.=&hashref2str($key).'=';
5115: } elsif (ref($key)) {
1.265 albertel 5116: $result.='=';
1.800 albertel 5117: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5118: } else {
1.1132 raeburn 5119: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5120: }
5121:
1.800 albertel 5122: if(ref($hashref->{$key}) eq 'ARRAY') {
5123: $result.=&arrayref2str($hashref->{$key}).'&';
5124: } elsif(ref($hashref->{$key}) eq 'HASH') {
5125: $result.=&hashref2str($hashref->{$key}).'&';
5126: } elsif(ref($hashref->{$key})) {
1.265 albertel 5127: $result.='&';
1.800 albertel 5128: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5129: } else {
1.800 albertel 5130: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5131: }
5132: }
1.168 albertel 5133: $result=~s/\&$//;
1.265 albertel 5134: $result .= '__END_HASH_REF__';
1.168 albertel 5135: return $result;
5136: }
5137:
5138: sub str2hash {
1.265 albertel 5139: my ($string)=@_;
5140: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5141: return %$hash;
5142: }
5143:
5144: sub str2hashref {
1.168 albertel 5145: my ($string) = @_;
1.265 albertel 5146:
5147: my %hash;
5148:
5149: if($string !~ /^__HASH_REF__/) {
5150: if (! ($string eq '' || !defined($string))) {
5151: $hash{'error'}='Not hash reference';
5152: }
5153: return (\%hash, $string);
5154: }
5155:
5156: $string =~ s/^__HASH_REF__//;
5157:
5158: while($string !~ /^__END_HASH_REF__/) {
5159: #key
5160: my $key='';
5161: if($string =~ /^__HASH_REF__/) {
5162: ($key, $string)=&str2hashref($string);
5163: if(defined($key->{'error'})) {
5164: $hash{'error'}='Bad data';
5165: return (\%hash, $string);
5166: }
5167: } elsif($string =~ /^__ARRAY_REF__/) {
5168: ($key, $string)=&str2arrayref($string);
5169: if($key->[0] eq 'Array reference error') {
5170: $hash{'error'}='Bad data';
5171: return (\%hash, $string);
5172: }
5173: } else {
5174: $string =~ s/^(.*?)=//;
1.267 albertel 5175: $key=&unescape($1);
1.265 albertel 5176: }
5177: $string =~ s/^=//;
5178:
5179: #value
5180: my $value='';
5181: if($string =~ /^__HASH_REF__/) {
5182: ($value, $string)=&str2hashref($string);
5183: if(defined($value->{'error'})) {
5184: $hash{'error'}='Bad data';
5185: return (\%hash, $string);
5186: }
5187: } elsif($string =~ /^__ARRAY_REF__/) {
5188: ($value, $string)=&str2arrayref($string);
5189: if($value->[0] eq 'Array reference error') {
5190: $hash{'error'}='Bad data';
5191: return (\%hash, $string);
5192: }
5193: } else {
5194: $value=&get_scalar(\$string,'__END_HASH_REF__');
5195: }
5196: $string =~ s/^&//;
5197:
5198: $hash{$key}=$value;
1.204 albertel 5199: }
1.265 albertel 5200:
5201: $string =~ s/^__END_HASH_REF__//;
5202:
5203: return (\%hash, $string);
1.204 albertel 5204: }
5205:
5206: sub str2array {
1.265 albertel 5207: my ($string)=@_;
5208: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5209: return @$array;
5210: }
5211:
5212: sub str2arrayref {
1.204 albertel 5213: my ($string) = @_;
1.265 albertel 5214: my @array;
5215:
5216: if($string !~ /^__ARRAY_REF__/) {
5217: if (! ($string eq '' || !defined($string))) {
5218: $array[0]='Array reference error';
5219: }
5220: return (\@array, $string);
5221: }
5222:
5223: $string =~ s/^__ARRAY_REF__//;
5224:
5225: while($string !~ /^__END_ARRAY_REF__/) {
5226: my $value='';
5227: if($string =~ /^__HASH_REF__/) {
5228: ($value, $string)=&str2hashref($string);
5229: if(defined($value->{'error'})) {
5230: $array[0] ='Array reference error';
5231: return (\@array, $string);
5232: }
5233: } elsif($string =~ /^__ARRAY_REF__/) {
5234: ($value, $string)=&str2arrayref($string);
5235: if($value->[0] eq 'Array reference error') {
5236: $array[0] ='Array reference error';
5237: return (\@array, $string);
5238: }
5239: } else {
5240: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5241: }
5242: $string =~ s/^&//;
5243:
5244: push(@array, $value);
1.191 harris41 5245: }
1.265 albertel 5246:
5247: $string =~ s/^__END_ARRAY_REF__//;
5248:
5249: return (\@array, $string);
1.168 albertel 5250: }
5251:
1.167 albertel 5252: # -------------------------------------------------------------------Temp Store
5253:
1.168 albertel 5254: sub tmpreset {
5255: my ($symb,$namespace,$domain,$stuname) = @_;
5256: if (!$symb) {
5257: $symb=&symbread();
1.620 albertel 5258: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5259: }
5260: $symb=escape($symb);
5261:
1.620 albertel 5262: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5263: $namespace=~s/\//\_/g;
5264: $namespace=~s/\W//g;
5265:
1.620 albertel 5266: if (!$domain) { $domain=$env{'user.domain'}; }
5267: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5268: if ($domain eq 'public' && $stuname eq 'public') {
5269: $stuname=$ENV{'REMOTE_ADDR'};
5270: }
1.1117 foxr 5271: my $path=LONCAPA::tempdir();
1.168 albertel 5272: my %hash;
5273: if (tie(%hash,'GDBM_File',
5274: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5275: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5276: foreach my $key (keys(%hash)) {
1.180 albertel 5277: if ($key=~ /:$symb/) {
1.168 albertel 5278: delete($hash{$key});
5279: }
5280: }
5281: }
5282: }
5283:
1.167 albertel 5284: sub tmpstore {
1.168 albertel 5285: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5286:
5287: if (!$symb) {
5288: $symb=&symbread();
1.620 albertel 5289: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5290: }
5291: $symb=escape($symb);
5292:
5293: if (!$namespace) {
5294: # I don't think we would ever want to store this for a course.
5295: # it seems this will only be used if we don't have a course.
1.620 albertel 5296: #$namespace=$env{'request.course.id'};
1.168 albertel 5297: #if (!$namespace) {
1.620 albertel 5298: $namespace=$env{'request.state'};
1.168 albertel 5299: #}
5300: }
5301: $namespace=~s/\//\_/g;
5302: $namespace=~s/\W//g;
1.620 albertel 5303: if (!$domain) { $domain=$env{'user.domain'}; }
5304: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5305: if ($domain eq 'public' && $stuname eq 'public') {
5306: $stuname=$ENV{'REMOTE_ADDR'};
5307: }
1.168 albertel 5308: my $now=time;
5309: my %hash;
1.1117 foxr 5310: my $path=LONCAPA::tempdir();
1.168 albertel 5311: if (tie(%hash,'GDBM_File',
5312: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5313: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5314: $hash{"version:$symb"}++;
5315: my $version=$hash{"version:$symb"};
5316: my $allkeys='';
5317: foreach my $key (keys(%$storehash)) {
5318: $allkeys.=$key.':';
1.591 albertel 5319: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5320: }
5321: $hash{"$version:$symb:timestamp"}=$now;
5322: $allkeys.='timestamp';
5323: $hash{"$version:keys:$symb"}=$allkeys;
5324: if (untie(%hash)) {
5325: return 'ok';
5326: } else {
5327: return "error:$!";
5328: }
5329: } else {
5330: return "error:$!";
5331: }
5332: }
1.167 albertel 5333:
1.168 albertel 5334: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5335:
1.168 albertel 5336: sub tmprestore {
5337: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5338:
1.168 albertel 5339: if (!$symb) {
5340: $symb=&symbread();
1.620 albertel 5341: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5342: }
5343: $symb=escape($symb);
5344:
1.620 albertel 5345: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5346:
1.620 albertel 5347: if (!$domain) { $domain=$env{'user.domain'}; }
5348: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5349: if ($domain eq 'public' && $stuname eq 'public') {
5350: $stuname=$ENV{'REMOTE_ADDR'};
5351: }
1.168 albertel 5352: my %returnhash;
5353: $namespace=~s/\//\_/g;
5354: $namespace=~s/\W//g;
5355: my %hash;
1.1117 foxr 5356: my $path=LONCAPA::tempdir();
1.168 albertel 5357: if (tie(%hash,'GDBM_File',
5358: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5359: &GDBM_READER(),0640)) {
1.168 albertel 5360: my $version=$hash{"version:$symb"};
5361: $returnhash{'version'}=$version;
5362: my $scope;
5363: for ($scope=1;$scope<=$version;$scope++) {
5364: my $vkeys=$hash{"$scope:keys:$symb"};
5365: my @keys=split(/:/,$vkeys);
5366: my $key;
5367: $returnhash{"$scope:keys"}=$vkeys;
5368: foreach $key (@keys) {
1.591 albertel 5369: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5370: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5371: }
5372: }
1.168 albertel 5373: if (!(untie(%hash))) {
5374: return "error:$!";
5375: }
5376: } else {
5377: return "error:$!";
5378: }
5379: return %returnhash;
1.167 albertel 5380: }
5381:
1.9 www 5382: # ----------------------------------------------------------------------- Store
5383:
5384: sub store {
1.1172.2.64 raeburn 5385: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5386: my $home='';
5387:
1.168 albertel 5388: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5389:
1.213 www 5390: $symb=&symbclean($symb);
1.122 albertel 5391: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5392:
1.620 albertel 5393: if (!$domain) { $domain=$env{'user.domain'}; }
5394: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5395:
5396: &devalidate($symb,$stuname,$domain);
1.109 www 5397:
5398: $symb=escape($symb);
1.187 www 5399: if (!$namespace) {
1.620 albertel 5400: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5401: return '';
5402: }
5403: }
1.620 albertel 5404: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5405:
5406: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5407: $$storehash{'host'}=$perlvar{'lonHostID'};
5408:
1.12 www 5409: my $namevalue='';
1.800 albertel 5410: foreach my $key (keys(%$storehash)) {
5411: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5412: }
1.12 www 5413: $namevalue=~s/\&$//;
1.187 www 5414: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5415: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5416: }
5417:
1.47 www 5418: # -------------------------------------------------------------- Critical Store
5419:
5420: sub cstore {
1.1172.2.64 raeburn 5421: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5422: my $home='';
5423:
1.168 albertel 5424: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5425:
1.213 www 5426: $symb=&symbclean($symb);
1.122 albertel 5427: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5428:
1.620 albertel 5429: if (!$domain) { $domain=$env{'user.domain'}; }
5430: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5431:
5432: &devalidate($symb,$stuname,$domain);
1.109 www 5433:
5434: $symb=escape($symb);
1.187 www 5435: if (!$namespace) {
1.620 albertel 5436: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5437: return '';
5438: }
5439: }
1.620 albertel 5440: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5441:
5442: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5443: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5444:
1.47 www 5445: my $namevalue='';
1.800 albertel 5446: foreach my $key (keys(%$storehash)) {
5447: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5448: }
1.47 www 5449: $namevalue=~s/\&$//;
1.187 www 5450: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5451: return critical
1.1172.2.64 raeburn 5452: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5453: }
5454:
1.9 www 5455: # --------------------------------------------------------------------- Restore
5456:
5457: sub restore {
1.124 www 5458: my ($symb,$namespace,$domain,$stuname) = @_;
5459: my $home='';
5460:
1.168 albertel 5461: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5462:
1.122 albertel 5463: if (!$symb) {
1.1172.2.26 raeburn 5464: return if ($namespace eq 'courserequests');
5465: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5466: } else {
1.1172.2.26 raeburn 5467: unless ($namespace eq 'courserequests') {
5468: $symb=&escape(&symbclean($symb));
5469: }
1.122 albertel 5470: }
1.188 www 5471: if (!$namespace) {
1.620 albertel 5472: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5473: return '';
5474: }
5475: }
1.620 albertel 5476: if (!$domain) { $domain=$env{'user.domain'}; }
5477: if (!$stuname) { $stuname=$env{'user.name'}; }
5478: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5479: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5480:
1.12 www 5481: my %returnhash=();
1.800 albertel 5482: foreach my $line (split(/\&/,$answer)) {
5483: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5484: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5485: }
1.75 www 5486: my $version;
5487: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5488: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5489: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5490: }
1.75 www 5491: }
1.13 www 5492: return %returnhash;
1.34 www 5493: }
5494:
5495: # ---------------------------------------------------------- Course Description
1.1118 foxr 5496: #
5497: #
1.34 www 5498:
5499: sub coursedescription {
1.731 albertel 5500: my ($courseid,$args)=@_;
1.34 www 5501: $courseid=~s/^\///;
1.49 www 5502: $courseid=~s/\_/\//g;
1.34 www 5503: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5504: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5505: my $normalid=$cdomain.'_'.$cnum;
5506: # need to always cache even if we get errors otherwise we keep
5507: # trying and trying and trying to get the course description.
5508: my %envhash=();
5509: my %returnhash=();
1.731 albertel 5510:
5511: my $expiretime=600;
5512: if ($env{'request.course.id'} eq $normalid) {
5513: $expiretime=120;
5514: }
5515:
5516: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5517: if (!$args->{'freshen_cache'}
5518: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5519: foreach my $key (keys(%env)) {
5520: next if ($key !~ /^\Q$prefix\E(.*)/);
5521: my ($setting) = $1;
5522: $returnhash{$setting} = $env{$key};
5523: }
5524: return %returnhash;
5525: }
5526:
1.1118 foxr 5527: # get the data again
5528:
1.731 albertel 5529: if (!$args->{'one_time'}) {
5530: $envhash{'course.'.$normalid.'.last_cache'}=time;
5531: }
1.811 albertel 5532:
1.34 www 5533: if ($chome ne 'no_host') {
1.302 albertel 5534: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5535: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5536: my $username = $env{'user.name'}; # Defult username
5537: if(defined $args->{'user'}) {
5538: $username = $args->{'user'};
5539: }
1.129 albertel 5540: $returnhash{'home'}= $chome;
5541: $returnhash{'domain'} = $cdomain;
5542: $returnhash{'num'} = $cnum;
1.741 raeburn 5543: if (!defined($returnhash{'type'})) {
5544: $returnhash{'type'} = 'Course';
5545: }
1.130 albertel 5546: while (my ($name,$value) = each %returnhash) {
1.53 www 5547: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5548: }
1.270 www 5549: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5550: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5551: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5552: $envhash{'course.'.$normalid.'.home'}=$chome;
5553: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5554: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5555: }
5556: }
1.731 albertel 5557: if (!$args->{'one_time'}) {
1.949 raeburn 5558: &appenv(\%envhash);
1.731 albertel 5559: }
1.302 albertel 5560: return %returnhash;
1.461 www 5561: }
5562:
1.1080 raeburn 5563: sub update_released_required {
5564: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5565: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5566: $cid = $env{'request.course.id'};
5567: $cdom = $env{'course.'.$cid.'.domain'};
5568: $cnum = $env{'course.'.$cid.'.num'};
5569: $chome = $env{'course.'.$cid.'.home'};
5570: }
5571: if ($needsrelease) {
5572: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5573: my $needsupdate;
5574: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5575: $needsupdate = 1;
5576: } else {
5577: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5578: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5579: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5580: $needsupdate = 1;
5581: }
5582: }
5583: if ($needsupdate) {
5584: my %needshash = (
5585: 'internal.releaserequired' => $needsrelease,
5586: );
5587: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5588: if ($putresult eq 'ok') {
5589: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5590: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5591: if (ref($crsinfo{$cid}) eq 'HASH') {
5592: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5593: &courseidput($cdom,\%crsinfo,$chome,'notime');
5594: }
5595: }
5596: }
5597: }
5598: return;
5599: }
5600:
1.461 www 5601: # -------------------------------------------------See if a user is privileged
5602:
5603: sub privileged {
1.1172.2.23 raeburn 5604: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5605: my $now = time;
1.1172.2.23 raeburn 5606: my $roles;
5607: if (ref($possroles) eq 'ARRAY') {
5608: $roles = $possroles;
5609: } else {
5610: $roles = ['dc','su'];
5611: }
5612: if (ref($possdomains) eq 'ARRAY') {
5613: my %privileged = &privileged_by_domain($possdomains,$roles);
5614: foreach my $dom (@{$possdomains}) {
5615: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5616: (ref($privileged{$dom}) eq 'HASH')) {
5617: foreach my $role (@{$roles}) {
5618: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5619: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5620: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5621: return 1 unless (($end && $end < $now) ||
5622: ($start && $start > $now));
5623: }
5624: }
5625: }
5626: }
5627: }
5628: } else {
5629: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5630: my $now = time;
1.1170 droeschl 5631:
1.1172.2.58 raeburn 5632: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5633: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5634: if (grep(/^\Q$trole\E$/,@{$roles})) {
5635: return 1 unless ($tend && $tend < $now)
5636: or ($tstart && $tstart > $now);
1.1170 droeschl 5637: }
1.1172.2.23 raeburn 5638: }
5639: }
1.461 www 5640: return 0;
1.9 www 5641: }
1.1 albertel 5642:
1.1172.2.23 raeburn 5643: sub privileged_by_domain {
5644: my ($domains,$roles) = @_;
5645: my %privileged = ();
5646: my $cachetime = 60*60*24;
5647: my $now = time;
5648: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5649: return %privileged;
5650: }
5651: foreach my $dom (@{$domains}) {
5652: next if (ref($privileged{$dom}) eq 'HASH');
5653: my $needroles;
5654: foreach my $role (@{$roles}) {
5655: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5656: if (defined($cached)) {
5657: if (ref($result) eq 'HASH') {
5658: $privileged{$dom}{$role} = $result;
5659: }
5660: } else {
5661: $needroles = 1;
5662: }
5663: }
5664: if ($needroles) {
5665: my %dompersonnel = &get_domain_roles($dom,$roles);
5666: $privileged{$dom} = {};
5667: foreach my $server (keys(%dompersonnel)) {
5668: if (ref($dompersonnel{$server}) eq 'HASH') {
5669: foreach my $item (keys(%{$dompersonnel{$server}})) {
5670: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5671: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5672: next if ($end && $end < $now);
5673: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5674: $dompersonnel{$server}{$item};
5675: }
5676: }
5677: }
5678: if (ref($privileged{$dom}) eq 'HASH') {
5679: foreach my $role (@{$roles}) {
5680: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5681: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5682: } else {
5683: my %hash = ();
5684: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5685: }
5686: }
5687: }
5688: }
5689: }
5690: return %privileged;
5691: }
5692:
1.103 harris41 5693: # -------------------------------------------------------- Get user privileges
1.11 www 5694:
5695: sub rolesinit {
1.1169 droeschl 5696: my ($domain, $username) = @_;
5697: my %userroles = ('user.login.time' => time);
5698: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5699:
5700: # firstaccess and timerinterval are related to timed maps/resources.
5701: # also, blocking can be triggered by an activating timer
5702: # it's saved in the user's %env.
5703: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5704: my %timerinterval = &dump('timerinterval', $domain, $username);
5705: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5706: %timerintchk, %timerintenv);
5707:
1.1162 raeburn 5708: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5709: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5710: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5711: }
1.1169 droeschl 5712:
1.1162 raeburn 5713: foreach my $key (keys(%timerinterval)) {
5714: my ($cid,$rest) = split(/\0/,$key);
5715: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5716: }
1.1169 droeschl 5717:
1.11 www 5718: my %allroles=();
1.1162 raeburn 5719: my %allgroups=();
1.11 www 5720:
1.1172.2.58 raeburn 5721: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5722: my $role = $rolesdump{$area};
5723: $area =~ s/\_\w\w$//;
5724:
5725: my ($trole, $tend, $tstart, $group_privs);
5726:
5727: if ($role =~ /^cr/) {
5728: # Custom role, defined by a user
5729: # e.g., user.role.cr/msu/smith/mynewrole
5730: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5731: $trole = $1;
5732: ($tend, $tstart) = split('_', $2);
5733: } else {
5734: $trole = $role;
5735: }
5736: } elsif ($role =~ m|^gr/|) {
5737: # Role of member in a group, defined within a course/community
5738: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5739: ($trole, $tend, $tstart) = split(/_/, $role);
5740: next if $tstart eq '-1';
5741: ($trole, $group_privs) = split(/\//, $trole);
5742: $group_privs = &unescape($group_privs);
5743: } else {
5744: # Just a normal role, defined in roles.tab
5745: ($trole, $tend, $tstart) = split(/_/,$role);
5746: }
5747:
5748: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5749: $username);
5750: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5751:
5752: # role expired or not available yet?
5753: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5754: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5755:
5756: next if $area eq '' or $trole eq '';
5757:
5758: my $spec = "$trole.$area";
5759: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5760:
5761: if ($trole =~ /^cr\//) {
5762: # Custom role, defined by a user
5763: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5764: } elsif ($trole eq 'gr') {
5765: # Role of a member in a group, defined within a course/community
5766: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5767: next;
5768: } else {
5769: # Normal role, defined in roles.tab
5770: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5771: }
5772:
5773: my $cid = $tdomain.'_'.$trest;
5774: unless ($firstaccchk{$cid}) {
5775: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5776: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5777: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5778: $coursetimerstarts{$cid}{$item};
5779: }
5780: }
5781: $firstaccchk{$cid} = 1;
5782: }
5783: unless ($timerintchk{$cid}) {
5784: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5785: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5786: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5787: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5788: }
1.12 www 5789: }
1.1169 droeschl 5790: $timerintchk{$cid} = 1;
1.191 harris41 5791: }
1.11 www 5792: }
1.1169 droeschl 5793:
1.1172.2.91 raeburn 5794: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5795: \%allroles, \%allgroups);
1.1169 droeschl 5796: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 5797: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5798:
1.1162 raeburn 5799: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5800: }
5801:
1.567 raeburn 5802: sub set_arearole {
1.1172.2.19 raeburn 5803: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5804: unless ($nolog) {
1.567 raeburn 5805: # log the associated role with the area
1.1172.2.19 raeburn 5806: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5807: }
1.743 albertel 5808: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5809: }
5810:
5811: sub custom_roleprivs {
5812: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5813: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5814: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5815: if (&hostname($homsvr) ne '') {
1.567 raeburn 5816: my ($rdummy,$roledef)=
5817: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5818: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5819: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5820: if (defined($syspriv)) {
1.1043 raeburn 5821: if ($trest =~ /^$match_community$/) {
5822: $syspriv =~ s/bre\&S//;
5823: }
1.567 raeburn 5824: $$allroles{'cm./'}.=':'.$syspriv;
5825: $$allroles{$spec.'./'}.=':'.$syspriv;
5826: }
5827: if ($tdomain ne '') {
5828: if (defined($dompriv)) {
5829: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5830: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5831: }
5832: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 5833: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5834: my $rolename = $1;
5835: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5836: }
1.567 raeburn 5837: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5838: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5839: }
5840: }
5841: }
5842: }
5843: }
5844:
1.1172.2.89 raeburn 5845: sub course_adhocrole_privs {
5846: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5847: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5848: if ($overrides{"internal.adhocpriv.$rolename"}) {
5849: my (%currprivs,%storeprivs);
5850: foreach my $item (split(/:/,$coursepriv)) {
5851: my ($priv,$restrict) = split(/\&/,$item);
5852: $currprivs{$priv} = $restrict;
5853: }
5854: my (%possadd,%possremove,%full);
5855: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5856: my ($priv,$restrict)=split(/\&/,$item);
5857: $full{$priv} = $restrict;
5858: }
5859: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5860: next if ($item eq '');
5861: my ($rule,$rest) = split(/=/,$item);
5862: next unless (($rule eq 'off') || ($rule eq 'on'));
5863: foreach my $priv (split(/:/,$rest)) {
5864: if ($priv ne '') {
5865: if ($rule eq 'off') {
5866: $possremove{$priv} = 1;
5867: } else {
5868: $possadd{$priv} = 1;
5869: }
5870: }
5871: }
5872: }
5873: foreach my $priv (sort(keys(%full))) {
5874: if (exists($currprivs{$priv})) {
5875: unless (exists($possremove{$priv})) {
5876: $storeprivs{$priv} = $currprivs{$priv};
5877: }
5878: } elsif (exists($possadd{$priv})) {
5879: $storeprivs{$priv} = $full{$priv};
5880: }
5881: }
5882: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5883: }
5884: return $coursepriv;
5885: }
5886:
1.678 raeburn 5887: sub group_roleprivs {
5888: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5889: my $access = 1;
5890: my $now = time;
5891: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5892: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5893: if ($access) {
1.811 albertel 5894: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5895: $$allgroups{$course}{$group} .=':'.$group_privs;
5896: }
5897: }
1.567 raeburn 5898:
5899: sub standard_roleprivs {
5900: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5901: if (defined($pr{$trole.':s'})) {
5902: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5903: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5904: }
5905: if ($tdomain ne '') {
5906: if (defined($pr{$trole.':d'})) {
5907: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5908: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5909: }
5910: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5911: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5912: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5913: }
5914: }
5915: }
5916:
5917: sub set_userprivs {
1.1064 raeburn 5918: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5919: my $author=0;
5920: my $adv=0;
1.1172.2.91 raeburn 5921: my $rar=0;
1.678 raeburn 5922: my %grouproles = ();
5923: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5924: my @groupkeys;
1.1000 raeburn 5925: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5926: push(@groupkeys,$role);
5927: }
5928: if (ref($groups_roles) eq 'HASH') {
5929: foreach my $key (keys(%{$groups_roles})) {
5930: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5931: push(@groupkeys,$key);
5932: }
5933: }
5934: }
5935: if (@groupkeys > 0) {
5936: foreach my $role (@groupkeys) {
5937: my ($trole,$area,$sec,$extendedarea);
5938: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5939: $trole = $1;
5940: $area = $2;
5941: $sec = $3;
5942: $extendedarea = $area.$sec;
5943: if (exists($$allgroups{$area})) {
5944: foreach my $group (keys(%{$$allgroups{$area}})) {
5945: my $spec = $trole.'.'.$extendedarea;
5946: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5947: $$allgroups{$area}{$group};
1.1064 raeburn 5948: }
1.678 raeburn 5949: }
5950: }
5951: }
5952: }
5953: }
1.800 albertel 5954: foreach my $group (keys(%grouproles)) {
5955: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5956: }
1.800 albertel 5957: foreach my $role (keys(%{$allroles})) {
5958: my %thesepriv;
1.941 raeburn 5959: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5960: foreach my $item (split(/:/,$$allroles{$role})) {
5961: if ($item ne '') {
5962: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5963: if ($restrictions eq '') {
5964: $thesepriv{$privilege}='F';
5965: } elsif ($thesepriv{$privilege} ne 'F') {
5966: $thesepriv{$privilege}.=$restrictions;
5967: }
5968: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 5969: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5970: }
5971: }
5972: my $thesestr='';
1.1104 raeburn 5973: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5974: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5975: }
5976: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5977: }
1.1172.2.91 raeburn 5978: return ($author,$adv,$rar);
1.567 raeburn 5979: }
5980:
1.994 raeburn 5981: sub role_status {
1.1104 raeburn 5982: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5983: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5984: my ($one,$two) = split(m{\./},$rolekey,2);
5985: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5986: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5987: $$where = '/'.$two;
1.994 raeburn 5988: $$trolecode=$$role.'.'.$$where;
5989: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5990: $$tstatus='is';
1.1104 raeburn 5991: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5992: $$tstatus='future';
1.1034 raeburn 5993: if ($$tstart<$now) {
5994: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5995: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5996: my (%allroles,%allgroups,$group_privs,
5997: %groups_roles,@rolecodes);
1.1002 raeburn 5998: my %userroles = (
5999: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6000: );
1.1064 raeburn 6001: @rolecodes = ('cm');
1.1002 raeburn 6002: my $spec=$$role.'.'.$$where;
6003: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6004: if ($$role =~ /^cr\//) {
6005: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6006: push(@rolecodes,'cr');
1.1002 raeburn 6007: } elsif ($$role eq 'gr') {
1.1064 raeburn 6008: push(@rolecodes,$$role);
1.1002 raeburn 6009: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6010: $env{'user.name'});
1.1064 raeburn 6011: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6012: (undef,my $group_privs) = split(/\//,$trole);
6013: $group_privs = &unescape($group_privs);
6014: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6015: 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 6016: &get_groups_roles($tdomain,$trest,
6017: \%course_roles,\@rolecodes,
6018: \%groups_roles);
1.1002 raeburn 6019: } else {
1.1064 raeburn 6020: push(@rolecodes,$$role);
1.1002 raeburn 6021: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6022: }
1.1172.2.91 raeburn 6023: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6024: \%groups_roles);
1.1064 raeburn 6025: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6026: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6027: }
6028: }
1.1034 raeburn 6029: $$tstatus = 'is';
1.1002 raeburn 6030: }
1.994 raeburn 6031: }
6032: if ($$tend) {
1.1104 raeburn 6033: if ($$tend<$update) {
1.994 raeburn 6034: $$tstatus='expired';
6035: } elsif ($$tend<$now) {
6036: $$tstatus='will_not';
6037: }
6038: }
6039: }
6040: }
6041: }
6042:
1.1104 raeburn 6043: sub get_groups_roles {
6044: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6045: return unless((ref($cdom_courseroles) eq 'HASH') &&
6046: (ref($rolecodes) eq 'ARRAY') &&
6047: (ref($groups_roles) eq 'HASH'));
6048: if (keys(%{$cdom_courseroles}) > 0) {
6049: my ($cnum) = ($rest =~ /^($match_courseid)/);
6050: if ($cdom ne '' && $cnum ne '') {
6051: foreach my $key (keys(%{$cdom_courseroles})) {
6052: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6053: my $crsrole = $1;
6054: my $crssec = $2;
6055: if ($crsrole =~ /^cr/) {
6056: unless (grep(/^cr$/,@{$rolecodes})) {
6057: push(@{$rolecodes},'cr');
6058: }
6059: } else {
6060: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6061: push(@{$rolecodes},$crsrole);
6062: }
6063: }
6064: my $rolekey = "$crsrole./$cdom/$cnum";
6065: if ($crssec ne '') {
6066: $rolekey .= "/$crssec";
6067: }
6068: $rolekey .= './';
6069: $groups_roles->{$rolekey} = $rolecodes;
6070: }
6071: }
6072: }
6073: }
6074: return;
6075: }
6076:
6077: sub delete_env_groupprivs {
6078: my ($where,$courseroles,$possroles) = @_;
6079: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6080: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6081: unless (ref($courseroles->{$udom}) eq 'HASH') {
6082: %{$courseroles->{$udom}} =
6083: &get_my_roles('','','userroles',['active'],
6084: $possroles,[$udom],1);
6085: }
6086: if (ref($courseroles->{$udom}) eq 'HASH') {
6087: foreach my $item (keys(%{$courseroles->{$udom}})) {
6088: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6089: my $area = '/'.$cdom.'/'.$cnum;
6090: my $privkey = "user.priv.$crsrole.$area";
6091: if ($crssec ne '') {
6092: $privkey .= '/'.$crssec;
6093: }
6094: $privkey .= ".$area/$group";
6095: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6096: }
6097: }
6098: return;
6099: }
6100:
1.994 raeburn 6101: sub check_adhoc_privs {
1.1172.2.86 raeburn 6102: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6103: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6104: if ($sec) {
6105: $cckey .= '/'.$sec;
6106: }
1.1172.2.9 raeburn 6107: my $setprivs;
1.994 raeburn 6108: if ($env{$cckey}) {
6109: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6110: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6111: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6112: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6113: $setprivs = 1;
1.994 raeburn 6114: }
6115: } else {
1.1172.2.87 raeburn 6116: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6117: $setprivs = 1;
1.994 raeburn 6118: }
1.1172.2.9 raeburn 6119: return $setprivs;
1.994 raeburn 6120: }
6121:
6122: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6123: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6124: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6125: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6126: if ($sec ne '') {
6127: $area .= '/'.$sec;
6128: }
1.994 raeburn 6129: my $spec = $role.'.'.$area;
6130: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6131: $env{'user.name'},1);
1.1172.2.84 raeburn 6132: my %rolehash = ();
1.1172.2.89 raeburn 6133: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6134: my $rolename = $1;
1.1172.2.84 raeburn 6135: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6136: my %domdef = &get_domain_defaults($dcdom);
6137: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6138: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6139: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6140: }
6141: }
1.1172.2.84 raeburn 6142: } else {
6143: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6144: }
1.1172.2.91 raeburn 6145: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6146: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6147: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6148: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6149: &appenv( {'request.role' => $spec,
6150: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6151: 'request.course.sec' => $sec,
1.1088 raeburn 6152: }
6153: );
6154: my $tadv=0;
6155: if (&allowed('adv') eq 'F') { $tadv=1; }
6156: &appenv({'request.role.adv' => $tadv});
6157: }
1.994 raeburn 6158: }
6159:
1.12 www 6160: # --------------------------------------------------------------- get interface
6161:
6162: sub get {
1.131 albertel 6163: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6164: my $items='';
1.800 albertel 6165: foreach my $item (@$storearr) {
6166: $items.=&escape($item).'&';
1.191 harris41 6167: }
1.12 www 6168: $items=~s/\&$//;
1.620 albertel 6169: if (!$udomain) { $udomain=$env{'user.domain'}; }
6170: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6171: my $uhome=&homeserver($uname,$udomain);
6172:
1.133 albertel 6173: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6174: my @pairs=split(/\&/,$rep);
1.273 albertel 6175: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6176: return @pairs;
6177: }
1.15 www 6178: my %returnhash=();
1.42 www 6179: my $i=0;
1.800 albertel 6180: foreach my $item (@$storearr) {
6181: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6182: $i++;
1.191 harris41 6183: }
1.15 www 6184: return %returnhash;
1.27 www 6185: }
6186:
6187: # --------------------------------------------------------------- del interface
6188:
6189: sub del {
1.133 albertel 6190: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6191: my $items='';
1.800 albertel 6192: foreach my $item (@$storearr) {
6193: $items.=&escape($item).'&';
1.191 harris41 6194: }
1.984 neumanie 6195:
1.27 www 6196: $items=~s/\&$//;
1.620 albertel 6197: if (!$udomain) { $udomain=$env{'user.domain'}; }
6198: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6199: my $uhome=&homeserver($uname,$udomain);
6200: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6201: }
6202:
6203: # -------------------------------------------------------------- dump interface
6204:
1.1172.2.22 raeburn 6205: sub unserialize {
6206: my ($rep, $escapedkeys) = @_;
6207:
6208: return {} if $rep =~ /^error/;
6209:
6210: my %returnhash=();
6211: foreach my $item (split(/\&/,$rep)) {
6212: my ($key, $value) = split(/=/, $item, 2);
6213: $key = unescape($key) unless $escapedkeys;
6214: next if $key =~ /^error: 2 /;
6215: $returnhash{$key} = &thaw_unescape($value);
6216: }
6217: return \%returnhash;
6218: }
6219:
6220: # see Lond::dump_with_regexp
6221: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6222: sub dump {
1.1172.2.22 raeburn 6223: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6224: if (!$udomain) { $udomain=$env{'user.domain'}; }
6225: if (!$uname) { $uname=$env{'user.name'}; }
6226: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6227:
1.1172.2.55 raeburn 6228: if ($regexp) {
6229: $regexp=&escape($regexp);
6230: } else {
6231: $regexp='.';
6232: }
1.1172.2.22 raeburn 6233: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6234: # user is hosted on this machine
1.1172.2.55 raeburn 6235: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6236: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6237: return %{&unserialize($reply, $escapedkeys)};
6238: }
1.1166 raeburn 6239: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6240: my @pairs=split(/\&/,$rep);
6241: my %returnhash=();
1.1098 foxr 6242: if (!($rep =~ /^error/ )) {
6243: foreach my $item (@pairs) {
6244: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6245: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6246: next if ($key =~ /^error: 2 /);
6247: $returnhash{$key}=&thaw_unescape($value);
6248: }
1.755 albertel 6249: }
6250: return %returnhash;
1.407 www 6251: }
6252:
1.1098 foxr 6253:
1.717 albertel 6254: # --------------------------------------------------------- dumpstore interface
6255:
6256: sub dumpstore {
6257: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6258: # same as dump but keys must be escaped. They may contain colon separated
6259: # lists of values that may themself contain colons (e.g. symbs).
6260: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6261: }
6262:
1.407 www 6263: # -------------------------------------------------------------- keys interface
6264:
6265: sub getkeys {
6266: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6267: if (!$udomain) { $udomain=$env{'user.domain'}; }
6268: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6269: my $uhome=&homeserver($uname,$udomain);
6270: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6271: my @keyarray=();
1.800 albertel 6272: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6273: next if ($key =~ /^error: 2 /);
1.800 albertel 6274: push(@keyarray,&unescape($key));
1.407 www 6275: }
6276: return @keyarray;
1.318 matthew 6277: }
6278:
1.319 matthew 6279: # --------------------------------------------------------------- currentdump
6280: sub currentdump {
1.328 matthew 6281: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6282: $courseid = $env{'request.course.id'} if (! defined($courseid));
6283: $sdom = $env{'user.domain'} if (! defined($sdom));
6284: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6285: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6286: my $rep;
6287:
6288: if (grep { $_ eq $uhome } current_machine_ids()) {
6289: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6290: $courseid)));
6291: } else {
6292: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6293: }
6294:
1.318 matthew 6295: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6296: #
1.318 matthew 6297: my %returnhash=();
1.319 matthew 6298: #
6299: if ($rep eq "unknown_cmd") {
6300: # an old lond will not know currentdump
6301: # Do a dump and make it look like a currentdump
1.822 albertel 6302: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6303: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6304: my %hash = @tmp;
6305: @tmp=();
1.424 matthew 6306: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6307: } else {
6308: my @pairs=split(/\&/,$rep);
1.800 albertel 6309: foreach my $pair (@pairs) {
6310: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6311: my ($symb,$param) = split(/:/,$key);
6312: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6313: &thaw_unescape($value);
1.319 matthew 6314: }
1.191 harris41 6315: }
1.12 www 6316: return %returnhash;
1.424 matthew 6317: }
6318:
6319: sub convert_dump_to_currentdump{
6320: my %hash = %{shift()};
6321: my %returnhash;
6322: # Code ripped from lond, essentially. The only difference
6323: # here is the unescaping done by lonnet::dump(). Conceivably
6324: # we might run in to problems with parameter names =~ /^v\./
6325: while (my ($key,$value) = each(%hash)) {
6326: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6327: $symb = &unescape($symb);
6328: $param = &unescape($param);
1.424 matthew 6329: next if ($v eq 'version' || $symb eq 'keys');
6330: next if (exists($returnhash{$symb}) &&
6331: exists($returnhash{$symb}->{$param}) &&
6332: $returnhash{$symb}->{'v.'.$param} > $v);
6333: $returnhash{$symb}->{$param}=$value;
6334: $returnhash{$symb}->{'v.'.$param}=$v;
6335: }
6336: #
6337: # Remove all of the keys in the hashes which keep track of
6338: # the version of the parameter.
6339: while (my ($symb,$param_hash) = each(%returnhash)) {
6340: # use a foreach because we are going to delete from the hash.
6341: foreach my $key (keys(%$param_hash)) {
6342: delete($param_hash->{$key}) if ($key =~ /^v\./);
6343: }
6344: }
6345: return \%returnhash;
1.12 www 6346: }
6347:
1.627 albertel 6348: # ------------------------------------------------------ critical inc interface
6349:
6350: sub cinc {
6351: return &inc(@_,'critical');
6352: }
6353:
1.449 matthew 6354: # --------------------------------------------------------------- inc interface
6355:
6356: sub inc {
1.627 albertel 6357: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6358: if (!$udomain) { $udomain=$env{'user.domain'}; }
6359: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6360: my $uhome=&homeserver($uname,$udomain);
6361: my $items='';
6362: if (! ref($store)) {
6363: # got a single value, so use that instead
6364: $items = &escape($store).'=&';
6365: } elsif (ref($store) eq 'SCALAR') {
6366: $items = &escape($$store).'=&';
6367: } elsif (ref($store) eq 'ARRAY') {
6368: $items = join('=&',map {&escape($_);} @{$store});
6369: } elsif (ref($store) eq 'HASH') {
6370: while (my($key,$value) = each(%{$store})) {
6371: $items.= &escape($key).'='.&escape($value).'&';
6372: }
6373: }
6374: $items=~s/\&$//;
1.627 albertel 6375: if ($critical) {
6376: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6377: } else {
6378: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6379: }
1.449 matthew 6380: }
6381:
1.12 www 6382: # --------------------------------------------------------------- put interface
6383:
6384: sub put {
1.134 albertel 6385: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6386: if (!$udomain) { $udomain=$env{'user.domain'}; }
6387: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6388: my $uhome=&homeserver($uname,$udomain);
1.12 www 6389: my $items='';
1.800 albertel 6390: foreach my $item (keys(%$storehash)) {
6391: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6392: }
1.12 www 6393: $items=~s/\&$//;
1.134 albertel 6394: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6395: }
6396:
1.631 albertel 6397: # ------------------------------------------------------------ newput interface
6398:
6399: sub newput {
6400: my ($namespace,$storehash,$udomain,$uname)=@_;
6401: if (!$udomain) { $udomain=$env{'user.domain'}; }
6402: if (!$uname) { $uname=$env{'user.name'}; }
6403: my $uhome=&homeserver($uname,$udomain);
6404: my $items='';
6405: foreach my $key (keys(%$storehash)) {
6406: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6407: }
6408: $items=~s/\&$//;
6409: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6410: }
6411:
6412: # --------------------------------------------------------- putstore interface
6413:
1.524 raeburn 6414: sub putstore {
1.1172.2.59 raeburn 6415: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6416: if (!$udomain) { $udomain=$env{'user.domain'}; }
6417: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6418: my $uhome=&homeserver($uname,$udomain);
6419: my $items='';
1.715 albertel 6420: foreach my $key (keys(%$storehash)) {
6421: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6422: }
1.715 albertel 6423: $items=~s/\&$//;
1.716 albertel 6424: my $esc_symb=&escape($symb);
6425: my $esc_v=&escape($version);
1.715 albertel 6426: my $reply =
1.716 albertel 6427: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6428: $uhome);
1.1172.2.59 raeburn 6429: if (($tolog) && ($reply eq 'ok')) {
6430: my $namevalue='';
6431: foreach my $key (keys(%{$storehash})) {
6432: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6433: }
6434: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6435: '&host='.&escape($perlvar{'lonHostID'}).
6436: '&version='.$esc_v.
6437: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6438: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6439: }
1.715 albertel 6440: if ($reply eq 'unknown_cmd') {
1.716 albertel 6441: # gfall back to way things use to be done
1.715 albertel 6442: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6443: $uname);
1.524 raeburn 6444: }
1.715 albertel 6445: return $reply;
6446: }
6447:
6448: sub old_putstore {
1.716 albertel 6449: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6450: if (!$udomain) { $udomain=$env{'user.domain'}; }
6451: if (!$uname) { $uname=$env{'user.name'}; }
6452: my $uhome=&homeserver($uname,$udomain);
6453: my %newstorehash;
1.800 albertel 6454: foreach my $item (keys(%$storehash)) {
6455: my $key = $version.':'.&escape($symb).':'.$item;
6456: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6457: }
6458: my $items='';
6459: my %allitems = ();
1.800 albertel 6460: foreach my $item (keys(%newstorehash)) {
6461: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6462: my $key = $1.':keys:'.$2;
6463: $allitems{$key} .= $3.':';
6464: }
1.800 albertel 6465: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6466: }
1.800 albertel 6467: foreach my $item (keys(%allitems)) {
6468: $allitems{$item} =~ s/\:$//;
6469: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6470: }
6471: $items=~s/\&$//;
6472: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6473: }
6474:
1.47 www 6475: # ------------------------------------------------------ critical put interface
6476:
6477: sub cput {
1.134 albertel 6478: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6479: if (!$udomain) { $udomain=$env{'user.domain'}; }
6480: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6481: my $uhome=&homeserver($uname,$udomain);
1.47 www 6482: my $items='';
1.800 albertel 6483: foreach my $item (keys(%$storehash)) {
6484: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6485: }
1.47 www 6486: $items=~s/\&$//;
1.134 albertel 6487: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6488: }
6489:
6490: # -------------------------------------------------------------- eget interface
6491:
6492: sub eget {
1.133 albertel 6493: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6494: my $items='';
1.800 albertel 6495: foreach my $item (@$storearr) {
6496: $items.=&escape($item).'&';
1.191 harris41 6497: }
1.12 www 6498: $items=~s/\&$//;
1.620 albertel 6499: if (!$udomain) { $udomain=$env{'user.domain'}; }
6500: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6501: my $uhome=&homeserver($uname,$udomain);
6502: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6503: my @pairs=split(/\&/,$rep);
6504: my %returnhash=();
1.42 www 6505: my $i=0;
1.800 albertel 6506: foreach my $item (@$storearr) {
6507: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6508: $i++;
1.191 harris41 6509: }
1.12 www 6510: return %returnhash;
6511: }
6512:
1.667 albertel 6513: # ------------------------------------------------------------ tmpput interface
6514: sub tmpput {
1.802 raeburn 6515: my ($storehash,$server,$context)=@_;
1.667 albertel 6516: my $items='';
1.800 albertel 6517: foreach my $item (keys(%$storehash)) {
6518: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6519: }
6520: $items=~s/\&$//;
1.802 raeburn 6521: if (defined($context)) {
6522: $items .= ':'.&escape($context);
6523: }
1.667 albertel 6524: return &reply("tmpput:$items",$server);
6525: }
6526:
6527: # ------------------------------------------------------------ tmpget interface
6528: sub tmpget {
1.688 albertel 6529: my ($token,$server)=@_;
6530: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6531: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6532: my %returnhash;
1.1172.2.85 raeburn 6533: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6534: return %returnhash;
6535: }
1.667 albertel 6536: foreach my $item (split(/\&/,$rep)) {
6537: my ($key,$value)=split(/=/,$item);
6538: $returnhash{&unescape($key)}=&thaw_unescape($value);
6539: }
6540: return %returnhash;
6541: }
6542:
1.1113 raeburn 6543: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6544: sub tmpdel {
6545: my ($token,$server)=@_;
6546: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6547: return &reply("tmpdel:$token",$server);
6548: }
6549:
1.1172.2.13 raeburn 6550: # ------------------------------------------------------------ get_timebased_id
6551:
6552: sub get_timebased_id {
6553: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6554: $maxtries) = @_;
6555: my ($newid,$error,$dellock);
6556: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6557: return ('','ok','invalid call to get suffix');
6558: }
6559:
6560: # set defaults for any optional args for which values were not supplied
6561: if ($who eq '') {
6562: $who = $env{'user.name'}.':'.$env{'user.domain'};
6563: }
6564: if (!$locktries) {
6565: $locktries = 3;
6566: }
6567: if (!$maxtries) {
6568: $maxtries = 10;
6569: }
6570:
6571: if (($cdom eq '') || ($cnum eq '')) {
6572: if ($env{'request.course.id'}) {
6573: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6574: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6575: }
6576: if (($cdom eq '') || ($cnum eq '')) {
6577: return ('','ok','call to get suffix not in course context');
6578: }
6579: }
6580:
6581: # construct locking item
6582: my $lockhash = {
6583: $prefix."\0".'locked_'.$keyid => $who,
6584: };
6585: my $tries = 0;
6586:
6587: # attempt to get lock on nohist_$namespace file
6588: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6589: while (($gotlock ne 'ok') && $tries <$locktries) {
6590: $tries ++;
6591: sleep 1;
6592: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6593: }
6594:
6595: # attempt to get unique identifier, based on current timestamp
6596: if ($gotlock eq 'ok') {
6597: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6598: my $id = time;
6599: $newid = $id;
1.1172.2.56 raeburn 6600: if ($idtype eq 'addcode') {
6601: $newid .= &sixnum_code();
6602: }
1.1172.2.13 raeburn 6603: my $idtries = 0;
6604: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6605: if ($idtype eq 'concat') {
6606: $newid = $id.$idtries;
1.1172.2.56 raeburn 6607: } elsif ($idtype eq 'addcode') {
6608: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6609: } else {
6610: $newid ++;
6611: }
6612: $idtries ++;
6613: }
6614: if (!exists($inuse{$prefix."\0".$newid})) {
6615: my %new_item = (
6616: $prefix."\0".$newid => $who,
6617: );
6618: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6619: $cdom,$cnum);
6620: if ($putresult ne 'ok') {
6621: undef($newid);
6622: $error = 'error saving new item: '.$putresult;
6623: }
6624: } else {
1.1172.2.56 raeburn 6625: undef($newid);
1.1172.2.13 raeburn 6626: $error = ('error: no unique suffix available for the new item ');
6627: }
6628: # remove lock
6629: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6630: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6631: } else {
6632: $error = "error: could not obtain lockfile\n";
6633: $dellock = 'ok';
1.1172.2.58 raeburn 6634: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6635: $dellock = 'nolock';
6636: }
1.1172.2.13 raeburn 6637: }
6638: return ($newid,$dellock,$error);
6639: }
6640:
1.1172.2.56 raeburn 6641: sub sixnum_code {
6642: my $code;
6643: for (0..6) {
6644: $code .= int( rand(9) );
6645: }
6646: return $code;
6647: }
6648:
1.765 albertel 6649: # -------------------------------------------------- portfolio access checking
6650:
6651: sub portfolio_access {
1.1172.2.77 raeburn 6652: my ($requrl,$clientip) = @_;
1.765 albertel 6653: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6654: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6655: if ($result) {
6656: my %setters;
6657: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6658: my ($startblock,$endblock) =
6659: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6660: if ($startblock && $endblock) {
6661: return 'B';
6662: }
6663: } else {
6664: my ($startblock,$endblock) =
6665: &Apache::loncommon::blockcheck(\%setters,'port');
6666: if ($startblock && $endblock) {
6667: return 'B';
6668: }
6669: }
6670: }
1.765 albertel 6671: if ($result eq 'ok') {
1.766 albertel 6672: return 'F';
1.765 albertel 6673: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6674: return 'A';
1.765 albertel 6675: }
1.766 albertel 6676: return '';
1.765 albertel 6677: }
6678:
6679: sub get_portfolio_access {
1.1172.2.77 raeburn 6680: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6681:
6682: if (!ref($access_hash)) {
6683: my $current_perms = &get_portfile_permissions($udom,$unum);
6684: my %access_controls = &get_access_controls($current_perms,$group,
6685: $file_name);
6686: $access_hash = $access_controls{$file_name};
6687: }
6688:
1.1172.2.77 raeburn 6689: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6690: my $now = time;
6691: if (ref($access_hash) eq 'HASH') {
6692: foreach my $key (keys(%{$access_hash})) {
6693: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6694: if ($start > $now) {
6695: next;
6696: }
6697: if ($end && $end<$now) {
6698: next;
6699: }
6700: if ($scope eq 'public') {
6701: $public = $key;
6702: last;
6703: } elsif ($scope eq 'guest') {
6704: $guest = $key;
6705: } elsif ($scope eq 'domains') {
6706: push(@domains,$key);
6707: } elsif ($scope eq 'users') {
6708: push(@users,$key);
6709: } elsif ($scope eq 'course') {
6710: push(@courses,$key);
6711: } elsif ($scope eq 'group') {
6712: push(@groups,$key);
1.1172.2.77 raeburn 6713: } elsif ($scope eq 'ip') {
6714: push(@ips,$key);
1.765 albertel 6715: }
6716: }
6717: if ($public) {
6718: return 'ok';
1.1172.2.77 raeburn 6719: } elsif (@ips > 0) {
6720: my $allowed;
6721: foreach my $ipkey (@ips) {
6722: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6723: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6724: $allowed = 1;
6725: last;
6726: }
6727: }
6728: }
6729: if ($allowed) {
6730: return 'ok';
6731: }
1.765 albertel 6732: }
6733: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6734: if ($guest) {
6735: return $guest;
6736: }
6737: } else {
6738: if (@domains > 0) {
6739: foreach my $domkey (@domains) {
6740: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6741: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6742: return 'ok';
6743: }
6744: }
6745: }
6746: }
6747: if (@users > 0) {
6748: foreach my $userkey (@users) {
1.865 raeburn 6749: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6750: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6751: if (ref($item) eq 'HASH') {
6752: if (($item->{'uname'} eq $env{'user.name'}) &&
6753: ($item->{'udom'} eq $env{'user.domain'})) {
6754: return 'ok';
6755: }
6756: }
6757: }
6758: }
1.765 albertel 6759: }
6760: }
6761: my %roleshash;
6762: my @courses_and_groups = @courses;
6763: push(@courses_and_groups,@groups);
6764: if (@courses_and_groups > 0) {
6765: my (%allgroups,%allroles);
6766: my ($start,$end,$role,$sec,$group);
6767: foreach my $envkey (%env) {
1.1060 raeburn 6768: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6769: my $cid = $2.'_'.$3;
6770: if ($1 eq 'gr') {
6771: $group = $4;
6772: $allgroups{$cid}{$group} = $env{$envkey};
6773: } else {
6774: if ($4 eq '') {
6775: $sec = 'none';
6776: } else {
6777: $sec = $4;
6778: }
6779: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6780: }
1.811 albertel 6781: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6782: my $cid = $2.'_'.$3;
6783: if ($4 eq '') {
6784: $sec = 'none';
6785: } else {
6786: $sec = $4;
6787: }
6788: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6789: }
6790: }
6791: if (keys(%allroles) == 0) {
6792: return;
6793: }
6794: foreach my $key (@courses_and_groups) {
6795: my %content = %{$$access_hash{$key}};
6796: my $cnum = $content{'number'};
6797: my $cdom = $content{'domain'};
6798: my $cid = $cdom.'_'.$cnum;
6799: if (!exists($allroles{$cid})) {
6800: next;
6801: }
6802: foreach my $role_id (keys(%{$content{'roles'}})) {
6803: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6804: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6805: my @status = @{$content{'roles'}{$role_id}{'access'}};
6806: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6807: foreach my $role (keys(%{$allroles{$cid}})) {
6808: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6809: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6810: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6811: if (grep/^all$/,@sections) {
6812: return 'ok';
6813: } else {
6814: if (grep/^$sec$/,@sections) {
6815: return 'ok';
6816: }
6817: }
6818: }
6819: }
6820: if (keys(%{$allgroups{$cid}}) == 0) {
6821: if (grep/^none$/,@groups) {
6822: return 'ok';
6823: }
6824: } else {
6825: if (grep/^all$/,@groups) {
6826: return 'ok';
6827: }
6828: foreach my $group (keys(%{$allgroups{$cid}})) {
6829: if (grep/^$group$/,@groups) {
6830: return 'ok';
6831: }
6832: }
6833: }
6834: }
6835: }
6836: }
6837: }
6838: }
6839: if ($guest) {
6840: return $guest;
6841: }
6842: }
6843: }
6844: return;
6845: }
6846:
6847: sub course_group_datechecker {
6848: my ($dates,$now,$status) = @_;
6849: my ($start,$end) = split(/\./,$dates);
6850: if (!$start && !$end) {
6851: return 'ok';
6852: }
6853: if (grep/^active$/,@{$status}) {
6854: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6855: return 'ok';
6856: }
6857: }
6858: if (grep/^previous$/,@{$status}) {
6859: if ($end > $now ) {
6860: return 'ok';
6861: }
6862: }
6863: if (grep/^future$/,@{$status}) {
6864: if ($start > $now) {
6865: return 'ok';
6866: }
6867: }
6868: return;
6869: }
6870:
6871: sub parse_portfolio_url {
6872: my ($url) = @_;
6873:
6874: my ($type,$udom,$unum,$group,$file_name);
6875:
1.823 albertel 6876: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6877: $type = 1;
6878: $udom = $1;
6879: $unum = $2;
6880: $file_name = $3;
1.823 albertel 6881: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6882: $type = 2;
6883: $udom = $1;
6884: $unum = $2;
6885: $group = $3;
6886: $file_name = $3.'/'.$4;
6887: }
6888: if (wantarray) {
6889: return ($type,$udom,$unum,$file_name,$group);
6890: }
6891: return $type;
6892: }
6893:
6894: sub is_portfolio_url {
6895: my ($url) = @_;
6896: return scalar(&parse_portfolio_url($url));
6897: }
6898:
1.798 raeburn 6899: sub is_portfolio_file {
6900: my ($file) = @_;
1.820 raeburn 6901: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6902: return 1;
6903: }
6904: return;
6905: }
6906:
1.976 raeburn 6907: sub usertools_access {
1.1084 raeburn 6908: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6909: my ($access,%tools);
6910: if ($context eq '') {
6911: $context = 'tools';
6912: }
6913: if ($context eq 'requestcourses') {
6914: %tools = (
6915: official => 1,
6916: unofficial => 1,
1.1006 raeburn 6917: community => 1,
1.1172.2.37 raeburn 6918: textbook => 1,
1.985 raeburn 6919: );
1.1172.2.9 raeburn 6920: } elsif ($context eq 'requestauthor') {
6921: %tools = (
6922: requestauthor => 1,
6923: );
1.985 raeburn 6924: } else {
6925: %tools = (
6926: aboutme => 1,
6927: blog => 1,
1.1172.2.6 raeburn 6928: webdav => 1,
1.985 raeburn 6929: portfolio => 1,
6930: );
6931: }
1.976 raeburn 6932: return if (!defined($tools{$tool}));
6933:
1.1172.2.35 raeburn 6934: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6935: $udom = $env{'user.domain'};
6936: $uname = $env{'user.name'};
6937: }
6938:
1.978 raeburn 6939: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6940: if ($action ne 'reload') {
1.985 raeburn 6941: if ($context eq 'requestcourses') {
6942: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6943: } elsif ($context eq 'requestauthor') {
6944: return $env{'environment.canrequest.author'};
1.985 raeburn 6945: } else {
6946: return $env{'environment.availabletools.'.$tool};
6947: }
6948: }
1.976 raeburn 6949: }
6950:
1.1172.2.9 raeburn 6951: my ($toolstatus,$inststatus,$envkey);
6952: if ($context eq 'requestauthor') {
6953: $envkey = $context;
6954: } else {
6955: $envkey = $context.'.'.$tool;
6956: }
1.976 raeburn 6957:
1.985 raeburn 6958: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6959: ($action ne 'reload')) {
1.1172.2.9 raeburn 6960: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6961: $inststatus = $env{'environment.inststatus'};
6962: } else {
1.1084 raeburn 6963: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6964: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6965: $inststatus = $userenvref->{'inststatus'};
6966: } else {
1.1172.2.9 raeburn 6967: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6968: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6969: $inststatus = $userenv{'inststatus'};
6970: }
1.976 raeburn 6971: }
6972:
6973: if ($toolstatus ne '') {
6974: if ($toolstatus) {
6975: $access = 1;
6976: } else {
6977: $access = 0;
6978: }
6979: return $access;
6980: }
6981:
1.1084 raeburn 6982: my ($is_adv,%domdef);
6983: if (ref($is_advref) eq 'HASH') {
6984: $is_adv = $is_advref->{'is_adv'};
6985: } else {
6986: $is_adv = &is_advanced_user($udom,$uname);
6987: }
6988: if (ref($domdefref) eq 'HASH') {
6989: %domdef = %{$domdefref};
6990: } else {
6991: %domdef = &get_domain_defaults($udom);
6992: }
1.976 raeburn 6993: if (ref($domdef{$tool}) eq 'HASH') {
6994: if ($is_adv) {
6995: if ($domdef{$tool}{'_LC_adv'} ne '') {
6996: if ($domdef{$tool}{'_LC_adv'}) {
6997: $access = 1;
6998: } else {
6999: $access = 0;
7000: }
7001: return $access;
7002: }
7003: }
7004: if ($inststatus ne '') {
7005: my ($hasaccess,$hasnoaccess);
7006: foreach my $affiliation (split(/:/,$inststatus)) {
7007: if ($domdef{$tool}{$affiliation} ne '') {
7008: if ($domdef{$tool}{$affiliation}) {
7009: $hasaccess = 1;
7010: } else {
7011: $hasnoaccess = 1;
7012: }
7013: }
7014: }
7015: if ($hasaccess || $hasnoaccess) {
7016: if ($hasaccess) {
7017: $access = 1;
7018: } elsif ($hasnoaccess) {
7019: $access = 0;
7020: }
7021: return $access;
7022: }
7023: } else {
7024: if ($domdef{$tool}{'default'} ne '') {
7025: if ($domdef{$tool}{'default'}) {
7026: $access = 1;
7027: } elsif ($domdef{$tool}{'default'} == 0) {
7028: $access = 0;
7029: }
7030: return $access;
7031: }
7032: }
7033: } else {
1.1172.2.6 raeburn 7034: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7035: $access = 1;
7036: } else {
7037: $access = 0;
7038: }
1.976 raeburn 7039: return $access;
7040: }
7041: }
7042:
1.1050 raeburn 7043: sub is_course_owner {
7044: my ($cdom,$cnum,$udom,$uname) = @_;
7045: if (($udom eq '') || ($uname eq '')) {
7046: $udom = $env{'user.domain'};
7047: $uname = $env{'user.name'};
7048: }
7049: unless (($udom eq '') || ($uname eq '')) {
7050: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7051: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7052: return 1;
7053: } else {
7054: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7055: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7056: return 1;
7057: }
7058: }
7059: }
7060: }
7061: return;
7062: }
7063:
1.976 raeburn 7064: sub is_advanced_user {
7065: my ($udom,$uname) = @_;
1.1085 raeburn 7066: if ($udom ne '' && $uname ne '') {
7067: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7068: if (wantarray) {
7069: return ($env{'user.adv'},$env{'user.author'});
7070: } else {
7071: return $env{'user.adv'};
7072: }
1.1085 raeburn 7073: }
7074: }
1.976 raeburn 7075: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7076: my %allroles;
1.1128 raeburn 7077: my ($is_adv,$is_author);
1.976 raeburn 7078: foreach my $role (keys(%roleshash)) {
7079: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7080: my $area = '/'.$tdomain.'/'.$trest;
7081: if ($sec ne '') {
7082: $area .= '/'.$sec;
7083: }
7084: if (($area ne '') && ($trole ne '')) {
7085: my $spec=$trole.'.'.$area;
7086: if ($trole =~ /^cr\//) {
7087: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7088: } elsif ($trole ne 'gr') {
7089: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7090: }
1.1128 raeburn 7091: if ($trole eq 'au') {
7092: $is_author = 1;
7093: }
1.976 raeburn 7094: }
7095: }
7096: foreach my $role (keys(%allroles)) {
7097: last if ($is_adv);
7098: foreach my $item (split(/:/,$allroles{$role})) {
7099: if ($item ne '') {
7100: my ($privilege,$restrictions)=split(/&/,$item);
7101: if ($privilege eq 'adv') {
7102: $is_adv = 1;
7103: last;
7104: }
7105: }
7106: }
7107: }
1.1128 raeburn 7108: if (wantarray) {
7109: return ($is_adv,$is_author);
7110: }
1.976 raeburn 7111: return $is_adv;
7112: }
1.798 raeburn 7113:
1.1035 raeburn 7114: sub check_can_request {
1.1036 raeburn 7115: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7116: my $canreq = 0;
7117: my ($types,$typename) = &Apache::loncommon::course_types();
7118: my @options = ('approval','validate','autolimit');
7119: my $optregex = join('|',@options);
7120: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7121: foreach my $type (@{$types}) {
7122: if (&usertools_access($env{'user.name'},
7123: $env{'user.domain'},
7124: $type,undef,'requestcourses')) {
7125: $canreq ++;
1.1036 raeburn 7126: if (ref($request_domains) eq 'HASH') {
7127: push(@{$request_domains->{$type}},$env{'user.domain'});
7128: }
1.1035 raeburn 7129: if ($dom eq $env{'user.domain'}) {
7130: $can_request->{$type} = 1;
7131: }
7132: }
7133: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7134: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7135: if (@curr > 0) {
1.1036 raeburn 7136: foreach my $item (@curr) {
7137: if (ref($request_domains) eq 'HASH') {
7138: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7139: if ($otherdom ne '') {
7140: if (ref($request_domains->{$type}) eq 'ARRAY') {
7141: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7142: push(@{$request_domains->{$type}},$otherdom);
7143: }
7144: } else {
7145: push(@{$request_domains->{$type}},$otherdom);
7146: }
7147: }
7148: }
7149: }
7150: unless($dom eq $env{'user.domain'}) {
7151: $canreq ++;
1.1035 raeburn 7152: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7153: $can_request->{$type} = 1;
7154: }
7155: }
7156: }
7157: }
7158: }
7159: }
7160: return $canreq;
7161: }
7162:
1.341 www 7163: # ---------------------------------------------- Custom access rule evaluation
7164:
7165: sub customaccess {
7166: my ($priv,$uri)=@_;
1.807 albertel 7167: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7168: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7169: $udom = &LONCAPA::clean_domain($udom);
7170: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7171: my $access=0;
1.800 albertel 7172: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7173: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7174: if ($type eq 'user') {
7175: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7176: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7177: if ($tdom) {
7178: if ($tdom ne $env{'user.domain'}) { next; }
7179: }
1.896 albertel 7180: if ($tuname) {
7181: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7182: }
7183: $access=($effect eq 'allow');
7184: last;
7185: }
7186: } else {
7187: if ($role) {
7188: if ($role ne $urole) { next; }
7189: }
7190: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7191: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7192: if ($tdom) {
7193: if ($tdom ne $udom) { next; }
7194: }
7195: if ($tcrs) {
7196: if ($tcrs ne $ucrs) { next; }
7197: }
7198: if ($tsec) {
7199: if ($tsec ne $usec) { next; }
7200: }
7201: $access=($effect eq 'allow');
7202: last;
7203: }
7204: if ($realm eq '' && $role eq '') {
7205: $access=($effect eq 'allow');
7206: }
1.402 bowersj2 7207: }
1.341 www 7208: }
7209: return $access;
7210: }
7211:
1.103 harris41 7212: # ------------------------------------------------- Check for a user privilege
1.12 www 7213:
7214: sub allowed {
1.1172.2.65 raeburn 7215: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7216: my $ver_orguri=$uri;
1.439 www 7217: $uri=&deversion($uri);
1.152 www 7218: my $orguri=$uri;
1.52 www 7219: $uri=&declutter($uri);
1.809 raeburn 7220:
1.810 raeburn 7221: if ($priv eq 'evb') {
7222: # Evade communication block restrictions for specified role in a course
7223: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7224: return $1;
7225: } else {
7226: return;
7227: }
7228: }
7229:
1.620 albertel 7230: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7231: # Free bre access to adm and meta resources
1.775 albertel 7232: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7233: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7234: && ($priv eq 'bre')) {
1.14 www 7235: return 'F';
1.159 www 7236: }
7237:
1.545 banghart 7238: # Free bre access to user's own portfolio contents
1.714 raeburn 7239: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7240: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7241: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7242: my %setters;
7243: my ($startblock,$endblock) =
7244: &Apache::loncommon::blockcheck(\%setters,'port');
7245: if ($startblock && $endblock) {
7246: return 'B';
7247: } else {
7248: return 'F';
7249: }
1.545 banghart 7250: }
7251:
1.762 raeburn 7252: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7253: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7254: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7255: if (exists($env{'request.course.id'})) {
7256: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7257: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7258: if (($domain eq $cdom) && ($name eq $cnum)) {
7259: my $courseprivid=$env{'request.course.id'};
7260: $courseprivid=~s/\_/\//;
7261: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7262: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7263: return $1;
1.762 raeburn 7264: } else {
7265: if ($env{'request.course.sec'}) {
7266: $courseprivid.='/'.$env{'request.course.sec'};
7267: }
7268: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7269: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7270: return $2;
7271: }
1.714 raeburn 7272: }
7273: }
7274: }
7275: }
7276:
1.159 www 7277: # Free bre to public access
7278:
7279: if ($priv eq 'bre') {
1.238 www 7280: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7281: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7282: return 'F';
7283: }
1.238 www 7284: if ($copyright eq 'priv') {
7285: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7286: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7287: return '';
7288: }
7289: }
7290: if ($copyright eq 'domain') {
7291: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7292: unless (($env{'user.domain'} eq $1) ||
7293: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7294: return '';
7295: }
1.262 matthew 7296: }
1.620 albertel 7297: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7298: # Library role, so allow browsing of resources in this domain.
7299: return 'F';
1.238 www 7300: }
1.341 www 7301: if ($copyright eq 'custom') {
7302: unless (&customaccess($priv,$uri)) { return ''; }
7303: }
1.14 www 7304: }
1.264 matthew 7305: # Domain coordinator is trying to create a course
1.620 albertel 7306: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7307: # uri is the requested domain in this case.
7308: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7309: # a role of dc for the domain in question.
1.620 albertel 7310: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7311: }
1.29 www 7312:
1.52 www 7313: my $thisallowed='';
7314: my $statecond=0;
7315: my $courseprivid='';
7316:
1.1039 raeburn 7317: my $ownaccess;
1.1043 raeburn 7318: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7319: if (($priv eq 'bro') && ($env{'user.author'})) {
7320: if ($uri eq '') {
7321: $ownaccess = 1;
7322: } else {
7323: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7324: my $udom = $env{'user.domain'};
7325: my $uname = $env{'user.name'};
7326: if ($uri =~ m{^\Q$udom\E/?$}) {
7327: $ownaccess = 1;
1.1040 raeburn 7328: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7329: unless ($uri =~ m{\.\./}) {
7330: $ownaccess = 1;
7331: }
7332: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7333: my $now = time;
7334: if ($uri =~ m{^([^/]+)/?$}) {
7335: my $adom = $1;
7336: foreach my $key (keys(%env)) {
1.1042 raeburn 7337: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7338: my ($start,$end) = split('.',$env{$key});
7339: if (($now >= $start) && (!$end || $end < $now)) {
7340: $ownaccess = 1;
7341: last;
7342: }
7343: }
7344: }
7345: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7346: my $adom = $1;
7347: my $aname = $2;
1.1042 raeburn 7348: foreach my $role ('ca','aa') {
7349: if ($env{"user.role.$role./$adom/$aname"}) {
7350: my ($start,$end) =
7351: split('.',$env{"user.role.$role./$adom/$aname"});
7352: if (($now >= $start) && (!$end || $end < $now)) {
7353: $ownaccess = 1;
7354: last;
7355: }
1.1039 raeburn 7356: }
7357: }
7358: }
7359: }
7360: }
7361: }
7362: }
7363:
1.52 www 7364: # Course
7365:
1.620 albertel 7366: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7367: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7368: $thisallowed.=$1;
7369: }
1.52 www 7370: }
1.29 www 7371:
1.52 www 7372: # Domain
7373:
1.620 albertel 7374: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7375: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7376: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7377: $thisallowed.=$1;
7378: }
1.12 www 7379: }
1.52 www 7380:
1.1141 raeburn 7381: # User who is not author or co-author might still be able to edit
7382: # resource of an author in the domain (e.g., if Domain Coordinator).
7383: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7384: (&allowed('mdc',$env{'request.course.id'}))) {
7385: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7386: $thisallowed.=$1;
7387: }
7388: }
7389:
1.52 www 7390: # Course: uri itself is a course
1.66 www 7391: my $courseuri=$uri;
7392: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7393: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7394:
1.620 albertel 7395: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7396: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7397: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7398: $thisallowed.=$1;
7399: }
1.12 www 7400: }
1.29 www 7401:
1.665 albertel 7402: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7403: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7404: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7405: $thisallowed='';
1.671 raeburn 7406: my ($match)=&is_on_map($uri);
7407: if ($match) {
7408: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7409: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7410: my $value = $1;
7411: if ($noblockcheck) {
7412: $thisallowed.=$value;
1.1162 raeburn 7413: } else {
1.1172.2.65 raeburn 7414: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7415: if (@blockers > 0) {
7416: $thisallowed = 'B';
7417: } else {
7418: $thisallowed.=$value;
7419: }
1.1162 raeburn 7420: }
1.671 raeburn 7421: }
7422: } else {
1.705 albertel 7423: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7424: if ($refuri) {
7425: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7426: $thisallowed='F';
1.671 raeburn 7427: } else {
7428: $refuri=&declutter($refuri);
7429: my ($match) = &is_on_map($refuri);
7430: if ($match) {
1.1172.2.65 raeburn 7431: if ($noblockcheck) {
1.1162 raeburn 7432: $thisallowed='F';
1.1172.2.65 raeburn 7433: } else {
7434: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7435: if (@blockers > 0) {
7436: $thisallowed = 'B';
7437: } else {
7438: $thisallowed='F';
7439: }
1.1162 raeburn 7440: }
1.671 raeburn 7441: }
1.669 raeburn 7442: }
1.671 raeburn 7443: }
7444: }
1.314 www 7445: }
1.492 albertel 7446:
1.766 albertel 7447: if ($priv eq 'bre'
7448: && $thisallowed ne 'F'
7449: && $thisallowed ne '2'
7450: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7451: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7452: }
7453:
1.52 www 7454: # Full access at system, domain or course-wide level? Exit.
1.29 www 7455: if ($thisallowed=~/F/) {
7456: return 'F';
7457: }
7458:
1.52 www 7459: # If this is generating or modifying users, exit with special codes
1.29 www 7460:
1.643 www 7461: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7462: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7463: my ($audom,$auname)=split('/',$uri);
1.643 www 7464: # no author name given, so this just checks on the general right to make a co-author in this domain
7465: unless ($auname) { return $thisallowed; }
7466: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7467: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7468: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7469: ($audom ne $env{'request.role.domain'}))) { return ''; }
7470: }
1.52 www 7471: return $thisallowed;
7472: }
7473: #
1.103 harris41 7474: # Gathered so far: system, domain and course wide privileges
1.52 www 7475: #
7476: # Course: See if uri or referer is an individual resource that is part of
7477: # the course
7478:
1.620 albertel 7479: if ($env{'request.course.id'}) {
1.232 www 7480:
1.620 albertel 7481: $courseprivid=$env{'request.course.id'};
7482: if ($env{'request.course.sec'}) {
7483: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7484: }
7485: $courseprivid=~s/\_/\//;
7486: my $checkreferer=1;
1.232 www 7487: my ($match,$cond)=&is_on_map($uri);
7488: if ($match) {
7489: $statecond=$cond;
1.620 albertel 7490: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7491: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7492: my $value = $1;
7493: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7494: if ($noblockcheck) {
1.1162 raeburn 7495: $thisallowed.=$value;
1.1172.2.65 raeburn 7496: } else {
7497: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7498: if (@blockers > 0) {
7499: $thisallowed = 'B';
7500: } else {
7501: $thisallowed.=$value;
7502: }
1.1162 raeburn 7503: }
7504: } else {
7505: $thisallowed.=$value;
7506: }
1.52 www 7507: $checkreferer=0;
7508: }
1.29 www 7509: }
1.83 www 7510:
1.148 www 7511: if ($checkreferer) {
1.620 albertel 7512: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7513: unless ($refuri) {
1.800 albertel 7514: foreach my $key (keys(%env)) {
7515: if ($key=~/^httpref\..*\*/) {
7516: my $pattern=$key;
1.156 www 7517: $pattern=~s/^httpref\.\/res\///;
1.148 www 7518: $pattern=~s/\*/\[\^\/\]\+/g;
7519: $pattern=~s/\//\\\//g;
1.152 www 7520: if ($orguri=~/$pattern/) {
1.800 albertel 7521: $refuri=$env{$key};
1.148 www 7522: }
7523: }
1.191 harris41 7524: }
1.148 www 7525: }
1.232 www 7526:
1.148 www 7527: if ($refuri) {
1.152 www 7528: $refuri=&declutter($refuri);
1.232 www 7529: my ($match,$cond)=&is_on_map($refuri);
7530: if ($match) {
7531: my $refstatecond=$cond;
1.620 albertel 7532: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7533: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7534: my $value = $1;
7535: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7536: if ($noblockcheck) {
1.1162 raeburn 7537: $thisallowed.=$value;
1.1172.2.65 raeburn 7538: } else {
7539: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7540: if (@blockers > 0) {
7541: $thisallowed = 'B';
7542: } else {
7543: $thisallowed.=$value;
7544: }
1.1162 raeburn 7545: }
7546: } else {
7547: $thisallowed.=$value;
7548: }
1.53 www 7549: $uri=$refuri;
7550: $statecond=$refstatecond;
1.52 www 7551: }
7552: }
1.148 www 7553: }
1.29 www 7554: }
1.52 www 7555: }
1.29 www 7556:
1.52 www 7557: #
1.103 harris41 7558: # Gathered now: all privileges that could apply, and condition number
1.52 www 7559: #
7560: #
7561: # Full or no access?
7562: #
1.29 www 7563:
1.52 www 7564: if ($thisallowed=~/F/) {
7565: return 'F';
7566: }
1.29 www 7567:
1.52 www 7568: unless ($thisallowed) {
7569: return '';
7570: }
1.29 www 7571:
1.52 www 7572: # Restrictions exist, deal with them
7573: #
7574: # C:according to course preferences
7575: # R:according to resource settings
7576: # L:unless locked
7577: # X:according to user session state
7578: #
7579:
7580: # Possibly locked functionality, check all courses
1.54 www 7581: # Locks might take effect only after 10 minutes cache expiration for other
7582: # courses, and 2 minutes for current course
1.52 www 7583:
7584: my $envkey;
7585: if ($thisallowed=~/L/) {
1.1000 raeburn 7586: foreach $envkey (keys(%env)) {
1.54 www 7587: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7588: my $courseid=$2;
7589: my $roleid=$1.'.'.$2;
1.92 www 7590: $courseid=~s/^\///;
1.54 www 7591: my $expiretime=600;
1.620 albertel 7592: if ($env{'request.role'} eq $roleid) {
1.54 www 7593: $expiretime=120;
7594: }
7595: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7596: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7597: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7598: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7599: }
1.620 albertel 7600: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7601: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7602: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7603: &log($env{'user.domain'},$env{'user.name'},
7604: $env{'user.home'},
1.57 www 7605: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7606: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7607: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7608: return '';
7609: }
7610: }
1.620 albertel 7611: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7612: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7613: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7614: &log($env{'user.domain'},$env{'user.name'},
7615: $env{'user.home'},
1.57 www 7616: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7617: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7618: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7619: return '';
7620: }
7621: }
7622: }
1.29 www 7623: }
1.52 www 7624: }
7625:
7626: #
7627: # Rest of the restrictions depend on selected course
7628: #
7629:
1.620 albertel 7630: unless ($env{'request.course.id'}) {
1.766 albertel 7631: if ($thisallowed eq 'A') {
7632: return 'A';
1.814 raeburn 7633: } elsif ($thisallowed eq 'B') {
7634: return 'B';
1.766 albertel 7635: } else {
7636: return '1';
7637: }
1.52 www 7638: }
1.29 www 7639:
1.52 www 7640: #
7641: # Now user is definitely in a course
7642: #
1.53 www 7643:
7644:
7645: # Course preferences
7646:
7647: if ($thisallowed=~/C/) {
1.620 albertel 7648: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7649: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7650: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7651: =~/\Q$rolecode\E/) {
1.1103 raeburn 7652: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7653: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7654: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7655: $env{'request.course.id'});
7656: }
1.237 www 7657: return '';
7658: }
7659:
1.620 albertel 7660: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7661: =~/\Q$unamedom\E/) {
1.1103 raeburn 7662: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7663: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7664: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7665: $env{'request.course.id'});
7666: }
1.54 www 7667: return '';
7668: }
1.53 www 7669: }
7670:
7671: # Resource preferences
7672:
7673: if ($thisallowed=~/R/) {
1.620 albertel 7674: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7675: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7676: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7677: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7678: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7679: }
7680: return '';
1.54 www 7681: }
1.53 www 7682: }
1.30 www 7683:
1.246 www 7684: # Restricted by state or randomout?
1.30 www 7685:
1.52 www 7686: if ($thisallowed=~/X/) {
1.620 albertel 7687: if ($env{'acc.randomout'}) {
1.579 albertel 7688: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7689: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7690: return '';
7691: }
1.247 www 7692: }
7693: if (&condval($statecond)) {
1.52 www 7694: return '2';
7695: } else {
7696: return '';
7697: }
7698: }
1.30 www 7699:
1.766 albertel 7700: if ($thisallowed eq 'A') {
7701: return 'A';
1.814 raeburn 7702: } elsif ($thisallowed eq 'B') {
7703: return 'B';
1.766 albertel 7704: }
1.52 www 7705: return 'F';
1.232 www 7706: }
1.1162 raeburn 7707:
1.1172.2.13 raeburn 7708: # ------------------------------------------- Check construction space access
7709:
7710: sub constructaccess {
7711: my ($url,$setpriv)=@_;
7712:
7713: # We do not allow editing of previous versions of files
7714: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7715:
7716: # Get username and domain from URL
7717: my ($ownername,$ownerdomain,$ownerhome);
7718:
7719: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7720: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7721:
7722: # The URL does not really point to any authorspace, forget it
7723: unless (($ownername) && ($ownerdomain)) { return ''; }
7724:
7725: # Now we need to see if the user has access to the authorspace of
7726: # $ownername at $ownerdomain
7727:
7728: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7729: # Real author for this?
7730: $ownerhome = $env{'user.home'};
7731: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7732: return ($ownername,$ownerdomain,$ownerhome);
7733: }
7734: } else {
7735: # Co-author for this?
7736: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7737: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7738: $ownerhome = &homeserver($ownername,$ownerdomain);
7739: return ($ownername,$ownerdomain,$ownerhome);
7740: }
7741: }
7742:
7743: # We don't have any access right now. If we are not possibly going to do anything about this,
7744: # we might as well leave
7745: unless ($setpriv) { return ''; }
7746:
7747: # Backdoor access?
7748: my $allowed=&allowed('eco',$ownerdomain);
7749: # Nope
7750: unless ($allowed) { return ''; }
7751: # Looks like we may have access, but could be locked by the owner of the construction space
7752: if ($allowed eq 'U') {
7753: my %blocked=&get('environment',['domcoord.author'],
7754: $ownerdomain,$ownername);
7755: # Is blocked by owner
7756: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7757: }
7758: if (($allowed eq 'F') || ($allowed eq 'U')) {
7759: # Grant temporary access
7760: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7761: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7762: if (!$update) { $update = $then; }
7763: my $refresh=$env{'user.refresh.time'};
7764: if (!$refresh) { $refresh = $update; }
7765: my $now = time;
7766: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7767: $now,'ca','constructaccess');
7768: $ownerhome = &homeserver($ownername,$ownerdomain);
7769: return($ownername,$ownerdomain,$ownerhome);
7770: }
7771: # No business here
7772: return '';
7773: }
7774:
1.1172.2.66 raeburn 7775: # ----------------------------------------------------------- Content Blocking
7776:
7777: {
7778: # Caches for faster Course Contents display where content blocking
7779: # is in operation (i.e., interval param set) for timed quiz.
7780: #
7781: # User for whom data are being temporarily cached.
7782: my $cacheduser='';
7783: # Cached blockers for this user (a hash of blocking items).
7784: my %cachedblockers=();
7785: # When the data were last cached.
7786: my $cachedlast='';
7787:
7788: sub load_all_blockers {
7789: my ($uname,$udom,$blocks)=@_;
7790: if (($uname ne '') && ($udom ne '')) {
7791: if (($cacheduser eq $uname.':'.$udom) &&
7792: (abs($cachedlast-time)<5)) {
7793: return;
7794: }
7795: }
7796: $cachedlast=time;
7797: $cacheduser=$uname.':'.$udom;
7798: %cachedblockers = &get_commblock_resources($blocks);
7799: }
7800:
1.1162 raeburn 7801: sub get_comm_blocks {
7802: my ($cdom,$cnum) = @_;
7803: if ($cdom eq '' || $cnum eq '') {
7804: return unless ($env{'request.course.id'});
7805: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7806: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7807: }
7808: my %commblocks;
7809: my $hashid=$cdom.'_'.$cnum;
7810: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7811: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7812: %commblocks = %{$blocksref};
7813: } else {
7814: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7815: my $cachetime = 600;
7816: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7817: }
7818: return %commblocks;
7819: }
7820:
1.1172.2.66 raeburn 7821: sub get_commblock_resources {
7822: my ($blocks) = @_;
7823: my %blockers = ();
7824: return %blockers unless ($env{'request.course.id'});
7825: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7826: my %commblocks;
7827: if (ref($blocks) eq 'HASH') {
7828: %commblocks = %{$blocks};
7829: } else {
7830: %commblocks = &get_comm_blocks();
7831: }
1.1172.2.66 raeburn 7832: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7833: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7834: return %blockers unless (ref($navmap));
7835: my $now = time;
1.1162 raeburn 7836: foreach my $block (keys(%commblocks)) {
7837: if ($block =~ /^(\d+)____(\d+)$/) {
7838: my ($start,$end) = ($1,$2);
7839: if ($start <= $now && $end >= $now) {
7840: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7841: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7842: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7843: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7844: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7845: }
7846: }
7847: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7848: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7849: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7850: }
7851: }
7852: }
7853: }
7854: }
7855: } elsif ($block =~ /^firstaccess____(.+)$/) {
7856: my $item = $1;
1.1163 raeburn 7857: my @to_test;
1.1162 raeburn 7858: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7859: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7860: my @interval;
7861: my $type = 'map';
7862: if ($item eq 'course') {
7863: $type = 'course';
7864: @interval=&EXT("resource.0.interval");
7865: } else {
7866: if ($item =~ /___\d+___/) {
7867: $type = 'resource';
7868: @interval=&EXT("resource.0.interval",$item);
7869: if (ref($navmap)) {
7870: my $res = $navmap->getBySymb($item);
7871: push(@to_test,$res);
7872: }
1.1162 raeburn 7873: } else {
1.1172.2.66 raeburn 7874: my $mapsymb = &symbread($item,1);
7875: if ($mapsymb) {
7876: if (ref($navmap)) {
7877: my $mapres = $navmap->getBySymb($mapsymb);
7878: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7879: foreach my $res (@to_test) {
7880: my $symb = $res->symb();
7881: next if ($symb eq $mapsymb);
7882: if ($symb ne '') {
7883: @interval=&EXT("resource.0.interval",$symb);
7884: if ($interval[1] eq 'map') {
7885: last;
1.1162 raeburn 7886: }
7887: }
7888: }
7889: }
7890: }
7891: }
1.1172.2.66 raeburn 7892: }
7893: if ($interval[0] =~ /^\d+$/) {
7894: my $first_access;
7895: if ($type eq 'resource') {
7896: $first_access=&get_first_access($interval[1],$item);
7897: } elsif ($type eq 'map') {
7898: $first_access=&get_first_access($interval[1],undef,$item);
7899: } else {
7900: $first_access=&get_first_access($interval[1]);
7901: }
7902: if ($first_access) {
7903: my $timesup = $first_access+$interval[0];
7904: if ($timesup > $now) {
7905: my $activeblock;
7906: foreach my $res (@to_test) {
7907: if ($res->answerable()) {
7908: $activeblock = 1;
7909: last;
7910: }
7911: }
7912: if ($activeblock) {
7913: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7914: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7915: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7916: }
7917: }
7918: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7919: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7920: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7921: }
1.1162 raeburn 7922: }
7923: }
7924: }
7925: }
7926: }
7927: }
7928: }
7929: }
7930: }
1.1172.2.66 raeburn 7931: return %blockers;
1.1162 raeburn 7932: }
7933:
1.1172.2.66 raeburn 7934: sub has_comm_blocking {
7935: my ($priv,$symb,$uri,$blocks) = @_;
7936: my @blockers;
7937: return unless ($env{'request.course.id'});
7938: return unless ($priv eq 'bre');
7939: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7940: return if ($env{'request.state'} eq 'construct');
7941: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7942: return unless (keys(%cachedblockers) > 0);
7943: my (%possibles,@symbs);
7944: if (!$symb) {
7945: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7946: }
1.1172.2.66 raeburn 7947: if ($symb) {
7948: @symbs = ($symb);
7949: } elsif (keys(%possibles)) {
7950: @symbs = keys(%possibles);
7951: }
7952: my $noblock;
7953: foreach my $symb (@symbs) {
7954: last if ($noblock);
7955: my ($map,$resid,$resurl)=&decode_symb($symb);
7956: foreach my $block (keys(%cachedblockers)) {
7957: if ($block =~ /^firstaccess____(.+)$/) {
7958: my $item = $1;
7959: if (($item eq $map) || ($item eq $symb)) {
7960: $noblock = 1;
7961: last;
7962: }
1.1162 raeburn 7963: }
1.1172.2.66 raeburn 7964: if (ref($cachedblockers{$block}) eq 'HASH') {
7965: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7966: if ($cachedblockers{$block}{'resources'}{$symb}) {
7967: unless (grep(/^\Q$block\E$/,@blockers)) {
7968: push(@blockers,$block);
7969: }
7970: }
7971: }
7972: }
7973: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7974: if ($cachedblockers{$block}{'maps'}{$map}) {
7975: unless (grep(/^\Q$block\E$/,@blockers)) {
7976: push(@blockers,$block);
7977: }
7978: }
1.1162 raeburn 7979: }
7980: }
7981: }
1.1172.2.66 raeburn 7982: return if ($noblock);
7983: return @blockers;
7984: }
1.1162 raeburn 7985: }
7986:
1.1172.2.66 raeburn 7987: # -------------------------------- Deversion and split uri into path an filename
7988:
1.1133 foxr 7989: #
1.1172.2.66 raeburn 7990: # Removes the version from a URI and
1.1133 foxr 7991: # splits it in to its filename and path to the filename.
7992: # Seems like File::Basename could have done this more clearly.
7993: # Parameters:
7994: # $uri - input URI
7995: # Returns:
7996: # Two element list consisting of
7997: # $pathname - the URI up to and excluding the trailing /
7998: # $filename - The part of the URI following the last /
7999: # NOTE:
8000: # Another realization of this is simply:
8001: # use File::Basename;
8002: # ...
8003: # $uri = shift;
8004: # $filename = basename($uri);
8005: # $path = dirname($uri);
8006: # return ($filename, $path);
8007: #
8008: # The implementation below is probably faster however.
8009: #
1.710 albertel 8010: sub split_uri_for_cond {
8011: my $uri=&deversion(&declutter(shift));
8012: my @uriparts=split(/\//,$uri);
8013: my $filename=pop(@uriparts);
8014: my $pathname=join('/',@uriparts);
8015: return ($pathname,$filename);
8016: }
1.232 www 8017: # --------------------------------------------------- Is a resource on the map?
8018:
8019: sub is_on_map {
1.710 albertel 8020: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8021: #Trying to find the conditional for the file
1.620 albertel 8022: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8023: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8024: if ($match) {
1.289 bowersj2 8025: return (1,$1);
8026: } else {
1.434 www 8027: return (0,0);
1.289 bowersj2 8028: }
1.12 www 8029: }
8030:
1.427 www 8031: # --------------------------------------------------------- Get symb from alias
8032:
8033: sub get_symb_from_alias {
8034: my $symb=shift;
8035: my ($map,$resid,$url)=&decode_symb($symb);
8036: # Already is a symb
8037: if ($url) { return $symb; }
8038: # Must be an alias
8039: my $aliassymb='';
8040: my %bighash;
1.620 albertel 8041: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8042: &GDBM_READER(),0640)) {
8043: my $rid=$bighash{'mapalias_'.$symb};
8044: if ($rid) {
8045: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8046: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8047: $resid,$bighash{'src_'.$rid});
1.427 www 8048: }
8049: untie %bighash;
8050: }
8051: return $aliassymb;
8052: }
8053:
1.12 www 8054: # ----------------------------------------------------------------- Define Role
8055:
8056: sub definerole {
8057: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8058: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8059: foreach my $role (split(':',$sysrole)) {
8060: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8061: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8062: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8063: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8064: return "refused:s:$crole&$cqual";
8065: }
8066: }
1.191 harris41 8067: }
1.800 albertel 8068: foreach my $role (split(':',$domrole)) {
8069: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8070: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8071: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8072: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8073: return "refused:d:$crole&$cqual";
8074: }
8075: }
1.191 harris41 8076: }
1.800 albertel 8077: foreach my $role (split(':',$courole)) {
8078: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8079: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8080: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8081: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8082: return "refused:c:$crole&$cqual";
8083: }
8084: }
1.191 harris41 8085: }
1.1172.2.84 raeburn 8086: my $uhome;
8087: if (($uname ne '') && ($udom ne '')) {
8088: $uhome = &homeserver($uname,$udom);
8089: return $uhome if ($uhome eq 'no_host');
8090: } else {
8091: $uname = $env{'user.name'};
8092: $udom = $env{'user.domain'};
8093: $uhome = $env{'user.home'};
8094: }
1.620 albertel 8095: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8096: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8097: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8098: return reply($command,$uhome);
1.12 www 8099: } else {
8100: return 'refused';
8101: }
1.105 harris41 8102: }
8103:
8104: # ---------------- Make a metadata query against the network of library servers
8105:
8106: sub metadata_query {
1.1172.2.33 raeburn 8107: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8108: my %rhash;
1.845 albertel 8109: my %libserv = &all_library();
1.244 matthew 8110: my @server_list = (defined($server_array) ? @$server_array
8111: : keys(%libserv) );
8112: for my $server (@server_list) {
1.1172.2.33 raeburn 8113: my $domains = '';
8114: if (ref($domains_hash) eq 'HASH') {
8115: $domains = $domains_hash->{$server};
8116: }
1.118 harris41 8117: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8118: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8119: $rhash{$server}=$reply;
8120: }
8121: else {
8122: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8123: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8124: $server);
8125: $rhash{$server}=$reply;
8126: }
1.112 harris41 8127: }
1.118 harris41 8128: return \%rhash;
1.240 www 8129: }
8130:
8131: # ----------------------------------------- Send log queries and wait for reply
8132:
8133: sub log_query {
8134: my ($uname,$udom,$query,%filters)=@_;
8135: my $uhome=&homeserver($uname,$udom);
8136: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8137: my $uhost=&hostname($uhome);
1.800 albertel 8138: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8139: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8140: $uhome);
1.479 albertel 8141: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8142: return get_query_reply($queryid);
8143: }
8144:
1.818 raeburn 8145: # -------------------------- Update MySQL table for portfolio file
8146:
8147: sub update_portfolio_table {
1.821 raeburn 8148: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8149: if ($group ne '') {
8150: $file_name =~s /^\Q$group\E//;
8151: }
1.818 raeburn 8152: my $homeserver = &homeserver($uname,$udom);
8153: my $queryid=
1.821 raeburn 8154: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8155: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8156: my $reply = &get_query_reply($queryid);
8157: return $reply;
8158: }
8159:
1.899 raeburn 8160: # -------------------------- Update MySQL allusers table
8161:
8162: sub update_allusers_table {
8163: my ($uname,$udom,$names) = @_;
8164: my $homeserver = &homeserver($uname,$udom);
8165: my $queryid=
8166: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8167: 'lastname='.&escape($names->{'lastname'}).'%%'.
8168: 'firstname='.&escape($names->{'firstname'}).'%%'.
8169: 'middlename='.&escape($names->{'middlename'}).'%%'.
8170: 'generation='.&escape($names->{'generation'}).'%%'.
8171: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8172: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8173: return;
1.899 raeburn 8174: }
8175:
1.508 raeburn 8176: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8177:
8178: sub fetch_enrollment_query {
1.511 raeburn 8179: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8180: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8181: my $maxtries = 1;
1.508 raeburn 8182: if ($context eq 'automated') {
8183: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8184: $sleep = 2;
8185: $loopmax = 100;
1.547 raeburn 8186: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8187: } else {
8188: $homeserver = &homeserver($cnum,$dom);
8189: }
1.838 albertel 8190: my $host=&hostname($homeserver);
1.506 raeburn 8191: my $cmd = '';
1.1000 raeburn 8192: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8193: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8194: }
8195: $cmd =~ s/%%$//;
8196: $cmd = &escape($cmd);
8197: my $query = 'fetchenrollment';
1.620 albertel 8198: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8199: unless ($queryid=~/^\Q$host\E\_/) {
8200: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8201: return 'error: '.$queryid;
8202: }
1.1172.2.93 raeburn 8203: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8204: my $tries = 1;
8205: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8206: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8207: $tries ++;
8208: }
1.526 raeburn 8209: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8210: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8211: } else {
1.901 albertel 8212: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8213: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8214: foreach my $line (@responses) {
8215: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8216: $$replyref{$key} = $value;
8217: }
8218: } else {
1.1117 foxr 8219: my $pathname = LONCAPA::tempdir();
1.800 albertel 8220: foreach my $line (@responses) {
8221: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8222: $$replyref{$key} = $value;
8223: if ($value > 0) {
1.800 albertel 8224: foreach my $item (@{$$affiliatesref{$key}}) {
8225: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8226: my $destname = $pathname.'/'.$filename;
8227: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8228: if ($xml_classlist =~ /^error/) {
8229: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8230: } else {
1.1172.2.96 raeburn 8231: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8232: print FILE &unescape($xml_classlist);
8233: close(FILE);
1.526 raeburn 8234: } else {
8235: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8236: }
8237: }
8238: }
8239: }
8240: }
8241: }
8242: return 'ok';
8243: }
8244: return 'error';
8245: }
8246:
1.242 www 8247: sub get_query_reply {
1.1172.2.79 raeburn 8248: my ($queryid,$sleep,$loopmax) = @_;
8249: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8250: $sleep = 0.2;
8251: }
8252: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8253: $loopmax = 100;
8254: }
1.1117 foxr 8255: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8256: my $reply='';
1.1172.2.79 raeburn 8257: for (1..$loopmax) {
8258: sleep($sleep);
1.240 www 8259: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8260: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8261: $reply = join('',<$fh>);
8262: close($fh);
1.240 www 8263: } else { return 'error: reply_file_error'; }
1.242 www 8264: return &unescape($reply);
8265: }
1.240 www 8266: }
1.242 www 8267: return 'timeout:'.$queryid;
1.240 www 8268: }
8269:
8270: sub courselog_query {
1.241 www 8271: #
8272: # possible filters:
8273: # url: url or symb
8274: # username
8275: # domain
8276: # action: view, submit, grade
8277: # start: timestamp
8278: # end: timestamp
8279: #
1.240 www 8280: my (%filters)=@_;
1.620 albertel 8281: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8282: if ($filters{'url'}) {
8283: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8284: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8285: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8286: }
1.620 albertel 8287: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8288: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8289: return &log_query($cname,$cdom,'courselog',%filters);
8290: }
8291:
8292: sub userlog_query {
1.858 raeburn 8293: #
8294: # possible filters:
8295: # action: log check role
8296: # start: timestamp
8297: # end: timestamp
8298: #
1.240 www 8299: my ($uname,$udom,%filters)=@_;
8300: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8301: }
8302:
1.506 raeburn 8303: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8304:
8305: sub auto_run {
1.508 raeburn 8306: my ($cnum,$cdom) = @_;
1.876 raeburn 8307: my $response = 0;
8308: my $settings;
8309: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8310: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8311: $settings = $domconfig{'autoenroll'};
8312: if ($settings->{'run'} eq '1') {
8313: $response = 1;
8314: }
8315: } else {
1.934 raeburn 8316: my $homeserver;
8317: if (&is_course($cdom,$cnum)) {
8318: $homeserver = &homeserver($cnum,$cdom);
8319: } else {
8320: $homeserver = &domain($cdom,'primary');
8321: }
8322: if ($homeserver ne 'no_host') {
8323: $response = &reply('autorun:'.$cdom,$homeserver);
8324: }
1.876 raeburn 8325: }
1.506 raeburn 8326: return $response;
8327: }
1.776 albertel 8328:
1.506 raeburn 8329: sub auto_get_sections {
1.508 raeburn 8330: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8331: my $homeserver;
8332: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8333: $homeserver = &homeserver($cnum,$cdom);
8334: }
8335: if (!defined($homeserver)) {
8336: if ($cdom =~ /^$match_domain$/) {
8337: $homeserver = &domain($cdom,'primary');
8338: }
8339: }
8340: my @secs;
8341: if (defined($homeserver)) {
8342: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8343: unless ($response eq 'refused') {
8344: @secs = split(/:/,$response);
8345: }
1.506 raeburn 8346: }
8347: return @secs;
8348: }
1.776 albertel 8349:
1.506 raeburn 8350: sub auto_new_course {
1.1099 raeburn 8351: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8352: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8353: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8354: return $response;
8355: }
1.776 albertel 8356:
1.506 raeburn 8357: sub auto_validate_courseID {
1.508 raeburn 8358: my ($cnum,$cdom,$inst_course_id) = @_;
8359: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8360: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8361: return $response;
8362: }
1.776 albertel 8363:
1.1007 raeburn 8364: sub auto_validate_instcode {
1.1020 raeburn 8365: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8366: my ($homeserver,$response);
8367: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8368: $homeserver = &homeserver($cnum,$cdom);
8369: }
8370: if (!defined($homeserver)) {
8371: if ($cdom =~ /^$match_domain$/) {
8372: $homeserver = &domain($cdom,'primary');
8373: }
8374: }
1.1065 raeburn 8375: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8376: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 8377: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8378: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8379: }
8380:
1.506 raeburn 8381: sub auto_create_password {
1.873 raeburn 8382: my ($cnum,$cdom,$authparam,$udom) = @_;
8383: my ($homeserver,$response);
1.506 raeburn 8384: my $create_passwd = 0;
8385: my $authchk = '';
1.873 raeburn 8386: if ($udom =~ /^$match_domain$/) {
8387: $homeserver = &domain($udom,'primary');
8388: }
8389: if ($homeserver eq '') {
8390: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8391: $homeserver = &homeserver($cnum,$cdom);
8392: }
8393: }
8394: if ($homeserver eq '') {
8395: $authchk = 'nodomain';
1.506 raeburn 8396: } else {
1.873 raeburn 8397: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8398: if ($response eq 'refused') {
8399: $authchk = 'refused';
8400: } else {
1.901 albertel 8401: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8402: }
1.506 raeburn 8403: }
8404: return ($authparam,$create_passwd,$authchk);
8405: }
8406:
1.706 raeburn 8407: sub auto_photo_permission {
8408: my ($cnum,$cdom,$students) = @_;
8409: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8410: my ($outcome,$perm_reqd,$conditions) =
8411: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8412: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8413: return (undef,undef);
8414: }
1.706 raeburn 8415: return ($outcome,$perm_reqd,$conditions);
8416: }
8417:
8418: sub auto_checkphotos {
8419: my ($uname,$udom,$pid) = @_;
8420: my $homeserver = &homeserver($uname,$udom);
8421: my ($result,$resulttype);
8422: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8423: &escape($uname).':'.&escape($pid),
8424: $homeserver));
1.709 albertel 8425: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8426: return (undef,undef);
8427: }
1.706 raeburn 8428: if ($outcome) {
8429: ($result,$resulttype) = split(/:/,$outcome);
8430: }
8431: return ($result,$resulttype);
8432: }
8433:
8434: sub auto_photochoice {
8435: my ($cnum,$cdom) = @_;
8436: my $homeserver = &homeserver($cnum,$cdom);
8437: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8438: &escape($cdom),
8439: $homeserver)));
1.709 albertel 8440: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8441: return (undef,undef);
8442: }
1.706 raeburn 8443: return ($update,$comment);
8444: }
8445:
8446: sub auto_photoupdate {
8447: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8448: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8449: my $host=&hostname($homeserver);
1.706 raeburn 8450: my $cmd = '';
8451: my $maxtries = 1;
1.800 albertel 8452: foreach my $affiliate (keys(%{$affiliatesref})) {
8453: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8454: }
8455: $cmd =~ s/%%$//;
8456: $cmd = &escape($cmd);
8457: my $query = 'institutionalphotos';
8458: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8459: unless ($queryid=~/^\Q$host\E\_/) {
8460: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8461: return 'error: '.$queryid;
8462: }
8463: my $reply = &get_query_reply($queryid);
8464: my $tries = 1;
8465: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8466: $reply = &get_query_reply($queryid);
8467: $tries ++;
8468: }
8469: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8470: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8471: } else {
8472: my @responses = split(/:/,$reply);
8473: my $outcome = shift(@responses);
8474: foreach my $item (@responses) {
8475: my ($key,$value) = split(/=/,$item);
8476: $$photo{$key} = $value;
8477: }
8478: return $outcome;
8479: }
8480: return 'error';
8481: }
8482:
1.521 raeburn 8483: sub auto_instcode_format {
1.793 albertel 8484: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8485: $cat_order) = @_;
1.521 raeburn 8486: my $courses = '';
1.772 raeburn 8487: my @homeservers;
1.521 raeburn 8488: if ($caller eq 'global') {
1.841 albertel 8489: my %servers = &get_servers($codedom,'library');
8490: foreach my $tryserver (keys(%servers)) {
8491: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8492: push(@homeservers,$tryserver);
8493: }
1.584 raeburn 8494: }
1.1022 raeburn 8495: } elsif ($caller eq 'requests') {
8496: if ($codedom =~ /^$match_domain$/) {
8497: my $chome = &domain($codedom,'primary');
8498: unless ($chome eq 'no_host') {
8499: push(@homeservers,$chome);
8500: }
8501: }
1.521 raeburn 8502: } else {
1.772 raeburn 8503: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8504: }
1.793 albertel 8505: foreach my $code (keys(%{$instcodes})) {
8506: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8507: }
8508: chop($courses);
1.772 raeburn 8509: my $ok_response = 0;
8510: my $response;
8511: while (@homeservers > 0 && $ok_response == 0) {
8512: my $server = shift(@homeservers);
8513: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8514: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8515: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8516: split(/:/,$response);
1.772 raeburn 8517: %{$codes} = (%{$codes},&str2hash($codes_str));
8518: push(@{$codetitles},&str2array($codetitles_str));
8519: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8520: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8521: $ok_response = 1;
8522: }
8523: }
8524: if ($ok_response) {
1.521 raeburn 8525: return 'ok';
1.772 raeburn 8526: } else {
8527: return $response;
1.521 raeburn 8528: }
8529: }
8530:
1.792 raeburn 8531: sub auto_instcode_defaults {
8532: my ($domain,$returnhash,$code_order) = @_;
8533: my @homeservers;
1.841 albertel 8534:
8535: my %servers = &get_servers($domain,'library');
8536: foreach my $tryserver (keys(%servers)) {
8537: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8538: push(@homeservers,$tryserver);
8539: }
1.792 raeburn 8540: }
1.841 albertel 8541:
1.792 raeburn 8542: my $response;
1.841 albertel 8543: foreach my $server (@homeservers) {
1.792 raeburn 8544: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8545: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8546:
8547: foreach my $pair (split(/\&/,$response)) {
8548: my ($name,$value)=split(/\=/,$pair);
8549: if ($name eq 'code_order') {
8550: @{$code_order} = split(/\&/,&unescape($value));
8551: } else {
8552: $returnhash->{&unescape($name)}=&unescape($value);
8553: }
8554: }
8555: return 'ok';
1.792 raeburn 8556: }
1.841 albertel 8557:
8558: return $response;
1.1003 raeburn 8559: }
8560:
8561: sub auto_possible_instcodes {
1.1007 raeburn 8562: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8563: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8564: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8565: return;
8566: }
1.1003 raeburn 8567: my (@homeservers,$uhome);
8568: if (defined(&domain($domain,'primary'))) {
8569: $uhome=&domain($domain,'primary');
8570: push(@homeservers,&domain($domain,'primary'));
8571: } else {
8572: my %servers = &get_servers($domain,'library');
8573: foreach my $tryserver (keys(%servers)) {
8574: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8575: push(@homeservers,$tryserver);
8576: }
8577: }
8578: }
8579: my $response;
8580: foreach my $server (@homeservers) {
8581: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8582: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8583: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8584: split(':',$response);
8585: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8586: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8587: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8588: my ($name,$value)=split('=',$item);
8589: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8590: }
8591: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8592: my ($name,$value)=split('=',$item);
8593: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8594: }
8595: return 'ok';
8596: }
8597: return $response;
8598: }
1.792 raeburn 8599:
1.1010 raeburn 8600: sub auto_courserequest_checks {
8601: my ($dom) = @_;
1.1020 raeburn 8602: my ($homeserver,%validations);
8603: if ($dom =~ /^$match_domain$/) {
8604: $homeserver = &domain($dom,'primary');
8605: }
8606: unless ($homeserver eq 'no_host') {
8607: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8608: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8609: my @items = split(/&/,$response);
8610: foreach my $item (@items) {
8611: my ($key,$value) = split('=',$item);
8612: $validations{&unescape($key)} = &thaw_unescape($value);
8613: }
8614: }
8615: }
1.1010 raeburn 8616: return %validations;
8617: }
8618:
1.1020 raeburn 8619: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8620: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8621: my ($homeserver,$response);
8622: if ($dom =~ /^$match_domain$/) {
8623: $homeserver = &domain($dom,'primary');
8624: }
1.1172.2.43 raeburn 8625: unless ($homeserver eq 'no_host') {
8626: my $customdata;
8627: if (ref($custominfo) eq 'HASH') {
8628: $customdata = &freeze_escape($custominfo);
8629: }
1.1020 raeburn 8630: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8631: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8632: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8633: $customdata,$homeserver));
1.1020 raeburn 8634: }
8635: return $response;
8636: }
8637:
1.777 albertel 8638: sub auto_validate_class_sec {
1.918 raeburn 8639: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8640: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8641: my $ownerlist;
8642: if (ref($owners) eq 'ARRAY') {
8643: $ownerlist = join(',',@{$owners});
8644: } else {
8645: $ownerlist = $owners;
8646: }
1.773 raeburn 8647: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8648: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8649: return $response;
8650: }
8651:
1.1172.2.94 raeburn 8652: sub auto_validate_instclasses {
8653: my ($cdom,$cnum,$owners,$classesref) = @_;
8654: my ($homeserver,%validations);
8655: $homeserver = &homeserver($cnum,$cdom);
8656: unless ($homeserver eq 'no_host') {
8657: my $ownerlist;
8658: if (ref($owners) eq 'ARRAY') {
8659: $ownerlist = join(',',@{$owners});
8660: } else {
8661: $ownerlist = $owners;
8662: }
8663: if (ref($classesref) eq 'HASH') {
8664: my $classes = &freeze_escape($classesref);
8665: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
8666: ':'.$cdom.':'.$classes,$homeserver);
8667: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8668: my @items = split(/&/,$response);
8669: foreach my $item (@items) {
8670: my ($key,$value) = split('=',$item);
8671: $validations{&unescape($key)} = &thaw_unescape($value);
8672: }
8673: }
8674: }
8675: }
8676: return %validations;
8677: }
8678:
1.1172.2.38 raeburn 8679: sub auto_crsreq_update {
8680: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8681: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8682: my ($homeserver,%crsreqresponse);
8683: if ($cdom =~ /^$match_domain$/) {
8684: $homeserver = &domain($cdom,'primary');
8685: }
8686: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8687: my $info;
8688: if (ref($inbound) eq 'HASH') {
8689: $info = &freeze_escape($inbound);
8690: }
8691: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8692: ':'.&escape($action).':'.&escape($ownername).':'.
8693: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8694: &escape($title).':'.&escape($code).':'.
8695: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8696: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8697: my @items = split(/&/,$response);
8698: foreach my $item (@items) {
8699: my ($key,$value) = split('=',$item);
8700: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8701: }
8702: }
8703: }
8704: return \%crsreqresponse;
8705: }
8706:
1.1172.2.78 raeburn 8707: sub auto_export_grades {
8708: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8709: my ($homeserver,%exportresponse);
8710: if ($cdom =~ /^$match_domain$/) {
8711: $homeserver = &domain($cdom,'primary');
8712: }
8713: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8714: my $info;
8715: if (ref($inforef) eq 'HASH') {
8716: $info = &freeze_escape($inforef);
8717: }
8718: if (ref($gradesref) eq 'HASH') {
8719: my $grades = &freeze_escape($gradesref);
8720: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8721: $info.':'.$grades,$homeserver);
8722: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8723: my @items = split(/&/,$response);
8724: foreach my $item (@items) {
8725: my ($key,$value) = split('=',$item);
8726: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8727: }
8728: }
8729: }
8730: }
8731: return \%exportresponse;
8732: }
8733:
1.1172.2.68 raeburn 8734: sub check_instcode_cloning {
8735: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8736: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8737: return;
8738: }
8739: my $canclone;
8740: if (@{$code_order} > 0) {
8741: my $instcoderegexp ='^';
8742: my @clonecodes = split(/\&/,$cloner);
8743: foreach my $item (@{$code_order}) {
8744: if (grep(/^\Q$item\E=/,@clonecodes)) {
8745: foreach my $pair (@clonecodes) {
8746: my ($key,$val) = split(/\=/,$pair,2);
8747: $val = &unescape($val);
8748: if ($key eq $item) {
8749: $instcoderegexp .= '('.$val.')';
8750: last;
8751: }
8752: }
8753: } else {
8754: $instcoderegexp .= $codedefaults->{$item};
8755: }
8756: }
8757: $instcoderegexp .= '$';
8758: my (@from,@to);
8759: eval {
8760: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8761: (@to) = ($clonetocode =~ /$instcoderegexp/);
8762: };
8763: if ((@from > 0) && (@to > 0)) {
8764: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8765: if (!@diffs) {
8766: $canclone = 1;
8767: }
8768: }
8769: }
8770: return $canclone;
8771: }
8772:
8773: sub default_instcode_cloning {
8774: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8775: my (%codedefaults,@code_order,$canclone);
8776: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8777: %codedefaults = %{$codedefaultsref};
8778: @code_order = @{$codeorderref};
8779: } elsif ($clonedom) {
8780: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8781: }
8782: if (($domdefclone) && (@code_order)) {
8783: my @clonecodes = split(/\+/,$domdefclone);
8784: my $instcoderegexp ='^';
8785: foreach my $item (@code_order) {
8786: if (grep(/^\Q$item\E$/,@clonecodes)) {
8787: $instcoderegexp .= '('.$codedefaults{$item}.')';
8788: } else {
8789: $instcoderegexp .= $codedefaults{$item};
8790: }
8791: }
8792: $instcoderegexp .= '$';
8793: my (@from,@to);
8794: eval {
8795: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8796: (@to) = ($clonetocode =~ /$instcoderegexp/);
8797: };
8798: if ((@from > 0) && (@to > 0)) {
8799: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8800: if (!@diffs) {
8801: $canclone = 1;
8802: }
8803: }
8804: }
8805: return $canclone;
8806: }
8807:
1.679 raeburn 8808: # ------------------------------------------------------- Course Group routines
8809:
8810: sub get_coursegroups {
1.809 raeburn 8811: my ($cdom,$cnum,$group,$namespace) = @_;
8812: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8813: }
8814:
1.679 raeburn 8815: sub modify_coursegroup {
8816: my ($cdom,$cnum,$groupsettings) = @_;
8817: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8818: }
8819:
1.809 raeburn 8820: sub toggle_coursegroup_status {
8821: my ($cdom,$cnum,$group,$action) = @_;
8822: my ($from_namespace,$to_namespace);
8823: if ($action eq 'delete') {
8824: $from_namespace = 'coursegroups';
8825: $to_namespace = 'deleted_groups';
8826: } else {
8827: $from_namespace = 'deleted_groups';
8828: $to_namespace = 'coursegroups';
8829: }
8830: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8831: if (my $tmp = &error(%curr_group)) {
8832: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8833: return ('read error',$tmp);
8834: } else {
8835: my %savedsettings = %curr_group;
1.809 raeburn 8836: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8837: my $deloutcome;
8838: if ($result eq 'ok') {
1.809 raeburn 8839: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8840: } else {
8841: return ('write error',$result);
8842: }
8843: if ($deloutcome eq 'ok') {
8844: return 'ok';
8845: } else {
8846: return ('delete error',$deloutcome);
8847: }
8848: }
8849: }
8850:
1.679 raeburn 8851: sub modify_group_roles {
1.957 raeburn 8852: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8853: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8854: my $role = 'gr/'.&escape($userprivs);
8855: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8856: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8857: if ($result eq 'ok') {
8858: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8859: }
1.679 raeburn 8860: return $result;
8861: }
8862:
8863: sub modify_coursegroup_membership {
8864: my ($cdom,$cnum,$membership) = @_;
8865: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8866: return $result;
8867: }
8868:
1.682 raeburn 8869: sub get_active_groups {
8870: my ($udom,$uname,$cdom,$cnum) = @_;
8871: my $now = time;
8872: my %groups = ();
8873: foreach my $key (keys(%env)) {
1.811 albertel 8874: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8875: my ($start,$end) = split(/\./,$env{$key});
8876: if (($end!=0) && ($end<$now)) { next; }
8877: if (($start!=0) && ($start>$now)) { next; }
8878: if ($1 eq $cdom && $2 eq $cnum) {
8879: $groups{$3} = $env{$key} ;
8880: }
8881: }
8882: }
8883: return %groups;
8884: }
8885:
1.683 raeburn 8886: sub get_group_membership {
8887: my ($cdom,$cnum,$group) = @_;
8888: return(&dump('groupmembership',$cdom,$cnum,$group));
8889: }
8890:
8891: sub get_users_groups {
8892: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8893: my @usersgroups;
1.683 raeburn 8894: my $cachetime=1800;
8895:
8896: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8897: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8898: if (defined($cached)) {
1.734 albertel 8899: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8900: } else {
8901: $grouplist = '';
1.816 raeburn 8902: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8903: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8904: my $access_end = $env{'course.'.$courseid.
8905: '.default_enrollment_end_date'};
8906: my $now = time;
8907: foreach my $key (keys(%roleshash)) {
8908: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8909: my $group = $1;
8910: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8911: my $start = $2;
8912: my $end = $1;
8913: if ($start == -1) { next; } # deleted from group
8914: if (($start!=0) && ($start>$now)) { next; }
8915: if (($end!=0) && ($end<$now)) {
8916: if ($access_end && $access_end < $now) {
8917: if ($access_end - $end < 86400) {
8918: push(@usersgroups,$group);
1.733 raeburn 8919: }
8920: }
1.817 raeburn 8921: next;
1.733 raeburn 8922: }
1.817 raeburn 8923: push(@usersgroups,$group);
1.683 raeburn 8924: }
8925: }
8926: }
1.817 raeburn 8927: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8928: $grouplist = join(':',@usersgroups);
8929: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8930: }
1.733 raeburn 8931: return @usersgroups;
1.683 raeburn 8932: }
8933:
8934: sub devalidate_getgroups_cache {
8935: my ($udom,$uname,$cdom,$cnum)=@_;
8936: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8937:
1.683 raeburn 8938: my $hashid="$udom:$uname:$courseid";
8939: &devalidate_cache_new('getgroups',$hashid);
8940: }
8941:
1.12 www 8942: # ------------------------------------------------------------------ Plain Text
8943:
8944: sub plaintext {
1.988 raeburn 8945: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8946: if ($short =~ m{^cr/}) {
1.758 albertel 8947: return (split('/',$short))[-1];
8948: }
1.742 raeburn 8949: if (!defined($cid)) {
8950: $cid = $env{'request.course.id'};
8951: }
8952: my %rolenames = (
1.1008 raeburn 8953: Course => 'std',
8954: Community => 'alt1',
1.742 raeburn 8955: );
1.1037 raeburn 8956: if ($cid ne '') {
8957: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8958: unless ($forcedefault) {
8959: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8960: &Apache::lonlocal::mt_escape(\$roletext);
8961: return &Apache::lonlocal::mt($roletext);
8962: }
8963: }
8964: }
8965: if ((defined($type)) && (defined($rolenames{$type})) &&
8966: (defined($rolenames{$type})) &&
8967: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8968: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8969: } elsif ($cid ne '') {
8970: my $crstype = $env{'course.'.$cid.'.type'};
8971: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8972: (defined($prp{$short}{$rolenames{$crstype}}))) {
8973: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8974: }
1.742 raeburn 8975: }
1.1037 raeburn 8976: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8977: }
8978:
8979: # ----------------------------------------------------------------- Assign Role
8980:
8981: sub assignrole {
1.957 raeburn 8982: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8983: $context)=@_;
1.21 www 8984: my $mrole;
8985: if ($role =~ /^cr\//) {
1.393 www 8986: my $cwosec=$url;
1.811 albertel 8987: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8988: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8989: my $refused = 1;
8990: if ($context eq 'requestcourses') {
8991: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8992: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8993: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8994: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8995: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8996: if ($crsenv{'internal.courseowner'} eq
8997: $env{'user.name'}.':'.$env{'user.domain'}) {
8998: $refused = '';
8999: }
9000: }
9001: }
9002: }
9003: }
9004: if ($refused) {
9005: &logthis('Refused custom assignrole: '.
9006: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9007: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9008: return 'refused';
9009: }
1.104 www 9010: }
1.21 www 9011: $mrole='cr';
1.678 raeburn 9012: } elsif ($role =~ /^gr\//) {
9013: my $cwogrp=$url;
1.811 albertel 9014: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9015: unless (&allowed('mdg',$cwogrp)) {
9016: &logthis('Refused group assignrole: '.
9017: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9018: $env{'user.name'}.' at '.$env{'user.domain'});
9019: return 'refused';
9020: }
9021: $mrole='gr';
1.21 www 9022: } else {
1.82 www 9023: my $cwosec=$url;
1.811 albertel 9024: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9025: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9026: my $refused;
9027: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9028: if (!(&allowed('c'.$role,$url))) {
9029: $refused = 1;
9030: }
9031: } else {
9032: $refused = 1;
9033: }
1.947 raeburn 9034: if ($refused) {
1.1045 raeburn 9035: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9036: if (!$selfenroll && $context eq 'course') {
9037: my %crsenv;
9038: if ($role eq 'cc' || $role eq 'co') {
9039: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9040: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9041: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9042: if ($crsenv{'internal.courseowner'} eq
9043: $env{'user.name'}.':'.$env{'user.domain'}) {
9044: $refused = '';
9045: }
9046: }
9047: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9048: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9049: if ($crsenv{'internal.courseowner'} eq
9050: $env{'user.name'}.':'.$env{'user.domain'}) {
9051: $refused = '';
9052: }
9053: }
9054: }
9055: }
9056: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9057: $refused = '';
1.1017 raeburn 9058: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9059: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9060: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9061: my $wrongcc;
9062: if ($cnum =~ /^$match_community$/) {
9063: $wrongcc = 1 if ($role eq 'cc');
9064: } else {
9065: $wrongcc = 1 if ($role eq 'co');
9066: }
9067: unless ($wrongcc) {
9068: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9069: if ($crsenv{'internal.courseowner'} eq
9070: $env{'user.name'}.':'.$env{'user.domain'}) {
9071: $refused = '';
9072: }
1.1017 raeburn 9073: }
9074: }
1.1172.2.9 raeburn 9075: } elsif ($context eq 'requestauthor') {
9076: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9077: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9078: if ($env{'environment.requestauthor'} eq 'automatic') {
9079: $refused = '';
9080: } else {
9081: my %domdefaults = &get_domain_defaults($udom);
9082: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9083: my $checkbystatus;
9084: if ($env{'user.adv'}) {
9085: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9086: if ($disposition eq 'automatic') {
9087: $refused = '';
9088: } elsif ($disposition eq '') {
9089: $checkbystatus = 1;
9090: }
9091: } else {
9092: $checkbystatus = 1;
9093: }
9094: if ($checkbystatus) {
9095: if ($env{'environment.inststatus'}) {
9096: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9097: foreach my $type (@inststatuses) {
9098: if (($type ne '') &&
9099: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9100: $refused = '';
9101: }
9102: }
9103: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9104: $refused = '';
9105: }
9106: }
9107: }
9108: }
9109: }
1.1017 raeburn 9110: }
9111: if ($refused) {
1.947 raeburn 9112: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9113: ' '.$role.' '.$end.' '.$start.' by '.
9114: $env{'user.name'}.' at '.$env{'user.domain'});
9115: return 'refused';
9116: }
1.932 raeburn 9117: }
1.1131 raeburn 9118: } elsif ($role eq 'au') {
9119: if ($url ne '/'.$udom.'/') {
9120: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9121: ' to assign author role for '.$uname.':'.$udom.
9122: ' in domain: '.$url.' refused (wrong domain).');
9123: return 'refused';
9124: }
1.104 www 9125: }
1.21 www 9126: $mrole=$role;
9127: }
1.620 albertel 9128: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9129: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9130: if ($end) { $command.='_'.$end; }
1.21 www 9131: if ($start) {
9132: if ($end) {
1.81 www 9133: $command.='_'.$start;
1.21 www 9134: } else {
1.81 www 9135: $command.='_0_'.$start;
1.21 www 9136: }
9137: }
1.739 raeburn 9138: my $origstart = $start;
9139: my $origend = $end;
1.957 raeburn 9140: my $delflag;
1.357 www 9141: # actually delete
9142: if ($deleteflag) {
1.373 www 9143: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9144: # modify command to delete the role
1.620 albertel 9145: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9146: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9147: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9148: # set start and finish to negative values for userrolelog
9149: $start=-1;
9150: $end=-1;
1.957 raeburn 9151: $delflag = 1;
1.357 www 9152: }
9153: }
9154: # send command
1.349 www 9155: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9156: # log new user role if status is ok
1.349 www 9157: if ($answer eq 'ok') {
1.663 raeburn 9158: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9159: if (($role eq 'cc') || ($role eq 'in') ||
9160: ($role eq 'ep') || ($role eq 'ad') ||
9161: ($role eq 'ta') || ($role eq 'st') ||
9162: ($role=~/^cr/) || ($role eq 'gr') ||
9163: ($role eq 'co')) {
1.1172.2.13 raeburn 9164: # for course roles, perform group memberships changes triggered by role change.
9165: unless ($role =~ /^gr/) {
9166: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9167: $origstart,$selfenroll,$context);
9168: }
1.1172.2.9 raeburn 9169: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9170: $selfenroll,$context);
9171: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9172: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9173: ($role eq 'da')) {
1.1172.2.9 raeburn 9174: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9175: $context);
9176: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9177: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9178: $context);
9179: }
1.1053 raeburn 9180: if ($role eq 'cc') {
9181: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9182: }
1.349 www 9183: }
9184: return $answer;
1.169 harris41 9185: }
9186:
1.1053 raeburn 9187: sub autoupdate_coowners {
9188: my ($url,$end,$start,$uname,$udom) = @_;
9189: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9190: if (($cdom ne '') && ($cnum ne '')) {
9191: my $now = time;
9192: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9193: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9194: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9195: my $instcode = $coursehash{'internal.coursecode'};
9196: if ($instcode ne '') {
1.1056 raeburn 9197: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9198: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9199: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9200: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9201: if ($result eq 'valid') {
9202: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9203: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9204: push(@newcoowners,$coowner);
9205: }
9206: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9207: push(@newcoowners,$uname.':'.$udom);
9208: }
9209: @newcoowners = sort(@newcoowners);
9210: } else {
9211: push(@newcoowners,$uname.':'.$udom);
9212: }
9213: } else {
9214: if ($coursehash{'internal.co-owners'}) {
9215: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9216: unless ($coowner eq $uname.':'.$udom) {
9217: push(@newcoowners,$coowner);
9218: }
9219: }
9220: unless (@newcoowners > 0) {
9221: $delcoowners = 1;
9222: $coowners = '';
9223: }
9224: }
9225: }
9226: if (@newcoowners || $delcoowners) {
9227: &store_coowners($cdom,$cnum,$coursehash{'home'},
9228: $delcoowners,@newcoowners);
9229: }
9230: }
9231: }
9232: }
9233: }
9234: }
9235: }
9236:
9237: sub store_coowners {
9238: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9239: my $cid = $cdom.'_'.$cnum;
9240: my ($coowners,$delresult,$putresult);
9241: if (@newcoowners) {
9242: $coowners = join(',',@newcoowners);
9243: my %coownershash = (
9244: 'internal.co-owners' => $coowners,
9245: );
9246: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9247: if ($putresult eq 'ok') {
9248: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9249: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9250: }
9251: }
9252: }
9253: if ($delcoowners) {
9254: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9255: if ($delresult eq 'ok') {
9256: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9257: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9258: }
9259: }
9260: }
9261: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9262: my %crsinfo =
9263: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9264: if (ref($crsinfo{$cid}) eq 'HASH') {
9265: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9266: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9267: }
9268: }
9269: }
9270:
1.169 harris41 9271: # -------------------------------------------------- Modify user authentication
1.197 www 9272: # Overrides without validation
9273:
1.169 harris41 9274: sub modifyuserauth {
9275: my ($udom,$uname,$umode,$upass)=@_;
9276: my $uhome=&homeserver($uname,$udom);
1.197 www 9277: unless (&allowed('mau',$udom)) { return 'refused'; }
9278: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9279: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9280: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9281: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9282: &escape($upass),$uhome);
1.620 albertel 9283: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9284: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9285: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9286: &log($udom,,$uname,$uhome,
1.620 albertel 9287: 'Authentication changed by '.$env{'user.domain'}.', '.
9288: $env{'user.name'}.', '.$umode.
1.197 www 9289: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9290: unless ($reply eq 'ok') {
1.197 www 9291: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9292: return 'error: '.$reply;
9293: }
1.170 harris41 9294: return 'ok';
1.80 www 9295: }
9296:
1.81 www 9297: # --------------------------------------------------------------- Modify a user
1.80 www 9298:
1.81 www 9299: sub modifyuser {
1.206 matthew 9300: my ($udom, $uname, $uid,
9301: $umode, $upass, $first,
9302: $middle, $last, $gene,
1.1058 raeburn 9303: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9304: $udom= &LONCAPA::clean_domain($udom);
9305: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9306: my $showcandelete = 'none';
9307: if (ref($candelete) eq 'ARRAY') {
9308: if (@{$candelete} > 0) {
9309: $showcandelete = join(', ',@{$candelete});
9310: }
9311: }
1.81 www 9312: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9313: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9314: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9315: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9316: ' desiredhome not specified').
1.620 albertel 9317: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9318: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9319: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9320: my $newuser;
9321: if ($uhome eq 'no_host') {
9322: $newuser = 1;
9323: }
1.80 www 9324: # ----------------------------------------------------------------- Create User
1.406 albertel 9325: if (($uhome eq 'no_host') &&
9326: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9327: my $unhome='';
1.844 albertel 9328: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9329: $unhome = $desiredhome;
1.620 albertel 9330: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9331: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9332: } else { # load balancing routine for determining $unhome
1.81 www 9333: my $loadm=10000000;
1.841 albertel 9334: my %servers = &get_servers($udom,'library');
9335: foreach my $tryserver (keys(%servers)) {
9336: my $answer=reply('load',$tryserver);
9337: if (($answer=~/\d+/) && ($answer<$loadm)) {
9338: $loadm=$answer;
9339: $unhome=$tryserver;
9340: }
1.80 www 9341: }
9342: }
9343: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9344: return 'error: unable to find a home server for '.$uname.
9345: ' in domain '.$udom;
1.80 www 9346: }
9347: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9348: &escape($upass),$unhome);
9349: unless ($reply eq 'ok') {
9350: return 'error: '.$reply;
9351: }
1.230 stredwic 9352: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9353: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9354: return 'error: unable verify users home machine.';
1.80 www 9355: }
1.209 matthew 9356: } # End of creation of new user
1.80 www 9357: # ---------------------------------------------------------------------- Add ID
9358: if ($uid) {
9359: $uid=~tr/A-Z/a-z/;
9360: my %uidhash=&idrget($udom,$uname);
1.196 www 9361: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9362: && (!$forceid)) {
1.80 www 9363: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9364: return 'error: user id "'.$uid.'" does not match '.
9365: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9366: }
9367: } else {
9368: &idput($udom,($uname => $uid));
9369: }
9370: }
9371: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9372: my @tmp=&get('environment',
1.899 raeburn 9373: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9374: 'permanentemail','inststatus'],
1.134 albertel 9375: $udom,$uname);
1.1075 raeburn 9376: my (%names,%oldnames);
1.313 matthew 9377: if ($tmp[0] =~ m/^error:.*/) {
9378: %names=();
9379: } else {
9380: %names = @tmp;
1.1075 raeburn 9381: %oldnames = %names;
1.313 matthew 9382: }
1.388 www 9383: #
1.1058 raeburn 9384: # If name, email and/or uid are blank (e.g., because an uploaded file
9385: # of users did not contain them), do not overwrite existing values
9386: # unless field is in $candelete array ref.
9387: #
9388:
9389: my @fields = ('firstname','middlename','lastname','generation',
9390: 'permanentemail','id');
9391: my %newvalues;
9392: if (ref($candelete) eq 'ARRAY') {
9393: foreach my $field (@fields) {
9394: if (grep(/^\Q$field\E$/,@{$candelete})) {
9395: if ($field eq 'firstname') {
9396: $names{$field} = $first;
9397: } elsif ($field eq 'middlename') {
9398: $names{$field} = $middle;
9399: } elsif ($field eq 'lastname') {
9400: $names{$field} = $last;
9401: } elsif ($field eq 'generation') {
9402: $names{$field} = $gene;
9403: } elsif ($field eq 'permanentemail') {
9404: $names{$field} = $email;
9405: } elsif ($field eq 'id') {
9406: $names{$field} = $uid;
9407: }
9408: }
9409: }
9410: }
1.388 www 9411: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9412: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9413: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9414: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9415: if ($email) {
9416: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9417: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9418: }
1.899 raeburn 9419: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9420: if (defined($inststatus)) {
9421: $names{'inststatus'} = '';
9422: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9423: if (ref($usertypes) eq 'HASH') {
9424: my @okstatuses;
9425: foreach my $item (split(/:/,$inststatus)) {
9426: if (defined($usertypes->{$item})) {
9427: push(@okstatuses,$item);
9428: }
9429: }
9430: if (@okstatuses) {
9431: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9432: }
9433: }
9434: }
1.1075 raeburn 9435: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9436: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9437: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9438: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9439: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9440: } else {
9441: $logmsg .= ' during self creation';
9442: }
1.1075 raeburn 9443: my $changed;
9444: if ($newuser) {
9445: $changed = 1;
9446: } else {
9447: foreach my $field (@fields) {
9448: if ($names{$field} ne $oldnames{$field}) {
9449: $changed = 1;
9450: last;
9451: }
9452: }
9453: }
9454: unless ($changed) {
9455: $logmsg = 'No changes in user information needed for: '.$logmsg;
9456: &logthis($logmsg);
9457: return 'ok';
9458: }
9459: my $reply = &put('environment', \%names, $udom,$uname);
9460: if ($reply ne 'ok') {
9461: return 'error: '.$reply;
9462: }
1.1087 raeburn 9463: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9464: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9465: }
1.1075 raeburn 9466: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9467: &devalidate_cache_new('namescache',$uname.':'.$udom);
9468: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9469: &logthis($logmsg);
1.134 albertel 9470: return 'ok';
1.80 www 9471: }
9472:
1.81 www 9473: # -------------------------------------------------------------- Modify student
1.80 www 9474:
1.81 www 9475: sub modifystudent {
9476: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9477: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9478: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9479: if (!$cid) {
1.620 albertel 9480: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9481: return 'not_in_class';
9482: }
1.80 www 9483: }
9484: # --------------------------------------------------------------- Make the user
1.81 www 9485: my $reply=&modifyuser
1.209 matthew 9486: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9487: $desiredhome,$email,$inststatus);
1.80 www 9488: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9489: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9490: # student's environment
1.297 matthew 9491: $uid = undef if (!$forceid);
1.455 albertel 9492: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9493: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9494: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9495: return $reply;
9496: }
9497:
9498: sub modify_student_enrollment {
1.1172.2.23 raeburn 9499: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9500: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9501: my ($cdom,$cnum,$chome);
9502: if (!$cid) {
1.620 albertel 9503: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9504: return 'not_in_class';
9505: }
1.620 albertel 9506: $cdom=$env{'course.'.$cid.'.domain'};
9507: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9508: } else {
9509: ($cdom,$cnum)=split(/_/,$cid);
9510: }
1.620 albertel 9511: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9512: if (!$chome) {
1.457 raeburn 9513: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9514: }
1.455 albertel 9515: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9516: # Make sure the user exists
1.81 www 9517: my $uhome=&homeserver($uname,$udom);
9518: if (($uhome eq '') || ($uhome eq 'no_host')) {
9519: return 'error: no such user';
9520: }
1.297 matthew 9521: # Get student data if we were not given enough information
9522: if (!defined($first) || $first eq '' ||
9523: !defined($last) || $last eq '' ||
9524: !defined($uid) || $uid eq '' ||
9525: !defined($middle) || $middle eq '' ||
9526: !defined($gene) || $gene eq '') {
1.294 matthew 9527: # They did not supply us with enough data to enroll the student, so
9528: # we need to pick up more information.
1.297 matthew 9529: my %tmp = &get('environment',
1.294 matthew 9530: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9531: ,$udom,$uname);
9532:
1.800 albertel 9533: #foreach my $key (keys(%tmp)) {
9534: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9535: #}
1.294 matthew 9536: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9537: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9538: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9539: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9540: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9541: }
1.556 albertel 9542: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9543: my $user = "$uname:$udom";
9544: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9545: my $reply=cput('classlist',
1.1148 raeburn 9546: {$user =>
1.1172.2.76 raeburn 9547: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9548: $cdom,$cnum);
1.1148 raeburn 9549: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9550: &devalidate_getsection_cache($udom,$uname,$cid);
9551: } else {
1.81 www 9552: return 'error: '.$reply;
9553: }
1.297 matthew 9554: # Add student role to user
1.83 www 9555: my $uurl='/'.$cid;
1.81 www 9556: $uurl=~s/\_/\//g;
9557: if ($usec) {
9558: $uurl.='/'.$usec;
9559: }
1.1148 raeburn 9560: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9561: $selfenroll,$context);
9562: if ($result ne 'ok') {
9563: if ($old_entry{$user} ne '') {
9564: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9565: } else {
9566: $reply = &del('classlist',[$user],$cdom,$cnum);
9567: }
9568: }
9569: return $result;
1.21 www 9570: }
9571:
1.556 albertel 9572: sub format_name {
9573: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9574: my $name;
9575: if ($first ne 'lastname') {
9576: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9577: } else {
9578: if ($lastname=~/\S/) {
9579: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9580: $name=~s/\s+,/,/;
9581: } else {
9582: $name.= $firstname.' '.$middlename.' '.$generation;
9583: }
9584: }
9585: $name=~s/^\s+//;
9586: $name=~s/\s+$//;
9587: $name=~s/\s+/ /g;
9588: return $name;
9589: }
9590:
1.84 www 9591: # ------------------------------------------------- Write to course preferences
9592:
9593: sub writecoursepref {
9594: my ($courseid,%prefs)=@_;
9595: $courseid=~s/^\///;
9596: $courseid=~s/\_/\//g;
9597: my ($cdomain,$cnum)=split(/\//,$courseid);
9598: my $chome=homeserver($cnum,$cdomain);
9599: if (($chome eq '') || ($chome eq 'no_host')) {
9600: return 'error: no such course';
9601: }
9602: my $cstring='';
1.800 albertel 9603: foreach my $pref (keys(%prefs)) {
9604: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9605: }
1.84 www 9606: $cstring=~s/\&$//;
9607: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9608: }
9609:
9610: # ---------------------------------------------------------- Make/modify course
9611:
9612: sub createcourse {
1.741 raeburn 9613: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9614: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9615: $url=&declutter($url);
9616: my $cid='';
1.1028 raeburn 9617: if ($context eq 'requestcourses') {
9618: my $can_create = 0;
9619: my ($ownername,$ownerdom) = split(':',$course_owner);
9620: if ($udom eq $ownerdom) {
9621: if (&usertools_access($ownername,$ownerdom,$category,undef,
9622: $context)) {
9623: $can_create = 1;
9624: }
9625: } else {
9626: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9627: $category);
9628: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9629: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9630: if (@curr > 0) {
9631: my @options = qw(approval validate autolimit);
9632: my $optregex = join('|',@options);
9633: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9634: $can_create = 1;
9635: }
9636: }
9637: }
9638: }
9639: if ($can_create) {
9640: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9641: unless (&allowed('ccc',$udom)) {
9642: return 'refused';
9643: }
1.1017 raeburn 9644: }
9645: } else {
9646: return 'refused';
9647: }
1.1028 raeburn 9648: } elsif (!&allowed('ccc',$udom)) {
9649: return 'refused';
1.84 www 9650: }
1.1011 raeburn 9651: # --------------------------------------------------------------- Get Unique ID
9652: my $uname;
9653: if ($cnum =~ /^$match_courseid$/) {
9654: my $chome=&homeserver($cnum,$udom,'true');
9655: if (($chome eq '') || ($chome eq 'no_host')) {
9656: $uname = $cnum;
9657: } else {
1.1038 raeburn 9658: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9659: }
9660: } else {
1.1038 raeburn 9661: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9662: }
9663: return $uname if ($uname =~ /^error/);
9664: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9665: if (!defined($course_server)) {
9666: if (defined(&domain($udom,'primary'))) {
9667: $course_server = &domain($udom,'primary');
9668: } else {
9669: $course_server = $env{'user.home'};
9670: }
9671: }
9672: my %host_servers =
9673: &Apache::lonnet::get_servers($udom,'library');
9674: unless ($host_servers{$course_server}) {
9675: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9676: }
1.84 www 9677: # ------------------------------------------------------------- Make the course
9678: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9679: $course_server);
1.84 www 9680: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9681: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9682: if (($uhome eq '') || ($uhome eq 'no_host')) {
9683: return 'error: no such course';
9684: }
1.271 www 9685: # ----------------------------------------------------------------- Course made
1.516 raeburn 9686: # log existence
1.1029 raeburn 9687: my $now = time;
1.918 raeburn 9688: my $newcourse = {
9689: $udom.'_'.$uname => {
1.921 raeburn 9690: description => $description,
9691: inst_code => $inst_code,
9692: owner => $course_owner,
9693: type => $crstype,
1.1029 raeburn 9694: creator => $env{'user.name'}.':'.
9695: $env{'user.domain'},
9696: created => $now,
9697: context => $context,
1.918 raeburn 9698: },
9699: };
1.921 raeburn 9700: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9701: # set toplevel url
1.271 www 9702: my $topurl=$url;
9703: unless ($nonstandard) {
9704: # ------------------------------------------ For standard courses, make top url
9705: my $mapurl=&clutter($url);
1.278 www 9706: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9707: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9708: <map>
9709: <resource id="1" type="start"></resource>
9710: <resource id="2" src="$mapurl"></resource>
9711: <resource id="3" type="finish"></resource>
9712: <link index="1" from="1" to="2"></link>
9713: <link index="2" from="2" to="3"></link>
9714: </map>
9715: ENDINITMAP
9716: $topurl=&declutter(
1.638 albertel 9717: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9718: );
9719: }
9720: # ----------------------------------------------------------- Write preferences
1.84 www 9721: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9722: ('description' => $description,
9723: 'url' => $topurl,
9724: 'internal.creator' => $env{'user.name'}.':'.
9725: $env{'user.domain'},
9726: 'internal.created' => $now,
9727: 'internal.creationcontext' => $context)
9728: );
1.84 www 9729: return '/'.$udom.'/'.$uname;
9730: }
9731:
1.1011 raeburn 9732: # ------------------------------------------------------------------- Create ID
9733: sub generate_coursenum {
1.1038 raeburn 9734: my ($udom,$crstype) = @_;
1.1011 raeburn 9735: my $domdesc = &domain($udom);
9736: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9737: my $first;
9738: if ($crstype eq 'Community') {
9739: $first = '0';
9740: } else {
9741: $first = int(1+rand(9));
9742: }
9743: my $uname=$first.
1.1011 raeburn 9744: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9745: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9746: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9747: # ----------------------------------------------- Make sure that does not exist
9748: my $uhome=&homeserver($uname,$udom,'true');
9749: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9750: if ($crstype eq 'Community') {
9751: $first = '0';
9752: } else {
9753: $first = int(1+rand(9));
9754: }
9755: $uname=$first.
1.1011 raeburn 9756: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9757: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9758: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9759: $uhome=&homeserver($uname,$udom,'true');
9760: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9761: return 'error: unable to generate unique course-ID';
9762: }
9763: }
9764: return $uname;
9765: }
9766:
1.813 albertel 9767: sub is_course {
1.1167 droeschl 9768: my ($cdom, $cnum) = scalar(@_) == 1 ?
9769: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 9770: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
9771: my $uhome=&homeserver($cnum,$cdom);
9772: my $iscourse;
9773: if (grep { $_ eq $uhome } current_machine_ids()) {
9774: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
9775: } else {
9776: my $hashid = $cdom.':'.$cnum;
9777: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
9778: unless (defined($cached)) {
9779: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
9780: $cnum,undef,undef,'.');
9781: $iscourse = 0;
9782: if (exists($courses{$cdom.'_'.$cnum})) {
9783: $iscourse = 1;
9784: }
9785: &do_cache_new('iscourse',$hashid,$iscourse,3600);
9786: }
9787: }
9788: return unless($iscourse);
1.1167 droeschl 9789: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9790: }
9791:
1.1015 raeburn 9792: sub store_userdata {
9793: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9794: my $result;
1.1016 raeburn 9795: if ($datakey ne '') {
1.1013 raeburn 9796: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9797: if ($udom eq '' || $uname eq '') {
9798: $udom = $env{'user.domain'};
9799: $uname = $env{'user.name'};
9800: }
9801: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9802: if (($uhome eq '') || ($uhome eq 'no_host')) {
9803: $result = 'error: no_host';
9804: } else {
9805: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9806: $storehash->{'host'} = $perlvar{'lonHostID'};
9807:
9808: my $namevalue='';
9809: foreach my $key (keys(%{$storehash})) {
9810: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9811: }
9812: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9813: unless ($namespace eq 'courserequests') {
9814: $datakey = &escape($datakey);
9815: }
1.1105 raeburn 9816: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9817: $namevalue,$uhome);
1.1013 raeburn 9818: }
9819: } else {
9820: $result = 'error: data to store was not a hash reference';
9821: }
9822: } else {
9823: $result= 'error: invalid requestkey';
9824: }
9825: return $result;
9826: }
9827:
1.21 www 9828: # ---------------------------------------------------------- Assign Custom Role
9829:
9830: sub assigncustomrole {
1.957 raeburn 9831: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9832: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9833: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9834: }
9835:
9836: # ----------------------------------------------------------------- Revoke Role
9837:
9838: sub revokerole {
1.957 raeburn 9839: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9840: my $now=time;
1.965 raeburn 9841: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9842: }
9843:
9844: # ---------------------------------------------------------- Revoke Custom Role
9845:
9846: sub revokecustomrole {
1.957 raeburn 9847: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9848: my $now=time;
1.357 www 9849: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9850: $deleteflag,$selfenroll,$context);
1.17 www 9851: }
9852:
1.533 banghart 9853: # ------------------------------------------------------------ Disk usage
1.535 albertel 9854: sub diskusage {
1.955 raeburn 9855: my ($udom,$uname,$directorypath,$getpropath)=@_;
9856: $directorypath =~ s/\/$//;
9857: my $listing=&reply('du2:'.&escape($directorypath).':'
9858: .&escape($getpropath).':'.&escape($uname).':'
9859: .&escape($udom),homeserver($uname,$udom));
9860: if ($listing eq 'unknown_cmd') {
9861: if ($getpropath) {
9862: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9863: }
9864: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9865: }
1.514 albertel 9866: return $listing;
1.512 banghart 9867: }
9868:
1.566 banghart 9869: sub is_locked {
1.1096 raeburn 9870: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9871: my @check;
9872: my $is_locked;
1.1093 raeburn 9873: push (@check,$file_name);
1.613 albertel 9874: my %locked = &get('file_permissions',\@check,
1.620 albertel 9875: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9876: my ($tmp)=keys(%locked);
9877: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9878:
1.566 banghart 9879: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9880: $is_locked = 'false';
9881: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9882: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9883: $is_locked = 'true';
1.1096 raeburn 9884: if (ref($which) eq 'ARRAY') {
9885: push(@{$which},$entry);
9886: } else {
9887: last;
9888: }
1.745 raeburn 9889: }
9890: }
1.566 banghart 9891: } else {
9892: $is_locked = 'false';
9893: }
1.1093 raeburn 9894: return $is_locked;
1.566 banghart 9895: }
9896:
1.759 albertel 9897: sub declutter_portfile {
9898: my ($file) = @_;
1.833 albertel 9899: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9900: return $file;
9901: }
9902:
1.559 banghart 9903: # ------------------------------------------------------------- Mark as Read Only
9904:
9905: sub mark_as_readonly {
9906: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9907: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9908: my ($tmp)=keys(%current_permissions);
9909: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9910: foreach my $file (@{$files}) {
1.759 albertel 9911: $file = &declutter_portfile($file);
1.561 banghart 9912: push(@{$current_permissions{$file}},$what);
1.559 banghart 9913: }
1.613 albertel 9914: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9915: return;
9916: }
9917:
1.572 banghart 9918: # ------------------------------------------------------------Save Selected Files
9919:
9920: sub save_selected_files {
9921: my ($user, $path, @files) = @_;
9922: my $filename = $user."savedfiles";
1.573 banghart 9923: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 9924: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 9925: foreach my $file (@files) {
1.620 albertel 9926: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9927: }
9928: foreach my $file (@other_files) {
1.574 banghart 9929: print (OUT $file."\n");
1.572 banghart 9930: }
1.574 banghart 9931: close (OUT);
1.572 banghart 9932: return 'ok';
9933: }
9934:
1.574 banghart 9935: sub clear_selected_files {
9936: my ($user) = @_;
9937: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 9938: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 9939: print (OUT undef);
9940: close (OUT);
9941: return ("ok");
9942: }
9943:
1.572 banghart 9944: sub files_in_path {
9945: my ($user, $path) = @_;
9946: my $filename = $user."savedfiles";
9947: my %return_files;
1.1172.2.96 raeburn 9948: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 9949: while (my $line_in = <IN>) {
1.574 banghart 9950: chomp ($line_in);
9951: my @paths_and_file = split (m!/!, $line_in);
9952: my $file_part = pop (@paths_and_file);
9953: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9954: $path_part.='/';
9955: my $path_and_file = $path_part.$file_part;
9956: if ($path_part eq $path) {
9957: $return_files{$file_part}= 'selected';
9958: }
9959: }
1.574 banghart 9960: close (IN);
9961: return (\%return_files);
1.572 banghart 9962: }
9963:
9964: # called in portfolio select mode, to show files selected NOT in current directory
9965: sub files_not_in_path {
9966: my ($user, $path) = @_;
9967: my $filename = $user."savedfiles";
9968: my @return_files;
9969: my $path_part;
1.1172.2.96 raeburn 9970: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 9971: while (my $line = <IN>) {
1.572 banghart 9972: #ok, I know it's clunky, but I want it to work
1.800 albertel 9973: my @paths_and_file = split(m|/|, $line);
9974: my $file_part = pop(@paths_and_file);
9975: chomp($file_part);
9976: my $path_part = join('/', @paths_and_file);
1.572 banghart 9977: $path_part .= '/';
9978: my $path_and_file = $path_part.$file_part;
9979: if ($path_part ne $path) {
1.800 albertel 9980: push(@return_files, ($path_and_file));
1.572 banghart 9981: }
9982: }
1.800 albertel 9983: close(OUT);
1.574 banghart 9984: return (@return_files);
1.572 banghart 9985: }
9986:
1.745 raeburn 9987: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9988:
1.745 raeburn 9989: sub get_portfile_permissions {
9990: my ($domain,$user) = @_;
1.613 albertel 9991: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9992: my ($tmp)=keys(%current_permissions);
9993: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9994: return \%current_permissions;
9995: }
9996:
9997: #---------------------------------------------Get portfolio file access controls
9998:
1.749 raeburn 9999: sub get_access_controls {
1.745 raeburn 10000: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10001: my %access;
10002: my $real_file = $file;
10003: $file =~ s/\.meta$//;
1.745 raeburn 10004: if (defined($file)) {
1.749 raeburn 10005: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10006: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10007: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10008: }
10009: }
1.745 raeburn 10010: } else {
1.749 raeburn 10011: foreach my $key (keys(%{$current_permissions})) {
10012: if ($key =~ /\0accesscontrol$/) {
10013: if (defined($group)) {
10014: if ($key !~ m-^\Q$group\E/-) {
10015: next;
10016: }
10017: }
10018: my ($fullpath) = split(/\0/,$key);
10019: if (ref($$current_permissions{$key}) eq 'HASH') {
10020: foreach my $control (keys(%{$$current_permissions{$key}})) {
10021: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10022: }
10023: }
10024: }
10025: }
10026: }
10027: return %access;
10028: }
10029:
10030: sub modify_access_controls {
10031: my ($file_name,$changes,$domain,$user)=@_;
10032: my ($outcome,$deloutcome);
10033: my %store_permissions;
10034: my %new_values;
10035: my %new_control;
10036: my %translation;
10037: my @deletions = ();
10038: my $now = time;
10039: if (exists($$changes{'activate'})) {
10040: if (ref($$changes{'activate'}) eq 'HASH') {
10041: my @newitems = sort(keys(%{$$changes{'activate'}}));
10042: my $numnew = scalar(@newitems);
10043: for (my $i=0; $i<$numnew; $i++) {
10044: my $newkey = $newitems[$i];
10045: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10046: if ($newkey =~ /^\d+:/) {
10047: $newkey =~ s/^(\d+)/$newid/;
10048: $translation{$1} = $newid;
10049: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10050: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10051: $translation{$1} = $newid;
10052: }
1.749 raeburn 10053: $new_values{$file_name."\0".$newkey} =
10054: $$changes{'activate'}{$newitems[$i]};
10055: $new_control{$newkey} = $now;
10056: }
10057: }
10058: }
10059: my %todelete;
10060: my %changed_items;
10061: foreach my $action ('delete','update') {
10062: if (exists($$changes{$action})) {
10063: if (ref($$changes{$action}) eq 'HASH') {
10064: foreach my $key (keys(%{$$changes{$action}})) {
10065: my ($itemnum) = ($key =~ /^([^:]+):/);
10066: if ($action eq 'delete') {
10067: $todelete{$itemnum} = 1;
10068: } else {
10069: $changed_items{$itemnum} = $key;
10070: }
10071: }
1.745 raeburn 10072: }
10073: }
1.749 raeburn 10074: }
10075: # get lock on access controls for file.
10076: my $lockhash = {
10077: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10078: ':'.$env{'user.domain'},
10079: };
10080: my $tries = 0;
10081: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10082:
1.1172.2.79 raeburn 10083: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10084: $tries ++;
1.1172.2.79 raeburn 10085: sleep(0.1);
1.749 raeburn 10086: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10087: }
10088: if ($gotlock eq 'ok') {
10089: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10090: my ($tmp)=keys(%curr_permissions);
10091: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10092: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10093: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10094: if (ref($curr_controls) eq 'HASH') {
10095: foreach my $control_item (keys(%{$curr_controls})) {
10096: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10097: if (defined($todelete{$itemnum})) {
10098: push(@deletions,$file_name."\0".$control_item);
10099: } else {
10100: if (defined($changed_items{$itemnum})) {
10101: $new_control{$changed_items{$itemnum}} = $now;
10102: push(@deletions,$file_name."\0".$control_item);
10103: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10104: } else {
10105: $new_control{$control_item} = $$curr_controls{$control_item};
10106: }
10107: }
1.745 raeburn 10108: }
10109: }
10110: }
1.970 raeburn 10111: my ($group);
10112: if (&is_course($domain,$user)) {
10113: ($group,my $file) = split(/\//,$file_name,2);
10114: }
1.749 raeburn 10115: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10116: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10117: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10118: # remove lock
10119: my @del_lock = ($file_name."\0".'locked_access_records');
10120: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10121: my $sqlresult =
1.970 raeburn 10122: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10123: $group);
1.749 raeburn 10124: } else {
10125: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10126: }
1.749 raeburn 10127: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10128: }
10129:
1.827 raeburn 10130: sub make_public_indefinitely {
10131: my ($requrl) = @_;
10132: my $now = time;
10133: my $action = 'activate';
10134: my $aclnum = 0;
10135: if (&is_portfolio_url($requrl)) {
10136: my (undef,$udom,$unum,$file_name,$group) =
10137: &parse_portfolio_url($requrl);
10138: my $current_perms = &get_portfile_permissions($udom,$unum);
10139: my %access_controls = &get_access_controls($current_perms,
10140: $group,$file_name);
10141: foreach my $key (keys(%{$access_controls{$file_name}})) {
10142: my ($num,$scope,$end,$start) =
10143: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10144: if ($scope eq 'public') {
10145: if ($start <= $now && $end == 0) {
10146: $action = 'none';
10147: } else {
10148: $action = 'update';
10149: $aclnum = $num;
10150: }
10151: last;
10152: }
10153: }
10154: if ($action eq 'none') {
10155: return 'ok';
10156: } else {
10157: my %changes;
10158: my $newend = 0;
10159: my $newstart = $now;
10160: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10161: $changes{$action}{$newkey} = {
10162: type => 'public',
10163: time => {
10164: start => $newstart,
10165: end => $newend,
10166: },
10167: };
10168: my ($outcome,$deloutcome,$new_values,$translation) =
10169: &modify_access_controls($file_name,\%changes,$udom,$unum);
10170: return $outcome;
10171: }
10172: } else {
10173: return 'invalid';
10174: }
10175: }
10176:
1.745 raeburn 10177: #------------------------------------------------------Get Marked as Read Only
10178:
10179: sub get_marked_as_readonly {
10180: my ($domain,$user,$what,$group) = @_;
10181: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10182: my @readonly_files;
1.629 banghart 10183: my $cmp1=$what;
10184: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10185: while (my ($file_name,$value) = each(%{$current_permissions})) {
10186: if (defined($group)) {
10187: if ($file_name !~ m-^\Q$group\E/-) {
10188: next;
10189: }
10190: }
1.561 banghart 10191: if (ref($value) eq "ARRAY"){
10192: foreach my $stored_what (@{$value}) {
1.629 banghart 10193: my $cmp2=$stored_what;
1.759 albertel 10194: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10195: $cmp2=join('',@{$stored_what});
1.745 raeburn 10196: }
1.629 banghart 10197: if ($cmp1 eq $cmp2) {
1.561 banghart 10198: push(@readonly_files, $file_name);
1.745 raeburn 10199: last;
1.563 banghart 10200: } elsif (!defined($what)) {
10201: push(@readonly_files, $file_name);
1.745 raeburn 10202: last;
1.561 banghart 10203: }
10204: }
1.745 raeburn 10205: }
1.561 banghart 10206: }
10207: return @readonly_files;
10208: }
1.577 banghart 10209: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10210:
1.577 banghart 10211: sub get_marked_as_readonly_hash {
1.745 raeburn 10212: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10213: my %readonly_files;
1.745 raeburn 10214: while (my ($file_name,$value) = each(%{$current_permissions})) {
10215: if (defined($group)) {
10216: if ($file_name !~ m-^\Q$group\E/-) {
10217: next;
10218: }
10219: }
1.577 banghart 10220: if (ref($value) eq "ARRAY"){
10221: foreach my $stored_what (@{$value}) {
1.745 raeburn 10222: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10223: foreach my $lock_descriptor(@{$stored_what}) {
10224: if ($lock_descriptor eq 'graded') {
10225: $readonly_files{$file_name} = 'graded';
10226: } elsif ($lock_descriptor eq 'handback') {
10227: $readonly_files{$file_name} = 'handback';
10228: } else {
10229: if (!exists($readonly_files{$file_name})) {
10230: $readonly_files{$file_name} = 'locked';
10231: }
10232: }
1.745 raeburn 10233: }
1.750 banghart 10234: }
1.577 banghart 10235: }
10236: }
10237: }
10238: return %readonly_files;
10239: }
1.559 banghart 10240: # ------------------------------------------------------------ Unmark as Read Only
10241:
10242: sub unmark_as_readonly {
1.629 banghart 10243: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10244: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10245: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10246: $file_name = &declutter_portfile($file_name);
1.634 albertel 10247: my $symb_crs = $what;
10248: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10249: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10250: my ($tmp)=keys(%current_permissions);
10251: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10252: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10253: foreach my $file (@readonly_files) {
1.759 albertel 10254: my $clean_file = &declutter_portfile($file);
10255: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10256: my $current_locks = $current_permissions{$file};
1.563 banghart 10257: my @new_locks;
10258: my @del_keys;
10259: if (ref($current_locks) eq "ARRAY"){
10260: foreach my $locker (@{$current_locks}) {
1.632 albertel 10261: my $compare=$locker;
1.749 raeburn 10262: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10263: $compare=join('',@{$locker});
1.746 raeburn 10264: if ($compare ne $symb_crs) {
10265: push(@new_locks, $locker);
10266: }
1.563 banghart 10267: }
10268: }
1.650 albertel 10269: if (scalar(@new_locks) > 0) {
1.563 banghart 10270: $current_permissions{$file} = \@new_locks;
10271: } else {
10272: push(@del_keys, $file);
1.613 albertel 10273: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10274: delete($current_permissions{$file});
1.563 banghart 10275: }
10276: }
1.561 banghart 10277: }
1.613 albertel 10278: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10279: return;
10280: }
1.512 banghart 10281:
1.17 www 10282: # ------------------------------------------------------------ Directory lister
10283:
10284: sub dirlist {
1.955 raeburn 10285: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10286: $uri=~s/^\///;
10287: $uri=~s/\/$//;
1.253 stredwic 10288: my ($udom, $uname);
1.955 raeburn 10289: if ($getuserdir) {
1.253 stredwic 10290: $udom = $userdomain;
10291: $uname = $username;
1.955 raeburn 10292: } else {
10293: (undef,$udom,$uname)=split(/\//,$uri);
10294: if(defined($userdomain)) {
10295: $udom = $userdomain;
10296: }
10297: if(defined($username)) {
10298: $uname = $username;
10299: }
1.253 stredwic 10300: }
1.955 raeburn 10301: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10302:
1.955 raeburn 10303: $dirRoot = $perlvar{'lonDocRoot'};
10304: if (defined($getpropath)) {
10305: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10306: $dirRoot =~ s/\/$//;
1.955 raeburn 10307: } elsif (defined($getuserdir)) {
10308: my $subdir=$uname.'__';
10309: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10310: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10311: ."/$udom/$subdir/$uname";
10312: } elsif (defined($alternateRoot)) {
10313: $dirRoot = $alternateRoot;
1.751 banghart 10314: }
1.253 stredwic 10315:
10316: if($udom) {
10317: if($uname) {
1.1135 raeburn 10318: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10319: if ($uhome eq 'no_host') {
10320: return ([],'no_host');
10321: }
1.955 raeburn 10322: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10323: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10324: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10325: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10326: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10327: } else {
10328: @listing_results = map { &unescape($_); } split(/:/,$listing);
10329: }
1.605 matthew 10330: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10331: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10332: @listing_results = split(/:/,$listing);
10333: } else {
10334: @listing_results = map { &unescape($_); } split(/:/,$listing);
10335: }
1.1135 raeburn 10336: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10337: ($listing eq 'rejected') || ($listing eq 'refused') ||
10338: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10339: return ([],$listing);
10340: } else {
10341: return (\@listing_results);
1.1135 raeburn 10342: }
1.955 raeburn 10343: } elsif(!$alternateRoot) {
1.1136 raeburn 10344: my (%allusers,%listerror);
1.841 albertel 10345: my %servers = &get_servers($udom,'library');
1.955 raeburn 10346: foreach my $tryserver (keys(%servers)) {
10347: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10348: &escape($udom),$tryserver);
10349: if ($listing eq 'unknown_cmd') {
10350: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10351: $udom, $tryserver);
10352: } else {
10353: @listing_results = map { &unescape($_); } split(/:/,$listing);
10354: }
1.841 albertel 10355: if ($listing eq 'unknown_cmd') {
10356: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10357: $udom, $tryserver);
10358: @listing_results = split(/:/,$listing);
10359: } else {
10360: @listing_results =
10361: map { &unescape($_); } split(/:/,$listing);
10362: }
1.1136 raeburn 10363: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10364: ($listing eq 'rejected') || ($listing eq 'refused') ||
10365: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10366: $listerror{$tryserver} = $listing;
10367: } else {
1.841 albertel 10368: foreach my $line (@listing_results) {
10369: my ($entry) = split(/&/,$line,2);
10370: $allusers{$entry} = 1;
10371: }
10372: }
1.253 stredwic 10373: }
1.1136 raeburn 10374: my @alluserslist=();
1.800 albertel 10375: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10376: push(@alluserslist,$user.'&user');
1.253 stredwic 10377: }
1.1172.2.80 raeburn 10378: if (!%listerror) {
10379: # no errors
10380: return (\@alluserslist);
10381: } elsif (scalar(keys(%servers)) == 1) {
10382: # one library server, one error
10383: my ($key) = keys(%listerror);
10384: return (\@alluserslist, $listerror{$key});
10385: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10386: # con_lost indicates that we might miss data from at least one
10387: # library server
10388: return (\@alluserslist, 'con_lost');
10389: } else {
10390: # multiple library servers and no con_lost -> data should be
10391: # complete.
10392: return (\@alluserslist);
10393: }
10394:
1.253 stredwic 10395: } else {
1.1136 raeburn 10396: return ([],'missing username');
1.253 stredwic 10397: }
1.955 raeburn 10398: } elsif(!defined($getpropath)) {
1.1136 raeburn 10399: my $path = $perlvar{'lonDocRoot'}.'/res/';
10400: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10401: return (\@all_domains);
1.955 raeburn 10402: } else {
1.1136 raeburn 10403: return ([],'missing domain');
1.275 stredwic 10404: }
10405: }
10406:
10407: # --------------------------------------------- GetFileTimestamp
10408: # This function utilizes dirlist and returns the date stamp for
10409: # when it was last modified. It will also return an error of -1
10410: # if an error occurs
10411:
10412: sub GetFileTimestamp {
1.955 raeburn 10413: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10414: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10415: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10416: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10417: undef,$getuserdir);
10418: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10419: return -1;
10420: }
10421: if (ref($fileref) eq 'ARRAY') {
10422: my @stats = split('&',$fileref->[0]);
1.375 matthew 10423: # @stats contains first the filename, then the stat output
10424: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10425: } else {
10426: return -1;
1.253 stredwic 10427: }
1.26 www 10428: }
10429:
1.712 albertel 10430: sub stat_file {
10431: my ($uri) = @_;
1.787 albertel 10432: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10433:
1.955 raeburn 10434: my ($udom,$uname,$file);
1.712 albertel 10435: if ($uri =~ m-^/(uploaded|editupload)/-) {
10436: ($udom,$uname,$file) =
1.811 albertel 10437: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10438: $file = 'userfiles/'.$file;
10439: }
10440: if ($uri =~ m-^/res/-) {
10441: ($udom,$uname) =
1.807 albertel 10442: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10443: $file = $uri;
10444: }
10445:
10446: if (!$udom || !$uname || !$file) {
10447: # unable to handle the uri
10448: return ();
10449: }
1.956 raeburn 10450: my $getpropath;
10451: if ($file =~ /^userfiles\//) {
10452: $getpropath = 1;
10453: }
1.1136 raeburn 10454: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10455: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10456: return ();
10457: } else {
10458: if (ref($listref) eq 'ARRAY') {
10459: my @stats = split('&',$listref->[0]);
10460: shift(@stats); #filename is first
10461: return @stats;
10462: }
1.712 albertel 10463: }
10464: return ();
10465: }
10466:
1.26 www 10467: # -------------------------------------------------------- Value of a Condition
10468:
1.713 albertel 10469: # gets the value of a specific preevaluated condition
10470: # stored in the string $env{user.state.<cid>}
10471: # or looks up a condition reference in the bighash and if if hasn't
10472: # already been evaluated recurses into docondval to get the value of
10473: # the condition, then memoizing it to
10474: # $env{user.state.<cid>.<condition>}
1.40 www 10475: sub directcondval {
10476: my $number=shift;
1.620 albertel 10477: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10478: &Apache::lonuserstate::evalstate();
10479: }
1.713 albertel 10480: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10481: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10482: } elsif ($number =~ /^_/) {
10483: my $sub_condition;
10484: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10485: &GDBM_READER(),0640)) {
10486: $sub_condition=$bighash{'conditions'.$number};
10487: untie(%bighash);
10488: }
10489: my $value = &docondval($sub_condition);
1.949 raeburn 10490: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10491: return $value;
10492: }
1.620 albertel 10493: if ($env{'user.state.'.$env{'request.course.id'}}) {
10494: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10495: } else {
10496: return 2;
10497: }
10498: }
10499:
1.713 albertel 10500: # get the collection of conditions for this resource
1.26 www 10501: sub condval {
10502: my $condidx=shift;
1.54 www 10503: my $allpathcond='';
1.713 albertel 10504: foreach my $cond (split(/\|/,$condidx)) {
10505: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10506: $allpathcond.=
10507: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10508: }
1.191 harris41 10509: }
1.54 www 10510: $allpathcond=~s/\|$//;
1.713 albertel 10511: return &docondval($allpathcond);
10512: }
10513:
10514: #evaluates an expression of conditions
10515: sub docondval {
10516: my ($allpathcond) = @_;
10517: my $result=0;
10518: if ($env{'request.course.id'}
10519: && defined($allpathcond)) {
10520: my $operand='|';
10521: my @stack;
10522: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10523: if ($chunk eq '(') {
10524: push @stack,($operand,$result);
10525: } elsif ($chunk eq ')') {
10526: my $before=pop @stack;
10527: if (pop @stack eq '&') {
10528: $result=$result>$before?$before:$result;
10529: } else {
10530: $result=$result>$before?$result:$before;
10531: }
10532: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10533: $operand=$chunk;
10534: } else {
10535: my $new=directcondval($chunk);
10536: if ($operand eq '&') {
10537: $result=$result>$new?$new:$result;
10538: } else {
10539: $result=$result>$new?$result:$new;
10540: }
10541: }
10542: }
1.26 www 10543: }
10544: return $result;
1.421 albertel 10545: }
10546:
10547: # ---------------------------------------------------- Devalidate courseresdata
10548:
10549: sub devalidatecourseresdata {
10550: my ($coursenum,$coursedomain)=@_;
10551: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10552: &devalidate_cache_new('courseres',$hashid);
1.28 www 10553: }
10554:
1.763 www 10555:
1.200 www 10556: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10557: #
10558: # Parameters:
10559: # $coursenum - Number of the course.
10560: # $coursedomain - Domain at which the course was created.
10561: # Returns:
10562: # A hash of the course parameters along (I think) with timestamps
10563: # and version info.
1.877 foxr 10564:
1.624 albertel 10565: sub get_courseresdata {
10566: my ($coursenum,$coursedomain)=@_;
1.200 www 10567: my $coursehom=&homeserver($coursenum,$coursedomain);
10568: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10569: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10570: my %dumpreply;
1.417 albertel 10571: unless (defined($cached)) {
1.624 albertel 10572: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10573: $result=\%dumpreply;
1.251 albertel 10574: my ($tmp) = keys(%dumpreply);
10575: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10576: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10577: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10578: return $tmp;
1.416 albertel 10579: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10580: $result=undef;
1.599 albertel 10581: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10582: }
10583: }
1.624 albertel 10584: return $result;
10585: }
10586:
1.633 albertel 10587: sub devalidateuserresdata {
10588: my ($uname,$udom)=@_;
10589: my $hashid="$udom:$uname";
10590: &devalidate_cache_new('userres',$hashid);
10591: }
10592:
1.624 albertel 10593: sub get_userresdata {
10594: my ($uname,$udom)=@_;
10595: #most student don\'t have any data set, check if there is some data
10596: if (&EXT_cache_status($udom,$uname)) { return undef; }
10597:
10598: my $hashid="$udom:$uname";
10599: my ($result,$cached)=&is_cached_new('userres',$hashid);
10600: if (!defined($cached)) {
10601: my %resourcedata=&dump('resourcedata',$udom,$uname);
10602: $result=\%resourcedata;
10603: &do_cache_new('userres',$hashid,$result,600);
10604: }
10605: my ($tmp)=keys(%$result);
10606: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10607: return $result;
10608: }
10609: #error 2 occurs when the .db doesn't exist
10610: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10611: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10612: &logthis("<font color=\"blue\">WARNING:".
10613: " Trying to get resource data for ".
10614: $uname." at ".$udom.": ".
10615: $tmp."</font>");
10616: }
1.624 albertel 10617: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10618: #&EXT_cache_set($udom,$uname);
10619: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10620: undef($tmp); # not really an error so don't send it back
1.624 albertel 10621: }
10622: return $tmp;
10623: }
1.879 foxr 10624: #----------------------------------------------- resdata - return resource data
10625: # Purpose:
10626: # Return resource data for either users or for a course.
10627: # Parameters:
10628: # $name - Course/user name.
10629: # $domain - Name of the domain the user/course is registered on.
10630: # $type - Type of thing $name is (must be 'course' or 'user'
10631: # @which - Array of names of resources desired.
10632: # Returns:
10633: # The value of the first reasource in @which that is found in the
10634: # resource hash.
10635: # Exceptional Conditions:
10636: # If the $type passed in is not valid (not the string 'course' or
10637: # 'user', an undefined reference is returned.
10638: # If none of the resources are found, an undef is returned
1.624 albertel 10639: sub resdata {
10640: my ($name,$domain,$type,@which)=@_;
10641: my $result;
10642: if ($type eq 'course') {
10643: $result=&get_courseresdata($name,$domain);
10644: } elsif ($type eq 'user') {
10645: $result=&get_userresdata($name,$domain);
10646: }
10647: if (!ref($result)) { return $result; }
1.251 albertel 10648: foreach my $item (@which) {
1.927 albertel 10649: if (defined($result->{$item->[0]})) {
10650: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10651: }
1.250 albertel 10652: }
1.291 albertel 10653: return undef;
1.200 www 10654: }
10655:
1.1172.2.31 raeburn 10656: sub get_numsuppfiles {
10657: my ($cnum,$cdom,$ignorecache)=@_;
10658: my $hashid=$cnum.':'.$cdom;
10659: my ($suppcount,$cached);
10660: unless ($ignorecache) {
10661: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10662: }
10663: unless (defined($cached)) {
10664: my $chome=&homeserver($cnum,$cdom);
10665: unless ($chome eq 'no_host') {
10666: ($suppcount,my $errors) = (0,0);
10667: my $suppmap = 'supplemental.sequence';
10668: ($suppcount,$errors) =
10669: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10670: }
10671: &do_cache_new('suppcount',$hashid,$suppcount,600);
10672: }
10673: return $suppcount;
10674: }
10675:
1.379 matthew 10676: #
10677: # EXT resource caching routines
10678: #
10679:
10680: sub clear_EXT_cache_status {
1.383 albertel 10681: &delenv('cache.EXT.');
1.379 matthew 10682: }
10683:
10684: sub EXT_cache_status {
10685: my ($target_domain,$target_user) = @_;
1.383 albertel 10686: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10687: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10688: # We know already the user has no data
10689: return 1;
10690: } else {
10691: return 0;
10692: }
10693: }
10694:
10695: sub EXT_cache_set {
10696: my ($target_domain,$target_user) = @_;
1.383 albertel 10697: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10698: #&appenv({$cachename => time});
1.379 matthew 10699: }
10700:
1.28 www 10701: # --------------------------------------------------------- Value of a Variable
1.58 www 10702: sub EXT {
1.715 albertel 10703:
1.1172.2.28 raeburn 10704: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10705: unless ($varname) { return ''; }
1.218 albertel 10706: #get real user name/domain, courseid and symb
10707: my $courseid;
1.359 albertel 10708: my $publicuser;
1.427 www 10709: if ($symbparm) {
10710: $symbparm=&get_symb_from_alias($symbparm);
10711: }
1.218 albertel 10712: if (!($uname && $udom)) {
1.790 albertel 10713: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10714: if (!$symbparm) { $symbparm=$cursymb; }
10715: } else {
1.620 albertel 10716: $courseid=$env{'request.course.id'};
1.218 albertel 10717: }
1.48 www 10718: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10719: my $rest;
1.320 albertel 10720: if (defined($therest[0])) {
1.48 www 10721: $rest=join('.',@therest);
10722: } else {
10723: $rest='';
10724: }
1.320 albertel 10725:
1.57 www 10726: my $qualifierrest=$qualifier;
10727: if ($rest) { $qualifierrest.='.'.$rest; }
10728: my $spacequalifierrest=$space;
10729: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10730: if ($realm eq 'user') {
1.48 www 10731: # --------------------------------------------------------------- user.resource
10732: if ($space eq 'resource') {
1.651 albertel 10733: if ( (defined($Apache::lonhomework::parsing_a_problem)
10734: || defined($Apache::lonhomework::parsing_a_task))
10735: &&
1.744 albertel 10736: ($symbparm eq &symbread()) ) {
10737: # if we are in the middle of processing the resource the
10738: # get the value we are planning on committing
10739: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10740: return $Apache::lonhomework::results{$qualifierrest};
10741: } else {
10742: return $Apache::lonhomework::history{$qualifierrest};
10743: }
1.335 albertel 10744: } else {
1.359 albertel 10745: my %restored;
1.620 albertel 10746: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10747: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10748: } else {
10749: %restored=&restore($symbparm,$courseid,$udom,$uname);
10750: }
1.335 albertel 10751: return $restored{$qualifierrest};
10752: }
1.48 www 10753: # ----------------------------------------------------------------- user.access
10754: } elsif ($space eq 'access') {
1.218 albertel 10755: # FIXME - not supporting calls for a specific user
1.48 www 10756: return &allowed($qualifier,$rest);
10757: # ------------------------------------------ user.preferences, user.environment
10758: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10759: if (($uname eq $env{'user.name'}) &&
10760: ($udom eq $env{'user.domain'})) {
10761: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10762: } else {
1.359 albertel 10763: my %returnhash;
10764: if (!$publicuser) {
10765: %returnhash=&userenvironment($udom,$uname,
10766: $qualifierrest);
10767: }
1.218 albertel 10768: return $returnhash{$qualifierrest};
10769: }
1.48 www 10770: # ----------------------------------------------------------------- user.course
10771: } elsif ($space eq 'course') {
1.218 albertel 10772: # FIXME - not supporting calls for a specific user
1.620 albertel 10773: return $env{join('.',('request.course',$qualifier))};
1.48 www 10774: # ------------------------------------------------------------------- user.role
10775: } elsif ($space eq 'role') {
1.218 albertel 10776: # FIXME - not supporting calls for a specific user
1.620 albertel 10777: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10778: if ($qualifier eq 'value') {
10779: return $role;
10780: } elsif ($qualifier eq 'extent') {
10781: return $where;
10782: }
10783: # ----------------------------------------------------------------- user.domain
10784: } elsif ($space eq 'domain') {
1.218 albertel 10785: return $udom;
1.48 www 10786: # ------------------------------------------------------------------- user.name
10787: } elsif ($space eq 'name') {
1.218 albertel 10788: return $uname;
1.48 www 10789: # ---------------------------------------------------- Any other user namespace
1.29 www 10790: } else {
1.359 albertel 10791: my %reply;
10792: if (!$publicuser) {
10793: %reply=&get($space,[$qualifierrest],$udom,$uname);
10794: }
10795: return $reply{$qualifierrest};
1.48 www 10796: }
1.236 www 10797: } elsif ($realm eq 'query') {
10798: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10799: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10800: [$spacequalifierrest]);
1.620 albertel 10801: return $env{'form.'.$spacequalifierrest};
1.236 www 10802: } elsif ($realm eq 'request') {
1.48 www 10803: # ------------------------------------------------------------- request.browser
10804: if ($space eq 'browser') {
1.1145 bisitz 10805: return $env{'browser.'.$qualifier};
1.57 www 10806: # ------------------------------------------------------------ request.filename
10807: } else {
1.620 albertel 10808: return $env{'request.'.$spacequalifierrest};
1.29 www 10809: }
1.28 www 10810: } elsif ($realm eq 'course') {
1.48 www 10811: # ---------------------------------------------------------- course.description
1.620 albertel 10812: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10813: } elsif ($realm eq 'resource') {
1.165 www 10814:
1.620 albertel 10815: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10816: if (!$symbparm) { $symbparm=&symbread(); }
10817: }
1.693 albertel 10818:
1.1172.2.30 raeburn 10819: if ($qualifier eq '') {
10820: if ($space eq 'title') {
10821: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10822: return &gettitle($symbparm);
10823: }
1.693 albertel 10824:
1.1172.2.30 raeburn 10825: if ($space eq 'map') {
10826: my ($map) = &decode_symb($symbparm);
10827: return &symbread($map);
10828: }
10829: if ($space eq 'maptitle') {
10830: my ($map) = &decode_symb($symbparm);
10831: return &gettitle($map);
10832: }
10833: if ($space eq 'filename') {
10834: if ($symbparm) {
10835: return &clutter((&decode_symb($symbparm))[2]);
10836: }
10837: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10838: }
1.1172.2.30 raeburn 10839:
10840: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10841: if ($space eq 'visibleparts') {
10842: my $navmap = Apache::lonnavmaps::navmap->new();
10843: my $item;
10844: if (ref($navmap)) {
10845: my $res = $navmap->getBySymb($symbparm);
10846: my $parts = $res->parts();
10847: if (ref($parts) eq 'ARRAY') {
10848: $item = join(',',@{$parts});
10849: }
10850: undef($navmap);
10851: }
10852: return $item;
10853: }
10854: }
10855: }
1.693 albertel 10856:
10857: my ($section, $group, @groups);
1.593 albertel 10858: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10859: if (($courseid eq '') && ($cid)) {
10860: $courseid = $cid;
10861: }
10862: if (($symbparm && $courseid) &&
10863: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10864:
1.218 albertel 10865: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10866:
1.60 www 10867: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10868: my $symbp=$symbparm;
1.735 albertel 10869: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10870:
10871: my $symbparm=$symbp.'.'.$spacequalifierrest;
10872: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10873:
1.620 albertel 10874: if (($env{'user.name'} eq $uname) &&
10875: ($env{'user.domain'} eq $udom)) {
10876: $section=$env{'request.course.sec'};
1.733 raeburn 10877: @groups = split(/:/,$env{'request.course.groups'});
10878: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10879: } else {
1.539 albertel 10880: if (! defined($usection)) {
1.551 albertel 10881: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10882: } else {
10883: $section = $usection;
10884: }
1.733 raeburn 10885: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10886: }
10887:
10888: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10889: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10890: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10891:
1.593 albertel 10892: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10893: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10894: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10895:
1.60 www 10896: # ----------------------------------------------------------- first, check user
1.624 albertel 10897:
10898: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10899: ([$courselevelr,'resource'],
10900: [$courselevelm,'map' ],
10901: [$courselevel, 'course' ]));
1.931 albertel 10902: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10903:
1.594 albertel 10904: # ------------------------------------------------ second, check some of course
1.684 raeburn 10905: my $coursereply;
1.691 raeburn 10906: if (@groups > 0) {
10907: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10908: $mapparm,$spacequalifierrest);
1.927 albertel 10909: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10910: }
1.96 www 10911:
1.684 raeburn 10912: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10913: $env{'course.'.$courseid.'.domain'},
10914: 'course',
10915: ([$seclevelr, 'resource'],
10916: [$seclevelm, 'map' ],
10917: [$seclevel, 'course' ],
10918: [$courselevelr,'resource']));
10919: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10920:
1.60 www 10921: # ------------------------------------------------------ third, check map parms
1.218 albertel 10922: my %parmhash=();
10923: my $thisparm='';
10924: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10925: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10926: &GDBM_READER(),0640)) {
1.218 albertel 10927: $thisparm=$parmhash{$symbparm};
10928: untie(%parmhash);
10929: }
1.927 albertel 10930: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10931: }
1.594 albertel 10932: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10933:
1.218 albertel 10934: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10935: my $filename;
10936: if (!$symbparm) { $symbparm=&symbread(); }
10937: if ($symbparm) {
1.409 www 10938: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10939: } else {
1.620 albertel 10940: $filename=$env{'request.filename'};
1.282 albertel 10941: }
10942: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10943: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10944: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10945: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10946:
1.927 albertel 10947: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10948: if ($symbparm && defined($courseid) &&
1.620 albertel 10949: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10950: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10951: $env{'course.'.$courseid.'.domain'},
10952: 'course',
1.927 albertel 10953: ([$courselevelm,'map' ],
10954: [$courselevel, 'course']));
10955: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10956: }
1.145 www 10957: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10958: unless ($space eq '0') {
1.336 albertel 10959: my @parts=split(/_/,$space);
10960: my $id=pop(@parts);
10961: my $part=join('_',@parts);
10962: if ($part eq '') { $part='0'; }
1.927 albertel 10963: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10964: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10965: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10966: }
1.395 albertel 10967: if ($recurse) { return undef; }
10968: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10969: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10970: # ---------------------------------------------------- Any other user namespace
10971: } elsif ($realm eq 'environment') {
10972: # ----------------------------------------------------------------- environment
1.620 albertel 10973: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10974: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10975: } else {
1.770 albertel 10976: if ($uname eq 'anonymous' && $udom eq '') {
10977: return '';
10978: }
1.219 albertel 10979: my %returnhash=&userenvironment($udom,$uname,
10980: $spacequalifierrest);
10981: return $returnhash{$spacequalifierrest};
10982: }
1.28 www 10983: } elsif ($realm eq 'system') {
1.48 www 10984: # ----------------------------------------------------------------- system.time
10985: if ($space eq 'time') {
10986: return time;
10987: }
1.696 albertel 10988: } elsif ($realm eq 'server') {
10989: # ----------------------------------------------------------------- system.time
10990: if ($space eq 'name') {
10991: return $ENV{'SERVER_NAME'};
10992: }
1.28 www 10993: }
1.48 www 10994: return '';
1.61 www 10995: }
10996:
1.927 albertel 10997: sub get_reply {
10998: my ($reply_value) = @_;
1.940 raeburn 10999: if (ref($reply_value) eq 'ARRAY') {
11000: if (wantarray) {
11001: return @$reply_value;
11002: }
11003: return $reply_value->[0];
11004: } else {
11005: return $reply_value;
1.927 albertel 11006: }
11007: }
11008:
1.691 raeburn 11009: sub check_group_parms {
11010: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11011: my @groupitems = ();
11012: my $resultitem;
1.927 albertel 11013: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11014: foreach my $group (@{$groups}) {
11015: foreach my $level (@levels) {
1.927 albertel 11016: my $item = $courseid.'.['.$group.'].'.$level->[0];
11017: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11018: }
11019: }
11020: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11021: $env{'course.'.$courseid.'.domain'},
11022: 'course',@groupitems);
11023: return $coursereply;
11024: }
11025:
11026: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11027: my ($courseid,@groups) = @_;
11028: @groups = sort(@groups);
1.691 raeburn 11029: return @groups;
11030: }
11031:
1.395 albertel 11032: sub packages_tab_default {
11033: my ($uri,$varname)=@_;
11034: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11035:
11036: my (@extension,@specifics,$do_default);
11037: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11038: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11039: if ($pack_type eq 'default') {
11040: $do_default=1;
11041: } elsif ($pack_type eq 'extension') {
11042: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11043: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11044: # only look at packages defaults for packages that this id is
1.738 albertel 11045: push(@specifics,[$package,$pack_type,$pack_part]);
11046: }
11047: }
11048: # first look for a package that matches the requested part id
11049: foreach my $package (@specifics) {
11050: my (undef,$pack_type,$pack_part)=@{$package};
11051: next if ($pack_part ne $part);
11052: if (defined($packagetab{"$pack_type&$name&default"})) {
11053: return $packagetab{"$pack_type&$name&default"};
11054: }
11055: }
11056: # look for any possible matching non extension_ package
11057: foreach my $package (@specifics) {
11058: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11059: if (defined($packagetab{"$pack_type&$name&default"})) {
11060: return $packagetab{"$pack_type&$name&default"};
11061: }
1.585 albertel 11062: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11063: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11064: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11065: }
11066: }
1.738 albertel 11067: # look for any posible extension_ match
11068: foreach my $package (@extension) {
11069: my ($package,$pack_type)=@{$package};
11070: if (defined($packagetab{"$pack_type&$name&default"})) {
11071: return $packagetab{"$pack_type&$name&default"};
11072: }
11073: if (defined($packagetab{$package."&$name&default"})) {
11074: return $packagetab{$package."&$name&default"};
11075: }
11076: }
11077: # look for a global default setting
11078: if ($do_default && defined($packagetab{"default&$name&default"})) {
11079: return $packagetab{"default&$name&default"};
11080: }
1.395 albertel 11081: return undef;
11082: }
11083:
1.334 albertel 11084: sub add_prefix_and_part {
11085: my ($prefix,$part)=@_;
11086: my $keyroot;
11087: if (defined($prefix) && $prefix !~ /^__/) {
11088: # prefix that has a part already
11089: $keyroot=$prefix;
11090: } elsif (defined($prefix)) {
11091: # prefix that is missing a part
11092: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11093: } else {
11094: # no prefix at all
11095: if (defined($part)) { $keyroot='_'.$part; }
11096: }
11097: return $keyroot;
11098: }
11099:
1.71 www 11100: # ---------------------------------------------------------------- Get metadata
11101:
1.599 albertel 11102: my %metaentry;
1.1070 www 11103: my %importedpartids;
1.1172.2.99 raeburn 11104: my %importedrespids;
1.71 www 11105: sub metadata {
1.176 www 11106: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11107: $uri=&declutter($uri);
1.288 albertel 11108: # if it is a non metadata possible uri return quickly
1.529 albertel 11109: if (($uri eq '') ||
11110: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11111: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11112: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11113: return undef;
11114: }
1.1172.2.49 raeburn 11115: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11116: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11117: return undef;
1.288 albertel 11118: }
1.73 www 11119: my $filename=$uri;
11120: $uri=~s/\.meta$//;
1.172 www 11121: #
11122: # Is the metadata already cached?
1.177 www 11123: # Look at timestamp of caching
1.172 www 11124: # Everything is cached by the main uri, libraries are never directly cached
11125: #
1.428 albertel 11126: if (!defined($liburi)) {
1.599 albertel 11127: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11128: if (defined($cached)) { return $result->{':'.$what}; }
11129: }
11130: {
1.1069 www 11131: # Imported parts would go here
1.1172.2.99 raeburn 11132: my @origfiletagids=();
1.1069 www 11133: my $importedparts=0;
1.1172.2.99 raeburn 11134:
11135: # Imported responseids would go here
11136: my $importedresponses=0;
1.172 www 11137: #
11138: # Is this a recursive call for a library?
11139: #
1.599 albertel 11140: # if (! exists($metacache{$uri})) {
11141: # $metacache{$uri}={};
11142: # }
1.924 albertel 11143: my $cachetime = 60*60;
1.171 www 11144: if ($liburi) {
11145: $liburi=&declutter($liburi);
11146: $filename=$liburi;
1.401 bowersj2 11147: } else {
1.599 albertel 11148: &devalidate_cache_new('meta',$uri);
11149: undef(%metaentry);
1.401 bowersj2 11150: }
1.140 www 11151: my %metathesekeys=();
1.73 www 11152: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11153: my $metastring;
1.1140 www 11154: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11155: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11156: $metastring =
1.929 albertel 11157: &Apache::lonnet::ssi_body($which,
1.924 albertel 11158: ('grade_target' => 'meta'));
11159: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11160: } elsif (($uri !~ m -^(editupload)/-) &&
11161: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11162: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11163: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11164: $metastring=&getfile($file);
1.489 albertel 11165: }
1.208 albertel 11166: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11167: my $token;
1.140 www 11168: undef %metathesekeys;
1.71 www 11169: while ($token=$parser->get_token) {
1.339 albertel 11170: if ($token->[0] eq 'S') {
11171: if (defined($token->[2]->{'package'})) {
1.172 www 11172: #
11173: # This is a package - get package info
11174: #
1.339 albertel 11175: my $package=$token->[2]->{'package'};
11176: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11177: if (defined($token->[2]->{'id'})) {
11178: $keyroot.='_'.$token->[2]->{'id'};
11179: }
1.599 albertel 11180: if ($metaentry{':packages'}) {
11181: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11182: } else {
1.599 albertel 11183: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11184: }
1.736 albertel 11185: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11186: my $part=$keyroot;
11187: $part=~s/^\_//;
1.736 albertel 11188: if ($pack_entry=~/^\Q$package\E\&/ ||
11189: $pack_entry=~/^\Q$package\E_0\&/) {
11190: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11191: # ignore package.tab specified default values
11192: # here &package_tab_default() will fetch those
11193: if ($subp eq 'default') { next; }
1.736 albertel 11194: my $value=$packagetab{$pack_entry};
1.432 albertel 11195: my $unikey;
11196: if ($pack =~ /_0$/) {
11197: $unikey='parameter_0_'.$name;
11198: $part=0;
11199: } else {
11200: $unikey='parameter'.$keyroot.'_'.$name;
11201: }
1.339 albertel 11202: if ($subp eq 'display') {
11203: $value.=' [Part: '.$part.']';
11204: }
1.599 albertel 11205: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11206: $metathesekeys{$unikey}=1;
1.599 albertel 11207: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11208: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11209: }
1.599 albertel 11210: if (defined($metaentry{':'.$unikey.'.default'})) {
11211: $metaentry{':'.$unikey}=
11212: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11213: }
1.339 albertel 11214: }
11215: }
11216: } else {
1.172 www 11217: #
11218: # This is not a package - some other kind of start tag
1.339 albertel 11219: #
11220: my $entry=$token->[1];
1.1068 www 11221: my $unikey='';
1.175 www 11222:
1.339 albertel 11223: if ($entry eq 'import') {
1.175 www 11224: #
11225: # Importing a library here
1.339 albertel 11226: #
1.1067 www 11227: my $location=$parser->get_text('/import');
11228: my $dir=$filename;
11229: $dir=~s|[^/]*$||;
11230: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 11231:
11232: my $importid=$token->[2]->{'id'};
1.1068 www 11233: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 11234: #
11235: # Check metadata for imported file to
11236: # see if it contained response items
11237: #
11238: my %currmetaentry = %metaentry;
11239: my $libresponseorder = &metadata($location,'responseorder');
11240: my $origfile;
11241: if ($libresponseorder ne '') {
11242: if ($#origfiletagids<0) {
11243: undef(%importedrespids);
11244: undef(%importedpartids);
11245: }
11246: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11247: if (@{$importedrespids{$importid}} > 0) {
11248: $importedresponses = 1;
11249: # We need to get the original file and the imported file to get the response order correct
11250: # Load and inspect original file
11251: if ($#origfiletagids<0) {
11252: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11253: $origfile=&getfile($origfilelocation);
11254: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11255: }
11256: }
11257: }
11258: # Do not overwrite contents of %metaentry hash for resource itself with
11259: # hash populated for imported library file
11260: %metaentry = %currmetaentry;
11261: undef(%currmetaentry);
1.1068 www 11262: if ($importmode eq 'problem') {
1.1069 www 11263: # Import as problem/response
1.1068 www 11264: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11265: } elsif ($importmode eq 'part') {
11266: # Import as part(s)
1.1069 www 11267: $importedparts=1;
11268: # We need to get the original file and the imported file to get the part order correct
11269: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 11270: # Load and inspect original file if we didn't do that already
11271: if ($#origfiletagids<0) {
11272: undef(%importedrespids);
11273: undef(%importedpartids);
11274: if ($origfile eq '') {
11275: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11276: $origfile=&getfile($origfilelocation);
11277: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11278: }
1.1070 www 11279: }
11280:
1.1069 www 11281: # Load and inspect imported file
11282: my $impfile=&getfile($location);
11283: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11284: if ($#impfilepartids>=0) {
11285: # This problem had parts
1.1070 www 11286: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11287: } else {
11288: # Importing by turning a single problem into a problem part
11289: # It gets the import-tags ID as part-ID
11290: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11291: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11292: }
1.1068 www 11293: } else {
11294: # Normal import
11295: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11296: if (defined($token->[2]->{'id'})) {
11297: $unikey.='_'.$token->[2]->{'id'};
11298: }
1.1067 www 11299: }
11300:
1.339 albertel 11301: if ($depthcount<20) {
1.736 albertel 11302: my $metadata =
11303: &metadata($uri,'keys', $location,$unikey,
11304: $depthcount+1);
11305: foreach my $meta (split(',',$metadata)) {
11306: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11307: $metathesekeys{$meta}=1;
1.339 albertel 11308: }
1.1068 www 11309:
11310: }
1.1067 www 11311: } else {
11312: #
11313: # Not importing, some other kind of non-package, non-library start tag
11314: #
11315: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11316: if (defined($token->[2]->{'id'})) {
11317: $unikey.='_'.$token->[2]->{'id'};
11318: }
1.339 albertel 11319: if (defined($token->[2]->{'name'})) {
11320: $unikey.='_'.$token->[2]->{'name'};
11321: }
11322: $metathesekeys{$unikey}=1;
1.736 albertel 11323: foreach my $param (@{$token->[3]}) {
11324: $metaentry{':'.$unikey.'.'.$param} =
11325: $token->[2]->{$param};
1.339 albertel 11326: }
11327: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11328: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11329: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11330: # only ws inside the tag, and not in default, so use default
11331: # as value
1.599 albertel 11332: $metaentry{':'.$unikey}=$default;
1.908 albertel 11333: } elsif ( $internaltext =~ /\S/ ) {
11334: # something interesting inside the tag
11335: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11336: } else {
1.908 albertel 11337: # no interesting values, don't set a default
1.339 albertel 11338: }
1.172 www 11339: # end of not-a-package not-a-library import
1.339 albertel 11340: }
1.172 www 11341: # end of not-a-package start tag
1.339 albertel 11342: }
1.172 www 11343: # the next is the end of "start tag"
1.339 albertel 11344: }
11345: }
1.483 albertel 11346: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11347: $extension = lc($extension);
11348: if ($extension eq 'htm') { $extension='html'; }
11349:
1.737 albertel 11350: foreach my $key (keys(%packagetab)) {
1.483 albertel 11351: #no specific packages #how's our extension
11352: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11353: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11354: \%metathesekeys);
11355: }
1.883 albertel 11356:
11357: if (!exists($metaentry{':packages'})
11358: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11359: foreach my $key (keys(%packagetab)) {
1.483 albertel 11360: #no specific packages well let's get default then
11361: if ($key!~/^default&/) { next; }
1.488 albertel 11362: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11363: \%metathesekeys);
11364: }
11365: }
1.338 www 11366: # are there custom rights to evaluate
1.599 albertel 11367: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11368:
1.338 www 11369: #
11370: # Importing a rights file here
1.339 albertel 11371: #
11372: unless ($depthcount) {
1.599 albertel 11373: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11374: my $dir=$filename;
11375: $dir=~s|[^/]*$||;
11376: $location=&filelocation($dir,$location);
1.736 albertel 11377: my $rights_metadata =
11378: &metadata($uri,'keys',$location,'_rights',
11379: $depthcount+1);
11380: foreach my $rights (split(',',$rights_metadata)) {
11381: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11382: $metathesekeys{$rights}=1;
1.339 albertel 11383: }
11384: }
11385: }
1.737 albertel 11386: # uniqifiy package listing
11387: my %seen;
11388: my @uniq_packages =
11389: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11390: $metaentry{':packages'} = join(',',@uniq_packages);
11391:
1.1172.2.99 raeburn 11392: if (($importedresponses) || ($importedparts)) {
11393: if ($importedparts) {
1.1070 www 11394: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 11395: $metaentry{':partorder'}='';
11396: $metathesekeys{'partorder'}=1;
11397: }
11398: if ($importedresponses) {
11399: # We had imported responses and need to rebuild responseorder
11400: $metaentry{':responseorder'}='';
11401: $metathesekeys{'responseorder'}=1;
11402: }
11403: for (my $index=0;$index<$#origfiletagids;$index+=2) {
11404: my $origid = $origfiletagids[$index+1];
11405: if ($origfiletagids[$index] eq 'part') {
11406: # Original part, part of the problem
11407: if ($importedparts) {
11408: $metaentry{':partorder'}.=','.$origid;
11409: }
11410: } elsif ($origfiletagids[$index] eq 'import') {
11411: if ($importedparts) {
11412: # We have imported parts at this position
11413: $metaentry{':partorder'}.=','.$importedpartids{$origid};
11414: }
11415: if ($importedresponses) {
11416: # We have imported responses at this position
11417: if (ref($importedrespids{$origid}) eq 'ARRAY') {
11418: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
11419: }
11420: }
11421: } else {
11422: # Original response item, part of the problem
11423: if ($importedresponses) {
11424: $metaentry{':responseorder'}.=','.$origid;
11425: }
11426: }
11427: }
11428: if ($importedparts) {
11429: $metaentry{':partorder'}=~s/^\,//;
11430: }
11431: if ($importedresponses) {
11432: $metaentry{':responseorder'}=~s/^\,//;
11433: }
1.1070 www 11434: }
11435:
1.737 albertel 11436: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11437: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 11438: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11439: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11440: # this is the end of "was not already recently cached
1.71 www 11441: }
1.599 albertel 11442: return $metaentry{':'.$what};
1.261 albertel 11443: }
11444:
1.488 albertel 11445: sub metadata_create_package_def {
1.483 albertel 11446: my ($uri,$key,$package,$metathesekeys)=@_;
11447: my ($pack,$name,$subp)=split(/\&/,$key);
11448: if ($subp eq 'default') { next; }
11449:
1.599 albertel 11450: if (defined($metaentry{':packages'})) {
11451: $metaentry{':packages'}.=','.$package;
1.483 albertel 11452: } else {
1.599 albertel 11453: $metaentry{':packages'}=$package;
1.483 albertel 11454: }
11455: my $value=$packagetab{$key};
11456: my $unikey;
11457: $unikey='parameter_0_'.$name;
1.599 albertel 11458: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11459: $$metathesekeys{$unikey}=1;
1.599 albertel 11460: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11461: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11462: }
1.599 albertel 11463: if (defined($metaentry{':'.$unikey.'.default'})) {
11464: $metaentry{':'.$unikey}=
11465: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11466: }
11467: }
11468:
1.261 albertel 11469: sub metadata_generate_part0 {
11470: my ($metadata,$metacache,$uri) = @_;
11471: my %allnames;
1.737 albertel 11472: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11473: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11474: my $part=$$metacache{':'.$metakey.'.part'};
11475: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11476: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11477: $allnames{$name}=$part;
11478: }
11479: }
11480: }
11481: foreach my $name (keys(%allnames)) {
11482: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11483: my $key=":parameter_0_$name";
1.261 albertel 11484: $$metacache{"$key.part"}='0';
11485: $$metacache{"$key.name"}=$name;
1.428 albertel 11486: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11487: $allnames{$name}.'_'.$name.
11488: '.type'};
1.428 albertel 11489: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11490: '.display'};
1.644 www 11491: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11492: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11493: $$metacache{"$key.display"}=$olddis;
11494: }
1.71 www 11495: }
11496:
1.764 albertel 11497: # ------------------------------------------------------ Devalidate title cache
11498:
11499: sub devalidate_title_cache {
11500: my ($url)=@_;
11501: if (!$env{'request.course.id'}) { return; }
11502: my $symb=&symbread($url);
11503: if (!$symb) { return; }
11504: my $key=$env{'request.course.id'}."\0".$symb;
11505: &devalidate_cache_new('title',$key);
11506: }
11507:
1.1014 droeschl 11508: # ------------------------------------------------- Get the title of a course
11509:
11510: sub current_course_title {
11511: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11512: }
1.301 www 11513: # ------------------------------------------------- Get the title of a resource
11514:
11515: sub gettitle {
11516: my $urlsymb=shift;
11517: my $symb=&symbread($urlsymb);
1.534 albertel 11518: if ($symb) {
1.620 albertel 11519: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11520: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11521: if (defined($cached)) {
11522: return $result;
11523: }
1.534 albertel 11524: my ($map,$resid,$url)=&decode_symb($symb);
11525: my $title='';
1.907 albertel 11526: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11527: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11528: } else {
11529: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11530: &GDBM_READER(),0640)) {
11531: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11532: $title=$bighash{'title_'.$mapid.'.'.$resid};
11533: untie(%bighash);
11534: }
1.534 albertel 11535: }
11536: $title=~s/\&colon\;/\:/gs;
11537: if ($title) {
1.1159 www 11538: # Remember both $symb and $title for dynamic metadata
11539: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11540: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11541: # Cache this title and then return it
1.599 albertel 11542: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11543: }
11544: $urlsymb=$url;
11545: }
11546: my $title=&metadata($urlsymb,'title');
11547: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11548: return $title;
1.301 www 11549: }
1.613 albertel 11550:
1.614 albertel 11551: sub get_slot {
11552: my ($which,$cnum,$cdom)=@_;
11553: if (!$cnum || !$cdom) {
1.790 albertel 11554: (undef,my $courseid)=&whichuser();
1.620 albertel 11555: $cdom=$env{'course.'.$courseid.'.domain'};
11556: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11557: }
1.703 albertel 11558: my $key=join("\0",'slots',$cdom,$cnum,$which);
11559: my %slotinfo;
11560: if (exists($remembered{$key})) {
11561: $slotinfo{$which} = $remembered{$key};
11562: } else {
11563: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11564: &Apache::lonhomework::showhash(%slotinfo);
11565: my ($tmp)=keys(%slotinfo);
11566: if ($tmp=~/^error:/) { return (); }
11567: $remembered{$key} = $slotinfo{$which};
11568: }
1.616 albertel 11569: if (ref($slotinfo{$which}) eq 'HASH') {
11570: return %{$slotinfo{$which}};
11571: }
11572: return $slotinfo{$which};
1.614 albertel 11573: }
1.1150 raeburn 11574:
11575: sub get_reservable_slots {
11576: my ($cnum,$cdom,$uname,$udom) = @_;
11577: my $now = time;
11578: my $reservable_info;
11579: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11580: if (exists($remembered{$key})) {
11581: $reservable_info = $remembered{$key};
11582: } else {
11583: my %resv;
11584: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11585: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11586: $reservable_info = \%resv;
11587: $remembered{$key} = $reservable_info;
11588: }
11589: return $reservable_info;
11590: }
11591:
11592: sub get_course_slots {
11593: my ($cnum,$cdom) = @_;
11594: my $hashid=$cnum.':'.$cdom;
11595: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11596: if (defined($cached)) {
11597: if (ref($result) eq 'HASH') {
11598: return %{$result};
11599: }
11600: } else {
11601: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11602: my ($tmp) = keys(%slots);
11603: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11604: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11605: return %slots;
11606: }
11607: }
11608: return;
11609: }
11610:
11611: sub devalidate_slots_cache {
11612: my ($cnum,$cdom)=@_;
11613: my $hashid=$cnum.':'.$cdom;
11614: &devalidate_cache_new('allslots',$hashid);
11615: }
11616:
1.1172.2.8 raeburn 11617: sub get_coursechange {
11618: my ($cdom,$cnum) = @_;
11619: if ($cdom eq '' || $cnum eq '') {
11620: return unless ($env{'request.course.id'});
11621: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11622: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11623: }
11624: my $hashid=$cdom.'_'.$cnum;
11625: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11626: if ((defined($cached)) && ($change ne '')) {
11627: return $change;
11628: } else {
11629: my %crshash;
11630: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11631: if ($crshash{'internal.contentchange'} eq '') {
11632: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11633: if ($change eq '') {
11634: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11635: $change = $crshash{'internal.created'};
11636: }
11637: } else {
11638: $change = $crshash{'internal.contentchange'};
11639: }
11640: my $cachetime = 600;
11641: &do_cache_new('crschange',$hashid,$change,$cachetime);
11642: }
11643: return $change;
11644: }
11645:
11646: sub devalidate_coursechange_cache {
11647: my ($cnum,$cdom)=@_;
11648: my $hashid=$cnum.':'.$cdom;
11649: &devalidate_cache_new('crschange',$hashid);
11650: }
11651:
1.31 www 11652: # ------------------------------------------------- Update symbolic store links
11653:
11654: sub symblist {
11655: my ($mapname,%newhash)=@_;
1.438 www 11656: $mapname=&deversion(&declutter($mapname));
1.31 www 11657: my %hash;
1.620 albertel 11658: if (($env{'request.course.fn'}) && (%newhash)) {
11659: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11660: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11661: foreach my $url (keys(%newhash)) {
1.711 albertel 11662: next if ($url eq 'last_known'
11663: && $env{'form.no_update_last_known'});
11664: $hash{declutter($url)}=&encode_symb($mapname,
11665: $newhash{$url}->[1],
11666: $newhash{$url}->[0]);
1.191 harris41 11667: }
1.31 www 11668: if (untie(%hash)) {
11669: return 'ok';
11670: }
11671: }
11672: }
11673: return 'error';
1.212 www 11674: }
11675:
11676: # --------------------------------------------------------------- Verify a symb
11677:
11678: sub symbverify {
1.1172.2.11 raeburn 11679: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11680: my $thisfn=$thisurl;
1.439 www 11681: $thisfn=&declutter($thisfn);
1.215 www 11682: # direct jump to resource in page or to a sequence - will construct own symbs
11683: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11684: # check URL part
1.409 www 11685: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11686:
1.431 www 11687: unless ($url eq $thisfn) { return 0; }
1.213 www 11688:
1.216 www 11689: $symb=&symbclean($symb);
1.510 www 11690: $thisurl=&deversion($thisurl);
1.439 www 11691: $thisfn=&deversion($thisfn);
1.213 www 11692:
11693: my %bighash;
11694: my $okay=0;
1.431 www 11695:
1.620 albertel 11696: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11697: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11698: my $noclutter;
1.1032 raeburn 11699: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11700: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11701: if ($map =~ m{^uploaded/.+\.page$}) {
11702: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11703: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11704: $noclutter = 1;
11705: }
11706: }
11707: my $ids;
11708: if ($noclutter) {
11709: $ids=$bighash{'ids_'.$thisurl};
11710: } else {
11711: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11712: }
1.1102 raeburn 11713: unless ($ids) {
1.1172.2.13 raeburn 11714: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11715: $ids=$bighash{$idkey};
1.216 www 11716: }
11717: if ($ids) {
11718: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11719: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11720: $symb =~ s/\?.+$//;
11721: }
1.800 albertel 11722: foreach my $id (split(/\,/,$ids)) {
11723: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11724: if (
11725: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11726: eq $symb) {
1.1172.2.11 raeburn 11727: if (ref($encstate)) {
11728: $$encstate = $bighash{'encrypted_'.$id};
11729: }
1.1172.2.13 raeburn 11730: if (($env{'request.role.adv'}) ||
11731: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11732: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11733: $okay=1;
11734: last;
11735: }
11736: }
11737: }
1.216 www 11738: }
1.213 www 11739: untie(%bighash);
11740: }
11741: return $okay;
1.31 www 11742: }
11743:
1.210 www 11744: # --------------------------------------------------------------- Clean-up symb
11745:
11746: sub symbclean {
11747: my $symb=shift;
1.568 albertel 11748: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11749: # remove version from map
11750: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11751:
1.210 www 11752: # remove version from URL
11753: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11754:
1.507 www 11755: # remove wrapper
11756:
1.510 www 11757: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11758: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11759: return $symb;
1.409 www 11760: }
11761:
11762: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11763:
11764: sub encode_symb {
11765: my ($map,$resid,$url)=@_;
11766: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11767: }
1.409 www 11768:
11769: sub decode_symb {
1.568 albertel 11770: my $symb=shift;
11771: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11772: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11773: return (&fixversion($map),$resid,&fixversion($url));
11774: }
11775:
11776: sub fixversion {
11777: my $fn=shift;
1.609 banghart 11778: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11779: my %bighash;
11780: my $uri=&clutter($fn);
1.620 albertel 11781: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11782: # is this cached?
1.599 albertel 11783: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11784: if (defined($cached)) { return $result; }
11785: # unfortunately not cached, or expired
1.620 albertel 11786: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11787: &GDBM_READER(),0640)) {
11788: if ($bighash{'version_'.$uri}) {
11789: my $version=$bighash{'version_'.$uri};
1.444 www 11790: unless (($version eq 'mostrecent') ||
11791: ($version==&getversion($uri))) {
1.440 www 11792: $uri=~s/\.(\w+)$/\.$version\.$1/;
11793: }
11794: }
11795: untie %bighash;
1.413 www 11796: }
1.599 albertel 11797: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11798: }
11799:
11800: sub deversion {
11801: my $url=shift;
11802: $url=~s/\.\d+\.(\w+)$/\.$1/;
11803: return $url;
1.210 www 11804: }
11805:
1.31 www 11806: # ------------------------------------------------------ Return symb list entry
11807:
11808: sub symbread {
1.1172.2.66 raeburn 11809: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11810: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11811: if (defined($env{$cache_str})) {
11812: if ($ignorecachednull) {
11813: return $env{$cache_str} unless ($env{$cache_str} eq '');
11814: } else {
11815: return $env{$cache_str};
11816: }
11817: }
1.242 www 11818: # no filename provided? try from environment
1.1172.2.54 raeburn 11819: unless ($thisfn) {
1.620 albertel 11820: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11821: return $env{$cache_str}=&symbclean($env{'request.symb'});
11822: }
11823: $thisfn=$env{'request.filename'};
1.44 www 11824: }
1.569 albertel 11825: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11826: # is that filename actually a symb? Verify, clean, and return
11827: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11828: if (&symbverify($thisfn,$1)) {
1.620 albertel 11829: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11830: }
1.242 www 11831: }
1.44 www 11832: $thisfn=declutter($thisfn);
1.31 www 11833: my %hash;
1.37 www 11834: my %bighash;
11835: my $syval='';
1.620 albertel 11836: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11837: my $targetfn = $thisfn;
1.609 banghart 11838: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11839: $targetfn = 'adm/wrapper/'.$thisfn;
11840: }
1.687 albertel 11841: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11842: $targetfn=$1;
11843: }
1.620 albertel 11844: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11845: &GDBM_READER(),0640)) {
1.481 raeburn 11846: $syval=$hash{$targetfn};
1.37 www 11847: untie(%hash);
11848: }
11849: # ---------------------------------------------------------- There was an entry
11850: if ($syval) {
1.601 albertel 11851: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11852: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11853: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11854: #return $env{$cache_str}='';
1.601 albertel 11855: #}
11856: #$syval.=$1;
11857: #}
1.37 www 11858: } else {
11859: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11860: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11861: &GDBM_READER(),0640)) {
1.37 www 11862: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11863: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11864: unless ($ids) {
11865: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11866: }
11867: unless ($ids) {
11868: # alias?
11869: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11870: }
1.37 www 11871: if ($ids) {
11872: # ------------------------------------------------------------------- Has ID(s)
11873: my @possibilities=split(/\,/,$ids);
1.39 www 11874: if ($#possibilities==0) {
11875: # ----------------------------------------------- There is only one possibility
1.37 www 11876: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11877: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11878: $resid,$thisfn);
1.1172.2.66 raeburn 11879: if (ref($possibles) eq 'HASH') {
11880: $possibles->{$syval} = 1;
11881: }
11882: if ($checkforblock) {
11883: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11884: if (@blockers) {
11885: $syval = '';
11886: return;
11887: }
11888: }
11889: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11890: # ------------------------------------------ There is more than one possibility
11891: my $realpossible=0;
1.800 albertel 11892: foreach my $id (@possibilities) {
11893: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11894: my $canaccess;
11895: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11896: $canaccess = 1;
11897: } else {
11898: $canaccess = &allowed('bre',$file);
11899: }
11900: if ($canaccess) {
11901: my ($mapid,$resid)=split(/\./,$id);
11902: if ($bighash{'map_type_'.$mapid} ne 'page') {
11903: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11904: $resid,$thisfn);
11905: if (ref($possibles) eq 'HASH') {
11906: $possibles->{$syval} = 1;
11907: }
11908: if ($checkforblock) {
11909: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11910: unless (@blockers > 0) {
11911: $syval = $poss_syval;
11912: $realpossible++;
11913: }
11914: } else {
11915: $syval = $poss_syval;
11916: $realpossible++;
11917: }
11918: }
1.39 www 11919: }
1.191 harris41 11920: }
1.39 www 11921: if ($realpossible!=1) { $syval=''; }
1.249 www 11922: } else {
11923: $syval='';
1.37 www 11924: }
11925: }
1.1172.2.66 raeburn 11926: untie(%bighash);
1.481 raeburn 11927: }
1.31 www 11928: }
1.62 www 11929: if ($syval) {
1.620 albertel 11930: return $env{$cache_str}=$syval;
1.62 www 11931: }
1.31 www 11932: }
1.949 raeburn 11933: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11934: return $env{$cache_str}='';
1.31 www 11935: }
11936:
11937: # ---------------------------------------------------------- Return random seed
11938:
1.32 www 11939: sub numval {
11940: my $txt=shift;
11941: $txt=~tr/A-J/0-9/;
11942: $txt=~tr/a-j/0-9/;
11943: $txt=~tr/K-T/0-9/;
11944: $txt=~tr/k-t/0-9/;
11945: $txt=~tr/U-Z/0-5/;
11946: $txt=~tr/u-z/0-5/;
11947: $txt=~s/\D//g;
1.564 albertel 11948: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11949: return int($txt);
1.368 albertel 11950: }
11951:
1.484 albertel 11952: sub numval2 {
11953: my $txt=shift;
11954: $txt=~tr/A-J/0-9/;
11955: $txt=~tr/a-j/0-9/;
11956: $txt=~tr/K-T/0-9/;
11957: $txt=~tr/k-t/0-9/;
11958: $txt=~tr/U-Z/0-5/;
11959: $txt=~tr/u-z/0-5/;
11960: $txt=~s/\D//g;
11961: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11962: my $total;
11963: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11964: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11965: return int($total);
11966: }
11967:
1.575 albertel 11968: sub numval3 {
11969: use integer;
11970: my $txt=shift;
11971: $txt=~tr/A-J/0-9/;
11972: $txt=~tr/a-j/0-9/;
11973: $txt=~tr/K-T/0-9/;
11974: $txt=~tr/k-t/0-9/;
11975: $txt=~tr/U-Z/0-5/;
11976: $txt=~tr/u-z/0-5/;
11977: $txt=~s/\D//g;
11978: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11979: my $total;
11980: foreach my $val (@txts) { $total+=$val; }
11981: if ($_64bit) { $total=(($total<<32)>>32); }
11982: return $total;
11983: }
11984:
1.675 albertel 11985: sub digest {
11986: my ($data)=@_;
11987: my $digest=&Digest::MD5::md5($data);
11988: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11989: my ($e,$f);
11990: {
11991: use integer;
11992: $e=($a+$b);
11993: $f=($c+$d);
11994: if ($_64bit) {
11995: $e=(($e<<32)>>32);
11996: $f=(($f<<32)>>32);
11997: }
11998: }
11999: if (wantarray) {
12000: return ($e,$f);
12001: } else {
12002: my $g;
12003: {
12004: use integer;
12005: $g=($e+$f);
12006: if ($_64bit) {
12007: $g=(($g<<32)>>32);
12008: }
12009: }
12010: return $g;
12011: }
12012: }
12013:
1.368 albertel 12014: sub latest_rnd_algorithm_id {
1.675 albertel 12015: return '64bit5';
1.366 albertel 12016: }
1.32 www 12017:
1.503 albertel 12018: sub get_rand_alg {
12019: my ($courseid)=@_;
1.790 albertel 12020: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12021: if ($courseid) {
1.620 albertel 12022: return $env{"course.$courseid.rndseed"};
1.503 albertel 12023: }
12024: return &latest_rnd_algorithm_id();
12025: }
12026:
1.562 albertel 12027: sub validCODE {
12028: my ($CODE)=@_;
12029: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12030: return 0;
12031: }
12032:
1.491 albertel 12033: sub getCODE {
1.620 albertel 12034: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12035: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12036: defined($Apache::lonhomework::parsing_a_task) ) &&
12037: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12038: return $Apache::lonhomework::history{'resource.CODE'};
12039: }
12040: return undef;
12041: }
1.1133 foxr 12042: #
12043: # Determines the random seed for a specific context:
12044: #
12045: # parameters:
12046: # symb - in course context the symb for the seed.
12047: # course_id - The course id of the form domain_coursenum.
12048: # domain - Domain for the user.
12049: # course - Course for the user.
12050: # cenv - environment of the course.
12051: #
12052: # NOTE:
12053: # All parameters are picked out of the environment if missing
12054: # or not defined.
12055: # If a symb cannot be determined the current time is used instead.
12056: #
12057: # For a given well defined symb, courside, domain, username,
12058: # and course environment, the seed is reproducible.
12059: #
1.31 www 12060: sub rndseed {
1.1133 foxr 12061: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12062: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12063: if (!defined($symb)) {
1.366 albertel 12064: unless ($symb=$wsymb) { return time; }
12065: }
1.1146 foxr 12066: if (!defined $courseid) {
12067: $courseid=$wcourseid;
12068: }
12069: if (!defined $domain) { $domain=$wdomain; }
12070: if (!defined $username) { $username=$wusername }
1.1133 foxr 12071:
12072: my $which;
12073: if (defined($cenv->{'rndseed'})) {
12074: $which = $cenv->{'rndseed'};
12075: } else {
12076: $which =&get_rand_alg($courseid);
12077: }
1.491 albertel 12078: if (defined(&getCODE())) {
1.675 albertel 12079: if ($which eq '64bit5') {
12080: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12081: } elsif ($which eq '64bit4') {
1.575 albertel 12082: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12083: } else {
12084: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12085: }
1.675 albertel 12086: } elsif ($which eq '64bit5') {
12087: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12088: } elsif ($which eq '64bit4') {
12089: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12090: } elsif ($which eq '64bit3') {
12091: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12092: } elsif ($which eq '64bit2') {
12093: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12094: } elsif ($which eq '64bit') {
12095: return &rndseed_64bit($symb,$courseid,$domain,$username);
12096: }
12097: return &rndseed_32bit($symb,$courseid,$domain,$username);
12098: }
12099:
12100: sub rndseed_32bit {
12101: my ($symb,$courseid,$domain,$username)=@_;
12102: {
12103: use integer;
12104: my $symbchck=unpack("%32C*",$symb) << 27;
12105: my $symbseed=numval($symb) << 22;
12106: my $namechck=unpack("%32C*",$username) << 17;
12107: my $nameseed=numval($username) << 12;
12108: my $domainseed=unpack("%32C*",$domain) << 7;
12109: my $courseseed=unpack("%32C*",$courseid);
12110: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12111: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12112: #&logthis("rndseed :$num:$symb");
1.564 albertel 12113: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12114: return $num;
12115: }
12116: }
12117:
12118: sub rndseed_64bit {
12119: my ($symb,$courseid,$domain,$username)=@_;
12120: {
12121: use integer;
12122: my $symbchck=unpack("%32S*",$symb) << 21;
12123: my $symbseed=numval($symb) << 10;
12124: my $namechck=unpack("%32S*",$username);
12125:
12126: my $nameseed=numval($username) << 21;
12127: my $domainseed=unpack("%32S*",$domain) << 10;
12128: my $courseseed=unpack("%32S*",$courseid);
12129:
12130: my $num1=$symbchck+$symbseed+$namechck;
12131: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12132: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12133: #&logthis("rndseed :$num:$symb");
1.564 albertel 12134: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12135: return "$num1,$num2";
1.155 albertel 12136: }
1.366 albertel 12137: }
12138:
1.443 albertel 12139: sub rndseed_64bit2 {
12140: my ($symb,$courseid,$domain,$username)=@_;
12141: {
12142: use integer;
12143: # strings need to be an even # of cahracters long, it it is odd the
12144: # last characters gets thrown away
12145: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12146: my $symbseed=numval($symb) << 10;
12147: my $namechck=unpack("%32S*",$username.' ');
12148:
12149: my $nameseed=numval($username) << 21;
1.501 albertel 12150: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12151: my $courseseed=unpack("%32S*",$courseid.' ');
12152:
12153: my $num1=$symbchck+$symbseed+$namechck;
12154: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12155: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12156: #&logthis("rndseed :$num:$symb");
1.803 albertel 12157: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12158: return "$num1,$num2";
12159: }
12160: }
12161:
12162: sub rndseed_64bit3 {
12163: my ($symb,$courseid,$domain,$username)=@_;
12164: {
12165: use integer;
12166: # strings need to be an even # of cahracters long, it it is odd the
12167: # last characters gets thrown away
12168: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12169: my $symbseed=numval2($symb) << 10;
12170: my $namechck=unpack("%32S*",$username.' ');
12171:
12172: my $nameseed=numval2($username) << 21;
1.443 albertel 12173: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12174: my $courseseed=unpack("%32S*",$courseid.' ');
12175:
12176: my $num1=$symbchck+$symbseed+$namechck;
12177: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12178: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12179: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12180: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12181:
1.503 albertel 12182: return "$num1:$num2";
1.443 albertel 12183: }
12184: }
12185:
1.575 albertel 12186: sub rndseed_64bit4 {
12187: my ($symb,$courseid,$domain,$username)=@_;
12188: {
12189: use integer;
12190: # strings need to be an even # of cahracters long, it it is odd the
12191: # last characters gets thrown away
12192: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12193: my $symbseed=numval3($symb) << 10;
12194: my $namechck=unpack("%32S*",$username.' ');
12195:
12196: my $nameseed=numval3($username) << 21;
12197: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12198: my $courseseed=unpack("%32S*",$courseid.' ');
12199:
12200: my $num1=$symbchck+$symbseed+$namechck;
12201: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12202: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12203: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12204: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12205:
1.575 albertel 12206: return "$num1:$num2";
12207: }
12208: }
12209:
1.675 albertel 12210: sub rndseed_64bit5 {
12211: my ($symb,$courseid,$domain,$username)=@_;
12212: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12213: return "$num1:$num2";
12214: }
12215:
1.366 albertel 12216: sub rndseed_CODE_64bit {
12217: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12218: {
1.366 albertel 12219: use integer;
1.443 albertel 12220: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12221: my $symbseed=numval2($symb);
1.491 albertel 12222: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12223: my $CODEseed=numval(&getCODE());
1.443 albertel 12224: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12225: my $num1=$symbseed+$CODEchck;
12226: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12227: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12228: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12229: if ($_64bit) { $num1=(($num1<<32)>>32); }
12230: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12231: return "$num1:$num2";
1.366 albertel 12232: }
12233: }
12234:
1.575 albertel 12235: sub rndseed_CODE_64bit4 {
12236: my ($symb,$courseid,$domain,$username)=@_;
12237: {
12238: use integer;
12239: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12240: my $symbseed=numval3($symb);
12241: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12242: my $CODEseed=numval3(&getCODE());
12243: my $courseseed=unpack("%32S*",$courseid.' ');
12244: my $num1=$symbseed+$CODEchck;
12245: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12246: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12247: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12248: if ($_64bit) { $num1=(($num1<<32)>>32); }
12249: if ($_64bit) { $num2=(($num2<<32)>>32); }
12250: return "$num1:$num2";
12251: }
12252: }
12253:
1.675 albertel 12254: sub rndseed_CODE_64bit5 {
12255: my ($symb,$courseid,$domain,$username)=@_;
12256: my $code = &getCODE();
12257: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12258: return "$num1:$num2";
12259: }
12260:
1.366 albertel 12261: sub setup_random_from_rndseed {
12262: my ($rndseed)=@_;
1.503 albertel 12263: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 12264: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12265: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12266: &Math::Random::random_set_seed_from_phrase($rndseed);
12267: } else {
12268: &Math::Random::random_set_seed($num1,$num2);
12269: }
1.366 albertel 12270: } else {
12271: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12272: }
1.36 albertel 12273: }
12274:
1.474 albertel 12275: sub latest_receipt_algorithm_id {
1.835 albertel 12276: return 'receipt3';
1.474 albertel 12277: }
12278:
1.480 www 12279: sub recunique {
12280: my $fucourseid=shift;
12281: my $unique;
1.835 albertel 12282: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12283: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12284: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12285: } else {
12286: $unique=$perlvar{'lonReceipt'};
12287: }
12288: return unpack("%32C*",$unique);
12289: }
12290:
12291: sub recprefix {
12292: my $fucourseid=shift;
12293: my $prefix;
1.835 albertel 12294: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12295: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12296: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12297: } else {
12298: $prefix=$perlvar{'lonHostID'};
12299: }
12300: return unpack("%32C*",$prefix);
12301: }
12302:
1.76 www 12303: sub ireceipt {
1.474 albertel 12304: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12305:
12306: my $return =&recprefix($fucourseid).'-';
12307:
12308: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12309: $env{'request.state'} eq 'construct') {
12310: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12311: return $return;
12312: }
12313:
1.76 www 12314: my $cuname=unpack("%32C*",$funame);
12315: my $cudom=unpack("%32C*",$fudom);
12316: my $cucourseid=unpack("%32C*",$fucourseid);
12317: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12318: my $cunique=&recunique($fucourseid);
1.474 albertel 12319: my $cpart=unpack("%32S*",$part);
1.835 albertel 12320: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12321:
1.790 albertel 12322: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12323:
12324: $return.= ($cunique%$cuname+
12325: $cunique%$cudom+
12326: $cusymb%$cuname+
12327: $cusymb%$cudom+
12328: $cucourseid%$cuname+
12329: $cucourseid%$cudom+
12330: $cpart%$cuname+
12331: $cpart%$cudom);
12332: } else {
12333: $return.= ($cunique%$cuname+
12334: $cunique%$cudom+
12335: $cusymb%$cuname+
12336: $cusymb%$cudom+
12337: $cucourseid%$cuname+
12338: $cucourseid%$cudom);
12339: }
12340: return $return;
1.76 www 12341: }
12342:
12343: sub receipt {
1.474 albertel 12344: my ($part)=@_;
1.790 albertel 12345: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12346: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12347: }
1.260 ng 12348:
1.790 albertel 12349: sub whichuser {
12350: my ($passedsymb)=@_;
12351: my ($symb,$courseid,$domain,$name,$publicuser);
12352: if (defined($env{'form.grade_symb'})) {
12353: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12354: my $allowed=&allowed('vgr',$tmp_courseid);
12355: if (!$allowed &&
12356: exists($env{'request.course.sec'}) &&
12357: $env{'request.course.sec'} !~ /^\s*$/) {
12358: $allowed=&allowed('vgr',$tmp_courseid.
12359: '/'.$env{'request.course.sec'});
12360: }
12361: if ($allowed) {
12362: ($symb)=&get_env_multiple('form.grade_symb');
12363: $courseid=$tmp_courseid;
12364: ($domain)=&get_env_multiple('form.grade_domain');
12365: ($name)=&get_env_multiple('form.grade_username');
12366: return ($symb,$courseid,$domain,$name,$publicuser);
12367: }
12368: }
12369: if (!$passedsymb) {
12370: $symb=&symbread();
12371: } else {
12372: $symb=$passedsymb;
12373: }
12374: $courseid=$env{'request.course.id'};
12375: $domain=$env{'user.domain'};
12376: $name=$env{'user.name'};
12377: if ($name eq 'public' && $domain eq 'public') {
12378: if (!defined($env{'form.username'})) {
12379: $env{'form.username'}.=time.rand(10000000);
12380: }
12381: $name.=$env{'form.username'};
12382: }
12383: return ($symb,$courseid,$domain,$name,$publicuser);
12384:
12385: }
12386:
1.36 albertel 12387: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12388: # returns either the contents of the file or
12389: # -1 if the file doesn't exist
1.481 raeburn 12390: #
12391: # if the target is a file that was uploaded via DOCS,
12392: # a check will be made to see if a current copy exists on the local server,
12393: # if it does this will be served, otherwise a copy will be retrieved from
12394: # the home server for the course and stored in /home/httpd/html/userfiles on
12395: # the local server.
1.472 albertel 12396:
1.36 albertel 12397: sub getfile {
1.538 albertel 12398: my ($file) = @_;
1.609 banghart 12399: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12400: &repcopy($file);
12401: return &readfile($file);
12402: }
12403:
12404: sub repcopy_userfile {
12405: my ($file)=@_;
1.1142 raeburn 12406: my $londocroot = $perlvar{'lonDocRoot'};
12407: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12408: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12409: my ($cdom,$cnum,$filename) =
1.811 albertel 12410: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12411: my $uri="/uploaded/$cdom/$cnum/$filename";
12412: if (-e "$file") {
1.828 www 12413: # we already have a local copy, check it out
1.538 albertel 12414: my @fileinfo = stat($file);
1.828 www 12415: my $rtncode;
12416: my $info;
1.538 albertel 12417: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12418: if ($lwpresp ne 'ok') {
1.828 www 12419: # there is no such file anymore, even though we had a local copy
1.482 albertel 12420: if ($rtncode eq '404') {
1.538 albertel 12421: unlink($file);
1.482 albertel 12422: }
12423: return -1;
12424: }
12425: if ($info < $fileinfo[9]) {
1.828 www 12426: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12427: return 'ok';
1.828 www 12428: } else {
12429: # the file is outdated, get rid of it
12430: unlink($file);
1.482 albertel 12431: }
1.828 www 12432: }
12433: # one way or the other, at this point, we don't have the file
12434: # construct the correct path for the file
12435: my @parts = ($cdom,$cnum);
12436: if ($filename =~ m|^(.+)/[^/]+$|) {
12437: push @parts, split(/\//,$1);
12438: }
12439: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12440: foreach my $part (@parts) {
12441: $path .= '/'.$part;
12442: if (!-e $path) {
12443: mkdir($path,0770);
1.482 albertel 12444: }
12445: }
1.828 www 12446: # now the path exists for sure
12447: # get a user agent
12448: my $ua=new LWP::UserAgent;
12449: my $transferfile=$file.'.in.transfer';
12450: # FIXME: this should flock
12451: if (-e $transferfile) { return 'ok'; }
12452: my $request;
12453: $uri=~s/^\///;
1.980 raeburn 12454: my $homeserver = &homeserver($cnum,$cdom);
12455: my $protocol = $protocol{$homeserver};
12456: $protocol = 'http' if ($protocol ne 'https');
12457: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12458: my $response=$ua->request($request,$transferfile);
12459: # did it work?
12460: if ($response->is_error()) {
12461: unlink($transferfile);
12462: &logthis("Userfile repcopy failed for $uri");
12463: return -1;
12464: }
12465: # worked, rename the transfer file
12466: rename($transferfile,$file);
1.607 raeburn 12467: return 'ok';
1.481 raeburn 12468: }
12469:
1.517 albertel 12470: sub tokenwrapper {
12471: my $uri=shift;
1.980 raeburn 12472: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12473: $uri=~s|^/||;
1.620 albertel 12474: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12475: my $token=$1;
1.552 albertel 12476: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12477: if ($udom && $uname && $file) {
12478: $file=~s|(\?\.*)*$||;
1.949 raeburn 12479: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12480: my $homeserver = &homeserver($uname,$udom);
12481: my $protocol = $protocol{$homeserver};
12482: $protocol = 'http' if ($protocol ne 'https');
12483: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12484: (($uri=~/\?/)?'&':'?').'token='.$token.
12485: '&tokenissued='.$perlvar{'lonHostID'};
12486: } else {
12487: return '/adm/notfound.html';
12488: }
12489: }
12490:
1.828 www 12491: # call with reqtype HEAD: get last modification time
12492: # call with reqtype GET: get the file contents
12493: # Do not call this with reqtype GET for large files! It loads everything into memory
12494: #
1.481 raeburn 12495: sub getuploaded {
12496: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12497: $uri=~s/^\///;
1.980 raeburn 12498: my $homeserver = &homeserver($cnum,$cdom);
12499: my $protocol = $protocol{$homeserver};
12500: $protocol = 'http' if ($protocol ne 'https');
12501: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12502: my $ua=new LWP::UserAgent;
12503: my $request=new HTTP::Request($reqtype,$uri);
12504: my $response=$ua->request($request);
12505: $$rtncode = $response->code;
1.482 albertel 12506: if (! $response->is_success()) {
12507: return 'failed';
12508: }
12509: if ($reqtype eq 'HEAD') {
1.486 www 12510: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12511: } elsif ($reqtype eq 'GET') {
12512: $$info = $response->content;
1.472 albertel 12513: }
1.482 albertel 12514: return 'ok';
1.36 albertel 12515: }
12516:
1.481 raeburn 12517: sub readfile {
12518: my $file = shift;
12519: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12520: my $fh;
1.1172.2.96 raeburn 12521: open($fh,"<",$file);
1.481 raeburn 12522: my $a='';
1.800 albertel 12523: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12524: return $a;
12525: }
12526:
1.36 albertel 12527: sub filelocation {
1.590 banghart 12528: my ($dir,$file) = @_;
12529: my $location;
12530: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12531:
12532: if ($file =~ m-^/adm/-) {
12533: $file=~s-^/adm/wrapper/-/-;
12534: $file=~s-^/adm/coursedocs/showdoc/-/-;
12535: }
1.882 albertel 12536:
1.1139 www 12537: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12538: $location = $file;
1.609 banghart 12539: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12540: my ($udom,$uname,$filename)=
1.811 albertel 12541: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12542: my $home=&homeserver($uname,$udom);
12543: my $is_me=0;
12544: my @ids=¤t_machine_ids();
12545: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12546: if ($is_me) {
1.1117 foxr 12547: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12548: } else {
12549: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12550: $udom.'/'.$uname.'/'.$filename;
12551: }
1.882 albertel 12552: } elsif ($file =~ m-^/adm/-) {
12553: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12554: } else {
12555: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12556: $file=~s:^/(res|priv)/:/:;
12557: my $space=$1;
1.590 banghart 12558: if ( !( $file =~ m:^/:) ) {
12559: $location = $dir. '/'.$file;
12560: } else {
1.1142 raeburn 12561: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12562: }
1.59 albertel 12563: }
1.590 banghart 12564: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12565: while ($location=~m{/\.\./}) {
12566: if ($location =~ m{/[^/]+/\.\./}) {
12567: $location=~ s{/[^/]+/\.\./}{/}g;
12568: } else {
12569: $location=~ s{/\.\./}{/}g;
12570: }
12571: } #remove dir/..
1.590 banghart 12572: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12573: return $location;
1.46 www 12574: }
1.36 albertel 12575:
1.46 www 12576: sub hreflocation {
12577: my ($dir,$file)=@_;
1.980 raeburn 12578: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12579: $file=filelocation($dir,$file);
1.700 albertel 12580: } elsif ($file=~m-^/adm/-) {
12581: $file=~s-^/adm/wrapper/-/-;
12582: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12583: }
12584: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12585: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12586: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12587: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12588: {/uploaded/$1/$2/}x;
1.46 www 12589: }
1.913 albertel 12590: if ($file=~ m{^/userfiles/}) {
12591: $file =~ s{^/userfiles/}{/uploaded/};
12592: }
1.462 albertel 12593: return $file;
1.465 albertel 12594: }
12595:
1.1139 www 12596:
12597:
12598:
12599:
1.465 albertel 12600: sub current_machine_domains {
1.853 albertel 12601: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12602: }
12603:
12604: sub machine_domains {
12605: my ($hostname) = @_;
1.465 albertel 12606: my @domains;
1.838 albertel 12607: my %hostname = &all_hostnames();
1.465 albertel 12608: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12609: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12610: if ($hostname eq $name) {
1.844 albertel 12611: push(@domains,&host_domain($id));
1.465 albertel 12612: }
12613: }
12614: return @domains;
12615: }
12616:
12617: sub current_machine_ids {
1.853 albertel 12618: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12619: }
12620:
12621: sub machine_ids {
12622: my ($hostname) = @_;
12623: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12624: my @ids;
1.888 albertel 12625: my %name_to_host = &all_names();
1.889 albertel 12626: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12627: return @{ $name_to_host{$hostname} };
12628: }
12629: return;
1.31 www 12630: }
12631:
1.824 raeburn 12632: sub additional_machine_domains {
12633: my @domains;
1.1172.2.96 raeburn 12634: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 12635: while( my $line = <$fh>) {
12636: $line =~ s/\s//g;
12637: push(@domains,$line);
12638: }
12639: return @domains;
12640: }
12641:
12642: sub default_login_domain {
12643: my $domain = $perlvar{'lonDefDomain'};
12644: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12645: foreach my $posdom (¤t_machine_domains(),
12646: &additional_machine_domains()) {
12647: if (lc($posdom) eq lc($testdomain)) {
12648: $domain=$posdom;
12649: last;
12650: }
12651: }
12652: return $domain;
12653: }
12654:
1.31 www 12655: # ------------------------------------------------------------- Declutters URLs
12656:
12657: sub declutter {
12658: my $thisfn=shift;
1.569 albertel 12659: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12660: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12661: $thisfn=~s{^/home/httpd/html}{};
12662: }
1.31 www 12663: $thisfn=~s/^\///;
1.697 albertel 12664: $thisfn=~s|^adm/wrapper/||;
12665: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12666: $thisfn=~s/^res\///;
1.1172 bisitz 12667: $thisfn=~s/^priv\///;
1.1032 raeburn 12668: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12669: $thisfn=~s/\?.+$//;
12670: }
1.268 www 12671: return $thisfn;
12672: }
12673:
12674: # ------------------------------------------------------------- Clutter up URLs
12675:
12676: sub clutter {
12677: my $thisfn='/'.&declutter(shift);
1.887 albertel 12678: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12679: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12680: $thisfn='/res'.$thisfn;
12681: }
1.1031 raeburn 12682: if ($thisfn !~m|^/adm|) {
12683: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12684: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12685: } else {
12686: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12687: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12688: if ($embstyle eq 'ssi'
12689: || ($embstyle eq 'hdn')
12690: || ($embstyle eq 'rat')
12691: || ($embstyle eq 'prv')
12692: || ($embstyle eq 'ign')) {
12693: #do nothing with these
12694: } elsif (($embstyle eq 'img')
1.695 albertel 12695: || ($embstyle eq 'emb')
12696: || ($embstyle eq 'wrp')) {
12697: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12698: } elsif ($embstyle eq 'unk'
12699: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12700: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12701: } else {
1.718 www 12702: # &logthis("Got a blank emb style");
1.695 albertel 12703: }
1.694 albertel 12704: }
12705: }
1.31 www 12706: return $thisfn;
1.12 www 12707: }
12708:
1.787 albertel 12709: sub clutter_with_no_wrapper {
12710: my $uri = &clutter(shift);
12711: if ($uri =~ m-^/adm/-) {
12712: $uri =~ s-^/adm/wrapper/-/-;
12713: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12714: }
12715: return $uri;
12716: }
12717:
1.557 albertel 12718: sub freeze_escape {
12719: my ($value)=@_;
12720: if (ref($value)) {
12721: $value=&nfreeze($value);
12722: return '__FROZEN__'.&escape($value);
12723: }
12724: return &escape($value);
12725: }
12726:
1.11 www 12727:
1.557 albertel 12728: sub thaw_unescape {
12729: my ($value)=@_;
12730: if ($value =~ /^__FROZEN__/) {
12731: substr($value,0,10,undef);
12732: $value=&unescape($value);
12733: return &thaw($value);
12734: }
12735: return &unescape($value);
12736: }
12737:
1.436 albertel 12738: sub correct_line_ends {
12739: my ($result)=@_;
12740: $$result =~s/\r\n/\n/mg;
12741: $$result =~s/\r/\n/mg;
1.415 albertel 12742: }
1.1 albertel 12743: # ================================================================ Main Program
12744:
1.184 www 12745: sub goodbye {
1.204 albertel 12746: &logthis("Starting Shut down");
1.443 albertel 12747: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12748: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12749: #converted
1.599 albertel 12750: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12751: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12752: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12753: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12754: #1.1 only
1.870 albertel 12755: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12756: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12757: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12758: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12759: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12760: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12761: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12762: &flushcourselogs();
12763: &logthis("Shutting down");
12764: }
12765:
1.852 albertel 12766: sub get_dns {
1.1172.2.17 raeburn 12767: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12768: if (!$ignore_cache) {
12769: my ($content,$cached)=
12770: &Apache::lonnet::is_cached_new('dns',$url);
12771: if ($cached) {
1.1172.2.17 raeburn 12772: &$func($content,$hashref);
1.869 albertel 12773: return;
12774: }
12775: }
12776:
12777: my %alldns;
1.1172.2.96 raeburn 12778: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
12779: foreach my $dns (<$config>) {
12780: next if ($dns !~ /^\^(\S*)/x);
12781: my $line = $1;
12782: my ($host,$protocol) = split(/:/,$line);
12783: if ($protocol ne 'https') {
12784: $protocol = 'http';
12785: }
12786: $alldns{$host} = $protocol;
1.979 raeburn 12787: }
1.1172.2.96 raeburn 12788: close($config);
1.869 albertel 12789: }
12790: while (%alldns) {
1.1172.2.52 raeburn 12791: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12792: my $ua=new LWP::UserAgent;
1.1134 raeburn 12793: $ua->timeout(30);
1.979 raeburn 12794: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12795: my $response=$ua->request($request);
1.979 raeburn 12796: delete($alldns{$dns});
1.852 albertel 12797: next if ($response->is_error());
12798: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12799: unless ($nocache) {
1.1172.2.23 raeburn 12800: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12801: }
12802: &$func(\@content,$hashref);
1.869 albertel 12803: return;
1.852 albertel 12804: }
12805: close($config);
1.871 albertel 12806: my $which = (split('/',$url))[3];
12807: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.96 raeburn 12808: open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12809: my @content = <$config>;
1.1172.2.17 raeburn 12810: &$func(\@content,$hashref);
12811: return;
12812: }
12813:
12814: # ------------------------------------------------------Get DNS checksums file
12815: sub parse_dns_checksums_tab {
12816: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12817: my $lonhost = $perlvar{'lonHostID'};
12818: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12819: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12820: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12821: my $webconfdir = '/etc/httpd/conf';
12822: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12823: $webconfdir = '/etc/apache2';
12824: } elsif ($distro =~ /^sles(\d+)$/) {
12825: if ($1 >= 10) {
12826: $webconfdir = '/etc/apache2';
12827: }
12828: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12829: if ($1 >= 10.0) {
12830: $webconfdir = '/etc/apache2';
12831: }
12832: }
1.1172.2.17 raeburn 12833: my ($release,$timestamp) = split(/\-/,$loncaparev);
12834: my (%chksum,%revnum);
12835: if (ref($lines) eq 'ARRAY') {
12836: chomp(@{$lines});
1.1172.2.34 raeburn 12837: my $version = shift(@{$lines});
12838: if ($version eq $release) {
1.1172.2.17 raeburn 12839: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12840: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12841: if ($file =~ m{^/etc/httpd/conf}) {
12842: if ($webconfdir eq '/etc/apache2') {
12843: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12844: }
12845: }
1.1172.2.34 raeburn 12846: $chksum{$file} = $shasum;
12847: $revnum{$file} = $version;
1.1172.2.17 raeburn 12848: }
12849: if (ref($hashref) eq 'HASH') {
12850: %{$hashref} = (
12851: sums => \%chksum,
12852: versions => \%revnum,
12853: );
12854: }
12855: }
12856: }
1.869 albertel 12857: return;
1.852 albertel 12858: }
1.1172.2.17 raeburn 12859:
12860: sub fetch_dns_checksums {
12861: my %checksums;
1.1172.2.34 raeburn 12862: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12863: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12864: my ($release,$timestamp) = split(/\-/,$loncaparev);
12865: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12866: \%checksums);
12867: return \%checksums;
12868: }
12869:
1.327 albertel 12870: # ------------------------------------------------------------ Read domain file
12871: {
1.852 albertel 12872: my $loaded;
1.846 albertel 12873: my %domain;
12874:
1.852 albertel 12875: sub parse_domain_tab {
12876: my ($lines) = @_;
12877: foreach my $line (@$lines) {
12878: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12879:
1.846 albertel 12880: chomp($line);
1.852 albertel 12881: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12882: my %this_domain;
12883: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12884: 'lang_def', 'city', 'longi', 'lati',
12885: 'primary') {
12886: $this_domain{$field} = shift(@elements);
12887: }
12888: $domain{$name} = \%this_domain;
1.852 albertel 12889: }
12890: }
1.864 albertel 12891:
12892: sub reset_domain_info {
12893: undef($loaded);
12894: undef(%domain);
12895: }
12896:
1.852 albertel 12897: sub load_domain_tab {
1.1172.2.70 raeburn 12898: my ($ignore_cache,$nocache) = @_;
12899: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12900: my $fh;
1.1172.2.96 raeburn 12901: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 12902: my @lines = <$fh>;
12903: &parse_domain_tab(\@lines);
1.448 albertel 12904: }
1.852 albertel 12905: close($fh);
12906: $loaded = 1;
1.327 albertel 12907: }
1.846 albertel 12908:
12909: sub domain {
1.852 albertel 12910: &load_domain_tab() if (!$loaded);
12911:
1.846 albertel 12912: my ($name,$what) = @_;
12913: return if ( !exists($domain{$name}) );
12914:
12915: if (!$what) {
12916: return $domain{$name}{'description'};
12917: }
12918: return $domain{$name}{$what};
12919: }
1.974 raeburn 12920:
12921: sub domain_info {
12922: &load_domain_tab() if (!$loaded);
12923: return %domain;
12924: }
12925:
1.327 albertel 12926: }
12927:
12928:
1.1 albertel 12929: # ------------------------------------------------------------- Read hosts file
12930: {
1.838 albertel 12931: my %hostname;
1.844 albertel 12932: my %hostdom;
1.845 albertel 12933: my %libserv;
1.852 albertel 12934: my $loaded;
1.888 albertel 12935: my %name_to_host;
1.1074 raeburn 12936: my %internetdom;
1.1107 raeburn 12937: my %LC_dns_serv;
1.852 albertel 12938:
12939: sub parse_hosts_tab {
12940: my ($file) = @_;
12941: foreach my $configline (@$file) {
12942: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12943: chomp($configline);
12944: if ($configline =~ /^\^/) {
12945: if ($configline =~ /^\^([\w.\-]+)/) {
12946: $LC_dns_serv{$1} = 1;
12947: }
12948: next;
12949: }
1.1074 raeburn 12950: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12951: $name=~s/\s//g;
12952: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 12953: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
12954: my $curr = $hostname{$id};
12955: my $skip;
12956: if (ref($name_to_host{$curr}) eq 'ARRAY') {
12957: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
12958: $skip = 1;
12959: } else {
12960: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
12961: }
12962: }
12963: unless ($skip) {
12964: push(@{$name_to_host{$name}},$id);
12965: }
12966: } else {
12967: push(@{$name_to_host{$name}},$id);
12968: }
1.852 albertel 12969: $hostname{$id}=$name;
12970: $hostdom{$id}=$domain;
12971: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12972: if (defined($protocol)) {
12973: if ($protocol eq 'https') {
12974: $protocol{$id} = $protocol;
12975: } else {
12976: $protocol{$id} = 'http';
12977: }
1.968 raeburn 12978: } else {
1.969 raeburn 12979: $protocol{$id} = 'http';
1.968 raeburn 12980: }
1.1074 raeburn 12981: if (defined($intdom)) {
12982: $internetdom{$id} = $intdom;
12983: }
1.852 albertel 12984: }
12985: }
12986: }
1.864 albertel 12987:
12988: sub reset_hosts_info {
1.897 albertel 12989: &purge_remembered();
1.864 albertel 12990: &reset_domain_info();
12991: &reset_hosts_ip_info();
1.892 albertel 12992: undef(%name_to_host);
1.864 albertel 12993: undef(%hostname);
12994: undef(%hostdom);
12995: undef(%libserv);
12996: undef($loaded);
12997: }
1.1 albertel 12998:
1.852 albertel 12999: sub load_hosts_tab {
1.1172.2.70 raeburn 13000: my ($ignore_cache,$nocache) = @_;
13001: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13002: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13003: my @config = <$config>;
13004: &parse_hosts_tab(\@config);
13005: close($config);
13006: $loaded=1;
1.1 albertel 13007: }
1.852 albertel 13008:
1.838 albertel 13009: sub hostname {
1.852 albertel 13010: &load_hosts_tab() if (!$loaded);
13011:
1.838 albertel 13012: my ($lonid) = @_;
13013: return $hostname{$lonid};
13014: }
1.845 albertel 13015:
1.838 albertel 13016: sub all_hostnames {
1.852 albertel 13017: &load_hosts_tab() if (!$loaded);
13018:
1.838 albertel 13019: return %hostname;
13020: }
1.845 albertel 13021:
1.888 albertel 13022: sub all_names {
1.1172.2.70 raeburn 13023: my ($ignore_cache,$nocache) = @_;
13024: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13025:
13026: return %name_to_host;
13027: }
13028:
1.974 raeburn 13029: sub all_host_domain {
13030: &load_hosts_tab() if (!$loaded);
13031: return %hostdom;
13032: }
13033:
1.845 albertel 13034: sub is_library {
1.852 albertel 13035: &load_hosts_tab() if (!$loaded);
13036:
1.845 albertel 13037: return exists($libserv{$_[0]});
13038: }
13039:
13040: sub all_library {
1.852 albertel 13041: &load_hosts_tab() if (!$loaded);
13042:
1.845 albertel 13043: return %libserv;
13044: }
13045:
1.1062 droeschl 13046: sub unique_library {
13047: #2x reverse removes all hostnames that appear more than once
13048: my %unique = reverse &all_library();
13049: return reverse %unique;
13050: }
13051:
1.841 albertel 13052: sub get_servers {
1.852 albertel 13053: &load_hosts_tab() if (!$loaded);
13054:
1.841 albertel 13055: my ($domain,$type) = @_;
13056: my %possible_hosts = ($type eq 'library') ? %libserv
13057: : %hostname;
13058: my %result;
1.842 albertel 13059: if (ref($domain) eq 'ARRAY') {
13060: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13061: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13062: $result{$host} = $hostname;
13063: }
13064: }
13065: } else {
13066: while ( my ($host,$hostname) = each(%possible_hosts)) {
13067: if ($hostdom{$host} eq $domain) {
13068: $result{$host} = $hostname;
13069: }
1.841 albertel 13070: }
13071: }
13072: return %result;
13073: }
1.845 albertel 13074:
1.1062 droeschl 13075: sub get_unique_servers {
13076: my %unique = reverse &get_servers(@_);
13077: return reverse %unique;
13078: }
13079:
1.844 albertel 13080: sub host_domain {
1.852 albertel 13081: &load_hosts_tab() if (!$loaded);
13082:
1.844 albertel 13083: my ($lonid) = @_;
13084: return $hostdom{$lonid};
13085: }
13086:
1.841 albertel 13087: sub all_domains {
1.852 albertel 13088: &load_hosts_tab() if (!$loaded);
13089:
1.841 albertel 13090: my %seen;
13091: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13092: return @uniq;
13093: }
1.1074 raeburn 13094:
13095: sub internet_dom {
13096: &load_hosts_tab() if (!$loaded);
13097:
13098: my ($lonid) = @_;
13099: return $internetdom{$lonid};
13100: }
1.1107 raeburn 13101:
13102: sub is_LC_dns {
13103: &load_hosts_tab() if (!$loaded);
13104:
13105: my ($hostname) = @_;
13106: return exists($LC_dns_serv{$hostname});
13107: }
13108:
1.1 albertel 13109: }
13110:
1.847 albertel 13111: {
13112: my %iphost;
1.856 albertel 13113: my %name_to_ip;
13114: my %lonid_to_ip;
1.869 albertel 13115:
1.847 albertel 13116: sub get_hosts_from_ip {
13117: my ($ip) = @_;
13118: my %iphosts = &get_iphost();
13119: if (ref($iphosts{$ip})) {
13120: return @{$iphosts{$ip}};
13121: }
13122: return;
1.839 albertel 13123: }
1.864 albertel 13124:
13125: sub reset_hosts_ip_info {
13126: undef(%iphost);
13127: undef(%name_to_ip);
13128: undef(%lonid_to_ip);
13129: }
1.856 albertel 13130:
13131: sub get_host_ip {
13132: my ($lonid) = @_;
13133: if (exists($lonid_to_ip{$lonid})) {
13134: return $lonid_to_ip{$lonid};
13135: }
13136: my $name=&hostname($lonid);
13137: my $ip = gethostbyname($name);
13138: return if (!$ip || length($ip) ne 4);
13139: $ip=inet_ntoa($ip);
13140: $name_to_ip{$name} = $ip;
13141: $lonid_to_ip{$lonid} = $ip;
13142: return $ip;
13143: }
1.847 albertel 13144:
13145: sub get_iphost {
1.1172.2.70 raeburn 13146: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13147:
1.869 albertel 13148: if (!$ignore_cache) {
13149: if (%iphost) {
13150: return %iphost;
13151: }
13152: my ($ip_info,$cached)=
13153: &Apache::lonnet::is_cached_new('iphost','iphost');
13154: if ($cached) {
13155: %iphost = %{$ip_info->[0]};
13156: %name_to_ip = %{$ip_info->[1]};
13157: %lonid_to_ip = %{$ip_info->[2]};
13158: return %iphost;
13159: }
13160: }
1.894 albertel 13161:
13162: # get yesterday's info for fallback
13163: my %old_name_to_ip;
13164: my ($ip_info,$cached)=
13165: &Apache::lonnet::is_cached_new('iphost','iphost');
13166: if ($cached) {
13167: %old_name_to_ip = %{$ip_info->[1]};
13168: }
13169:
1.1172.2.70 raeburn 13170: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13171: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13172: my $ip;
13173: if (!exists($name_to_ip{$name})) {
13174: $ip = gethostbyname($name);
13175: if (!$ip || length($ip) ne 4) {
1.894 albertel 13176: if (defined($old_name_to_ip{$name})) {
13177: $ip = $old_name_to_ip{$name};
13178: &logthis("Can't find $name defaulting to old $ip");
13179: } else {
13180: &logthis("Name $name no IP found");
13181: next;
13182: }
13183: } else {
13184: $ip=inet_ntoa($ip);
1.847 albertel 13185: }
13186: $name_to_ip{$name} = $ip;
13187: } else {
13188: $ip = $name_to_ip{$name};
1.653 albertel 13189: }
1.888 albertel 13190: foreach my $id (@{ $name_to_host{$name} }) {
13191: $lonid_to_ip{$id} = $ip;
13192: }
13193: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13194: }
1.1172.2.70 raeburn 13195: unless ($nocache) {
13196: &do_cache_new('iphost','iphost',
13197: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13198: 48*60*60);
13199: }
1.869 albertel 13200:
1.847 albertel 13201: return %iphost;
1.598 albertel 13202: }
13203:
1.992 raeburn 13204: #
13205: # Given a DNS returns the loncapa host name for that DNS
13206: #
13207: sub host_from_dns {
13208: my ($dns) = @_;
13209: my @hosts;
13210: my $ip;
13211:
1.993 raeburn 13212: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13213: $ip = $name_to_ip{$dns};
13214: }
13215: if (!$ip) {
13216: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13217: if (length($ip) == 4) {
13218: $ip = &IO::Socket::inet_ntoa($ip);
13219: }
13220: }
13221: if ($ip) {
13222: @hosts = get_hosts_from_ip($ip);
13223: return $hosts[0];
13224: }
13225: return undef;
1.986 foxr 13226: }
1.992 raeburn 13227:
1.1074 raeburn 13228: sub get_internet_names {
13229: my ($lonid) = @_;
13230: return if ($lonid eq '');
13231: my ($idnref,$cached)=
13232: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13233: if ($cached) {
13234: return $idnref;
13235: }
13236: my $ip = &get_host_ip($lonid);
13237: my @hosts = &get_hosts_from_ip($ip);
13238: my %iphost = &get_iphost();
13239: my (@idns,%seen);
13240: foreach my $id (@hosts) {
13241: my $dom = &host_domain($id);
13242: my $prim_id = &domain($dom,'primary');
13243: my $prim_ip = &get_host_ip($prim_id);
13244: next if ($seen{$prim_ip});
13245: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13246: foreach my $id (@{$iphost{$prim_ip}}) {
13247: my $intdom = &internet_dom($id);
13248: unless (grep(/^\Q$intdom\E$/,@idns)) {
13249: push(@idns,$intdom);
13250: }
13251: }
13252: }
13253: $seen{$prim_ip} = 1;
13254: }
1.1172.2.23 raeburn 13255: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13256: }
13257:
1.986 foxr 13258: }
13259:
1.1079 raeburn 13260: sub all_loncaparevs {
1.1172.2.39 raeburn 13261: 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 13262: }
13263:
1.1172.2.27 raeburn 13264: # ------------------------------------------------------- Read loncaparev table
13265: {
13266: sub load_loncaparevs {
13267: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 13268: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 13269: while (my $configline=<$config>) {
13270: chomp($configline);
13271: my ($hostid,$loncaparev)=split(/:/,$configline);
13272: $loncaparevs{$hostid}=$loncaparev;
13273: }
13274: close($config);
13275: }
13276: }
13277: }
13278: }
13279:
13280: # ----------------------------------------------------- Read serverhostID table
13281: {
13282: sub load_serverhomeIDs {
13283: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 13284: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 13285: while (my $configline=<$config>) {
13286: chomp($configline);
13287: my ($name,$id)=split(/:/,$configline);
13288: $serverhomeIDs{$name}=$id;
13289: }
13290: close($config);
13291: }
13292: }
13293: }
13294: }
13295:
13296:
1.862 albertel 13297: BEGIN {
13298:
13299: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13300: unless ($readit) {
13301: {
13302: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13303: %perlvar = (%perlvar,%{$configvars});
13304: }
13305:
13306:
1.1 albertel 13307: # ------------------------------------------------------ Read spare server file
13308: {
1.1172.2.96 raeburn 13309: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13310:
13311: while (my $configline=<$config>) {
13312: chomp($configline);
1.284 matthew 13313: if ($configline) {
1.784 albertel 13314: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13315: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13316: push(@{ $spareid{$type} }, $host);
1.1 albertel 13317: }
13318: }
1.448 albertel 13319: close($config);
1.1 albertel 13320: }
1.11 www 13321: # ------------------------------------------------------------ Read permissions
13322: {
1.1172.2.96 raeburn 13323: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13324:
13325: while (my $configline=<$config>) {
1.448 albertel 13326: chomp($configline);
13327: if ($configline) {
13328: my ($role,$perm)=split(/ /,$configline);
13329: if ($perm ne '') { $pr{$role}=$perm; }
13330: }
1.11 www 13331: }
1.448 albertel 13332: close($config);
1.11 www 13333: }
13334:
13335: # -------------------------------------------- Read plain texts for permissions
13336: {
1.1172.2.96 raeburn 13337: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13338:
13339: while (my $configline=<$config>) {
1.448 albertel 13340: chomp($configline);
13341: if ($configline) {
1.742 raeburn 13342: my ($short,@plain)=split(/:/,$configline);
13343: %{$prp{$short}} = ();
13344: if (@plain > 0) {
13345: $prp{$short}{'std'} = $plain[0];
13346: for (my $i=1; $i<@plain; $i++) {
13347: $prp{$short}{'alt'.$i} = $plain[$i];
13348: }
13349: }
1.448 albertel 13350: }
1.135 www 13351: }
1.448 albertel 13352: close($config);
1.135 www 13353: }
13354:
13355: # ---------------------------------------------------------- Read package table
13356: {
1.1172.2.96 raeburn 13357: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13358:
13359: while (my $configline=<$config>) {
1.483 albertel 13360: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13361: chomp($configline);
13362: my ($short,$plain)=split(/:/,$configline);
13363: my ($pack,$name)=split(/\&/,$short);
13364: if ($plain ne '') {
13365: $packagetab{$pack.'&'.$name.'&name'}=$name;
13366: $packagetab{$short}=$plain;
13367: }
1.11 www 13368: }
1.448 albertel 13369: close($config);
1.329 matthew 13370: }
13371:
1.1172.2.27 raeburn 13372: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 13373:
1.1172.2.27 raeburn 13374: &load_loncaparevs();
13375:
13376: # ------------------------------------------------------- Read serverhostID table
13377:
13378: &load_serverhomeIDs();
1.1074 raeburn 13379:
1.1172.2.27 raeburn 13380: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13381: {
13382: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13383: if (-e $file) {
13384: my $parser = HTML::LCParser->new($file);
13385: while (my $token = $parser->get_token()) {
13386: if ($token->[0] eq 'S') {
13387: my $item = $token->[1];
13388: my $name = $token->[2]{'name'};
13389: my $value = $token->[2]{'value'};
13390: if ($item ne '' && $name ne '' && $value ne '') {
13391: my $release = $parser->get_text();
13392: $release =~ s/(^\s*|\s*$ )//gx;
13393: $needsrelease{$item.':'.$name.':'.$value} = $release;
13394: }
13395: }
13396: }
13397: }
1.1073 raeburn 13398: }
13399:
1.1138 raeburn 13400: # ---------------------------------------------------------- Read managers table
13401: {
13402: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 13403: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 13404: while (my $configline=<$config>) {
13405: chomp($configline);
13406: next if ($configline =~ /^\#/);
13407: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13408: $managerstab{$configline} = 1;
13409: }
13410: }
13411: close($config);
13412: }
13413: }
13414: }
13415:
1.329 matthew 13416: # ------------- set up temporary directory
13417: {
1.1117 foxr 13418: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13419:
1.11 www 13420: }
13421:
1.1172.2.104! raeburn 13422: # ------------- set default texengine (domain default overrides this)
! 13423: {
! 13424: $deftex = LONCAPA::texengine();
! 13425: }
! 13426:
1.794 albertel 13427: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13428: 'compress_threshold'=> 20_000,
13429: });
1.185 www 13430:
1.281 www 13431: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13432: $dumpcount=0;
1.958 www 13433: $locknum=0;
1.22 www 13434:
1.163 harris41 13435: &logtouch();
1.672 albertel 13436: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13437: $readit=1;
1.564 albertel 13438: {
13439: use integer;
13440: my $test=(2**32)+1;
1.568 albertel 13441: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13442: &logthis(" Detected 64bit platform ($_64bit)");
13443: }
1.195 www 13444: }
1.1 albertel 13445: }
1.179 www 13446:
1.1 albertel 13447: 1;
1.191 harris41 13448: __END__
13449:
1.243 albertel 13450: =pod
13451:
1.191 harris41 13452: =head1 NAME
13453:
1.243 albertel 13454: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13455:
13456: =head1 SYNOPSIS
13457:
1.243 albertel 13458: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13459:
13460: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13461:
1.243 albertel 13462: Common parameters:
13463:
13464: =over 4
13465:
13466: =item *
13467:
13468: $uname : an internal username (if $cname expecting a course Id specifically)
13469:
13470: =item *
13471:
13472: $udom : a domain (if $cdom expecting a course's domain specifically)
13473:
13474: =item *
13475:
13476: $symb : a resource instance identifier
13477:
13478: =item *
13479:
13480: $namespace : the name of a .db file that contains the data needed or
13481: being set.
13482:
13483: =back
13484:
1.394 bowersj2 13485: =head1 OVERVIEW
1.191 harris41 13486:
1.394 bowersj2 13487: lonnet provides subroutines which interact with the
13488: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13489: about classes, users, and resources.
1.243 albertel 13490:
13491: For many of these objects you can also use this to store data about
13492: them or modify them in various ways.
1.191 harris41 13493:
1.394 bowersj2 13494: =head2 Symbs
1.191 harris41 13495:
1.394 bowersj2 13496: To identify a specific instance of a resource, LON-CAPA uses symbols
13497: or "symbs"X<symb>. These identifiers are built from the URL of the
13498: map, the resource number of the resource in the map, and the URL of
13499: the resource itself. The latter is somewhat redundant, but might help
13500: if maps change.
13501:
13502: An example is
13503:
13504: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13505:
13506: The respective map entry is
13507:
13508: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13509: title="Problem 2">
13510: </resource>
13511:
13512: Symbs are used by the random number generator, as well as to store and
13513: restore data specific to a certain instance of for example a problem.
13514:
13515: =head2 Storing And Retrieving Data
13516:
13517: X<store()>X<cstore()>X<restore()>Three of the most important functions
13518: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13519: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13520: is is the non-critical message twin of cstore. These functions are for
13521: handlers to store a perl hash to a user's permanent data space in an
13522: easy manner, and to retrieve it again on another call. It is expected
13523: that a handler would use this once at the beginning to retrieve data,
13524: and then again once at the end to send only the new data back.
13525:
13526: The data is stored in the user's data directory on the user's
13527: homeserver under the ID of the course.
13528:
13529: The hash that is returned by restore will have all of the previous
13530: value for all of the elements of the hash.
13531:
13532: Example:
13533:
13534: #creating a hash
13535: my %hash;
13536: $hash{'foo'}='bar';
13537:
13538: #storing it
13539: &Apache::lonnet::cstore(\%hash);
13540:
13541: #changing a value
13542: $hash{'foo'}='notbar';
13543:
13544: #adding a new value
13545: $hash{'bar'}='foo';
13546: &Apache::lonnet::cstore(\%hash);
13547:
13548: #retrieving the hash
13549: my %history=&Apache::lonnet::restore();
13550:
13551: #print the hash
13552: foreach my $key (sort(keys(%history))) {
13553: print("\%history{$key} = $history{$key}");
13554: }
13555:
13556: Will print out:
1.191 harris41 13557:
1.394 bowersj2 13558: %history{1:foo} = bar
13559: %history{1:keys} = foo:timestamp
13560: %history{1:timestamp} = 990455579
13561: %history{2:bar} = foo
13562: %history{2:foo} = notbar
13563: %history{2:keys} = foo:bar:timestamp
13564: %history{2:timestamp} = 990455580
13565: %history{bar} = foo
13566: %history{foo} = notbar
13567: %history{timestamp} = 990455580
13568: %history{version} = 2
13569:
13570: Note that the special hash entries C<keys>, C<version> and
13571: C<timestamp> were added to the hash. C<version> will be equal to the
13572: total number of versions of the data that have been stored. The
13573: C<timestamp> attribute will be the UNIX time the hash was
13574: stored. C<keys> is available in every historical section to list which
13575: keys were added or changed at a specific historical revision of a
13576: hash.
13577:
13578: B<Warning>: do not store the hash that restore returns directly. This
13579: will cause a mess since it will restore the historical keys as if the
13580: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13581:
1.394 bowersj2 13582: Calling convention:
1.191 harris41 13583:
1.1172.2.27 raeburn 13584: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13585: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13586:
1.394 bowersj2 13587: For more detailed information, see lonnet specific documentation.
1.191 harris41 13588:
1.394 bowersj2 13589: =head1 RETURN MESSAGES
1.191 harris41 13590:
1.394 bowersj2 13591: =over 4
1.191 harris41 13592:
1.394 bowersj2 13593: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13594:
1.394 bowersj2 13595: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13596: when the connection is brought back up
1.191 harris41 13597:
1.394 bowersj2 13598: =item * B<con_failed>: unable to contact remote host and unable to save message
13599: for later delivery
1.191 harris41 13600:
1.967 bisitz 13601: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13602:
1.394 bowersj2 13603: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13604: that was requested
1.191 harris41 13605:
1.243 albertel 13606: =back
1.191 harris41 13607:
1.243 albertel 13608: =head1 PUBLIC SUBROUTINES
1.191 harris41 13609:
1.243 albertel 13610: =head2 Session Environment Functions
1.191 harris41 13611:
1.243 albertel 13612: =over 4
1.191 harris41 13613:
1.394 bowersj2 13614: =item *
13615: X<appenv()>
1.949 raeburn 13616: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13617: the user envirnoment file, and will be restored for each access this
1.620 albertel 13618: user makes during this session, also modifies the %env for the current
1.949 raeburn 13619: process. Optional rolesarrayref - if defined contains a reference to an array
13620: of roles which are exempt from the restriction on modifying user.role entries
13621: in the user's environment.db and in %env.
1.191 harris41 13622:
13623: =item *
1.394 bowersj2 13624: X<delenv()>
1.987 raeburn 13625: B<delenv($delthis,$regexp)>: removes all items from the session
13626: environment file that begin with $delthis. If the
13627: optional second arg - $regexp - is true, $delthis is treated as a
13628: regular expression, otherwise \Q$delthis\E is used.
13629: The values are also deleted from the current processes %env.
1.191 harris41 13630:
1.795 albertel 13631: =item * get_env_multiple($name)
13632:
13633: gets $name from the %env hash, it seemlessly handles the cases where multiple
13634: values may be defined and end up as an array ref.
13635:
13636: returns an array of values
13637:
1.243 albertel 13638: =back
13639:
13640: =head2 User Information
1.191 harris41 13641:
1.243 albertel 13642: =over 4
1.191 harris41 13643:
13644: =item *
1.394 bowersj2 13645: X<queryauthenticate()>
13646: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13647: authentication scheme
13648:
13649: =item *
1.394 bowersj2 13650: X<authenticate()>
1.1073 raeburn 13651: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13652: authenticate user from domain's lib servers (first use the current
13653: one). C<$upass> should be the users password.
1.1073 raeburn 13654: $checkdefauth is optional (value is 1 if a check should be made to
13655: authenticate user using default authentication method, and allow
13656: account creation if username does not have account in the domain).
13657: $clientcancheckhost is optional (value is 1 if checking whether the
13658: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13659:
13660: =item *
1.394 bowersj2 13661: X<homeserver()>
13662: B<homeserver($uname,$udom)>: find the server which has
13663: the user's directory and files (there must be only one), this caches
13664: the answer, and also caches if there is a borken connection.
1.191 harris41 13665:
13666: =item *
1.394 bowersj2 13667: X<idget()>
13668: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13669: (IDs are a unique resource in a domain, there must be only 1 ID per
13670: username, and only 1 username per ID in a specific domain) (returns
13671: hash: id=>name,id=>name)
1.191 harris41 13672:
13673: =item *
1.394 bowersj2 13674: X<idrget()>
13675: B<idrget($udom,@unames)>: find the IDs behind a list of
13676: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13677:
13678: =item *
1.394 bowersj2 13679: X<idput()>
13680: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13681:
13682: =item *
1.394 bowersj2 13683: X<rolesinit()>
1.1169 droeschl 13684: B<rolesinit($udom,$username)>: get user privileges.
13685: returns user role, first access and timer interval hashes
1.243 albertel 13686:
13687: =item *
1.1171 droeschl 13688: X<privileged()>
13689: B<privileged($username,$domain)>: returns a true if user has a
13690: privileged and active role (i.e. su or dc), false otherwise.
13691:
13692: =item *
1.551 albertel 13693: X<getsection()>
13694: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13695: course $cname, return section name/number or '' for "not in course"
13696: and '-1' for "no section"
13697:
13698: =item *
1.394 bowersj2 13699: X<userenvironment()>
13700: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13701: passed in @what from the requested user's environment, returns a hash
13702:
1.858 raeburn 13703: =item *
13704: X<userlog_query()>
1.859 albertel 13705: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13706: activity.log file. %filters defines filters applied when parsing the
13707: log file. These can be start or end timestamps, or the type of action
13708: - log to look for Login or Logout events, check for Checkin or
13709: Checkout, role for role selection. The response is in the form
13710: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13711: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13712:
1.243 albertel 13713: =back
13714:
13715: =head2 User Roles
13716:
13717: =over 4
13718:
13719: =item *
13720:
1.1172.2.65 raeburn 13721: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13722: returns codes for allowed actions.
13723:
13724: The first argument is required, all others are optional.
13725:
13726: $priv is the privilege being checked.
13727: $uri contains additional information about what is being checked for access (e.g.,
13728: URL, course ID etc.).
13729: $symb is the unique resource instance identifier in a course; if needed,
13730: but not provided, it will be retrieved via a call to &symbread().
13731: $role is the role for which a priv is being checked (only used if priv is evb).
13732: $clientip is the user's IP address (only used when checking for access to portfolio
13733: files).
13734: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13735: prevents recursive calls to &allowed.
13736:
1.243 albertel 13737: F: full access
13738: U,I,K: authentication modes (cxx only)
13739: '': forbidden
13740: 1: user needs to choose course
13741: 2: browse allowed
1.766 albertel 13742: A: passphrase authentication needed
1.1172.2.65 raeburn 13743: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13744:
13745: =item *
13746:
1.1172.2.13 raeburn 13747: constructaccess($url,$setpriv) : check for access to construction space URL
13748:
13749: See if the owner domain and name in the URL match those in the
13750: expected environment. If so, return three element list
13751: ($ownername,$ownerdomain,$ownerhome).
13752:
13753: Otherwise return the null string.
13754:
13755: If second argument 'setpriv' is true, it assigns the privileges,
13756: and returns the same three element list, unless the owner has
13757: blocked "ad hoc" Domain Coordinator access to the Author Space,
13758: in which case the null string is returned.
13759:
13760: =item *
13761:
1.1172.2.84 raeburn 13762: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13763: define a custom role rolename set privileges in format of lonTabs/roles.tab
13764: for system, domain, and course level. $uname and $udom are optional (current
13765: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13766:
13767: =item *
13768:
1.988 raeburn 13769: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13770: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13771: $type is Course (default) or Community.
1.988 raeburn 13772: If $forcedefault evaluates to true, text returned will be default
13773: text for $type. Otherwise, if this is a course, the text returned
13774: will be a custom name for the role (if defined in the course's
13775: environment). If no custom name is defined the default is returned.
13776:
1.832 raeburn 13777: =item *
13778:
1.1172.2.23 raeburn 13779: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13780: All arguments are optional. Returns a hash of a roles, either for
13781: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13782: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13783: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13784: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13785: For each key, value is set to colon-separated start and end times for
13786: the role. If no username and domain are specified, will default to
1.934 raeburn 13787: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13788: of role statuses (active, future or previous), roles
13789: (e.g., cc,in, st etc.) and domains of the roles which can be used
13790: to restrict the list of roles reported. If no array ref is
13791: provided for types, will default to return only active roles.
1.834 albertel 13792:
1.1172.2.13 raeburn 13793: =item *
13794:
13795: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13796: user: $uname:$udom has a role in the course: $cdom_$cnum.
13797:
13798: Additional optional arguments are: $type (if role checking is to be restricted
13799: to certain user status types -- previous (expired roles), active (currently
13800: available roles) or future (roles available in the future), and
13801: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13802: have active Domain Coordinator role in course's domain or in additional
13803: domains (specified in 'Domains to check for privileged users' in course
13804: environment -- set via: Course Settings -> Classlists and staff listing).
13805:
13806: =item *
13807:
13808: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13809: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13810: $possdomains and $possroles are optional array refs -- to domains to check and
13811: roles to check. If $possdomains is not specified, a dump will be done of the
13812: users' roles.db to check for a dc or su role in any domain. This can be
13813: time consuming if &privileged is called repeatedly (e.g., when displaying a
13814: classlist), so in such cases, supplying a $possdomains array is preferred, as
13815: this then allows &privileged_by_domain() to be used, which caches the identity
13816: of privileged users, eliminating the need for repeated calls to &dump().
13817:
13818: =item *
13819:
13820: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13821: where the outer hash keys are domains specified in the $possdomains array ref,
13822: next inner hash keys are privileged roles specified in the $roles array ref,
13823: and the innermost hash contains key = value pairs for username:domain = end:start
13824: for active or future "privileged" users with that role in that domain. To avoid
13825: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13826: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13827:
1.243 albertel 13828: =back
13829:
13830: =head2 User Modification
13831:
13832: =over 4
13833:
13834: =item *
13835:
1.957 raeburn 13836: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13837: user for the level given by URL. Optional start and end dates (leave empty
13838: string or zero for "no date")
1.191 harris41 13839:
13840: =item *
13841:
1.243 albertel 13842: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13843: change a users, password, possible return values are: ok,
13844: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13845: refused
1.191 harris41 13846:
13847: =item *
13848:
1.243 albertel 13849: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13850:
13851: =item *
13852:
1.1058 raeburn 13853: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13854: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13855:
13856: will update user information (firstname,middlename,lastname,generation,
13857: permanentemail), and if forceid is true, student/employee ID also.
13858: A user's institutional affiliation(s) can also be updated.
13859: User information fields will not be overwritten with empty entries
13860: unless the field is included in the $candelete array reference.
13861: This array is included when a single user is modified via "Manage Users",
13862: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13863:
13864: =item *
13865:
1.286 matthew 13866: modifystudent
13867:
1.957 raeburn 13868: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13869: The course id is resolved based on the current user's environment.
13870: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13871: associated with a course.
13872:
1.297 matthew 13873: This call is essentially a wrapper for lonnet::modifyuser and
13874: lonnet::modify_student_enrollment
1.286 matthew 13875:
13876: Inputs:
13877:
13878: =over 4
13879:
1.957 raeburn 13880: =item B<$udom> Student's loncapa domain
1.286 matthew 13881:
1.957 raeburn 13882: =item B<$uname> Student's loncapa login name
1.286 matthew 13883:
1.964 bisitz 13884: =item B<$uid> Student/Employee ID
1.286 matthew 13885:
1.957 raeburn 13886: =item B<$umode> Student's authentication mode
1.286 matthew 13887:
1.957 raeburn 13888: =item B<$upass> Student's password
1.286 matthew 13889:
1.957 raeburn 13890: =item B<$first> Student's first name
1.286 matthew 13891:
1.957 raeburn 13892: =item B<$middle> Student's middle name
1.286 matthew 13893:
1.957 raeburn 13894: =item B<$last> Student's last name
1.286 matthew 13895:
1.957 raeburn 13896: =item B<$gene> Student's generation
1.286 matthew 13897:
1.957 raeburn 13898: =item B<$usec> Student's section in course
1.286 matthew 13899:
13900: =item B<$end> Unix time of the roles expiration
13901:
13902: =item B<$start> Unix time of the roles start date
13903:
13904: =item B<$forceid> If defined, allow $uid to be changed
13905:
13906: =item B<$desiredhome> server to use as home server for student
13907:
1.957 raeburn 13908: =item B<$email> Student's permanent e-mail address
13909:
13910: =item B<$type> Type of enrollment (auto or manual)
13911:
1.963 raeburn 13912: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13913:
13914: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13915:
1.963 raeburn 13916: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13917:
1.963 raeburn 13918: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13919:
1.1172.2.19 raeburn 13920: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13921:
13922: =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 13923:
1.286 matthew 13924: =back
1.297 matthew 13925:
13926: =item *
13927:
13928: modify_student_enrollment
13929:
1.1172.2.31 raeburn 13930: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13931: 'role.request.course' must be defined for this function to proceed.
13932:
13933: Inputs:
13934:
13935: =over 4
13936:
1.1172.2.31 raeburn 13937: =item $udom, student's domain
1.297 matthew 13938:
1.1172.2.31 raeburn 13939: =item $uname, student's name
1.297 matthew 13940:
1.1172.2.31 raeburn 13941: =item $uid, student's user id
1.297 matthew 13942:
1.1172.2.31 raeburn 13943: =item $first, student's first name
1.297 matthew 13944:
13945: =item $middle
13946:
13947: =item $last
13948:
13949: =item $gene
13950:
13951: =item $usec
13952:
13953: =item $end
13954:
13955: =item $start
13956:
1.957 raeburn 13957: =item $type
13958:
13959: =item $locktype
13960:
13961: =item $cid
13962:
13963: =item $selfenroll
13964:
13965: =item $context
13966:
1.1172.2.19 raeburn 13967: =item $credits, number of credits student will earn from this class
13968:
1.1172.2.76 raeburn 13969: =item $instsec, institutional course section code for student
13970:
1.297 matthew 13971: =back
13972:
1.191 harris41 13973:
13974: =item *
13975:
1.243 albertel 13976: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13977: custom role; give a custom role to a user for the level given by URL. Specify
13978: name and domain of role author, and role name
1.191 harris41 13979:
13980: =item *
13981:
1.243 albertel 13982: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13983:
13984: =item *
13985:
1.243 albertel 13986: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13987:
13988: =back
13989:
13990: =head2 Course Infomation
13991:
13992: =over 4
1.191 harris41 13993:
13994: =item *
13995:
1.1118 foxr 13996: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13997: specified course id, including all environment settings for the
13998: course, the description of the course will be in the hash under the
13999: key 'description'
1.191 harris41 14000:
1.1118 foxr 14001: $options is an optional parameter that if supplied is a hash reference that controls
14002: what how this function works. It has the following key/values:
14003:
14004: =over 4
14005:
14006: =item freshen_cache
14007:
14008: If defined, and the environment cache for the course is valid, it is
14009: returned in the returned hash.
14010:
14011: =item one_time
14012:
14013: If defined, the last cache time is set to _now_
14014:
14015: =item user
14016:
14017: If defined, the supplied username is used instead of the current user.
14018:
14019:
14020: =back
14021:
1.191 harris41 14022: =item *
14023:
1.624 albertel 14024: resdata($name,$domain,$type,@which) : request for current parameter
14025: setting for a specific $type, where $type is either 'course' or 'user',
14026: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14027: answers for 10 minutes.
1.243 albertel 14028:
1.877 foxr 14029: =item *
14030:
14031: get_courseresdata($courseid, $domain) : dump the entire course resource
14032: data base, returning a hash that is keyed by the resource name and has
14033: values that are the resource value. I believe that the timestamps and
14034: versions are also returned.
14035:
1.1172.2.31 raeburn 14036: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14037: supplemental content area. This routine caches the number of files for
14038: 10 minutes.
14039:
1.243 albertel 14040: =back
14041:
14042: =head2 Course Modification
14043:
14044: =over 4
1.191 harris41 14045:
14046: =item *
14047:
1.243 albertel 14048: writecoursepref($courseid,%prefs) : write preferences (environment
14049: database) for a course
1.191 harris41 14050:
14051: =item *
14052:
1.1011 raeburn 14053: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14054:
14055: =item *
14056:
1.1038 raeburn 14057: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14058:
1.1167 droeschl 14059: =item *
14060:
14061: is_course($courseid), is_course($cdom, $cnum)
14062:
14063: Accepts either a combined $courseid (in the form of domain_courseid) or the
14064: two component version $cdom, $cnum. It checks if the specified course exists.
14065:
14066: Returns:
14067: undef if the course doesn't exist, otherwise
14068: in scalar context the combined courseid.
14069: in list context the two components of the course identifier, domain and
14070: courseid.
14071:
1.243 albertel 14072: =back
14073:
14074: =head2 Resource Subroutines
14075:
14076: =over 4
1.191 harris41 14077:
14078: =item *
14079:
1.243 albertel 14080: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14081:
14082: =item *
14083:
1.243 albertel 14084: repcopy($filename) : subscribes to the requested file, and attempts to
14085: replicate from the owning library server, Might return
1.607 raeburn 14086: 'unavailable', 'not_found', 'forbidden', 'ok', or
14087: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14088: resource. Expects the local filesystem pathname
14089: (/home/httpd/html/res/....)
14090:
14091: =back
14092:
14093: =head2 Resource Information
14094:
14095: =over 4
1.191 harris41 14096:
14097: =item *
14098:
1.1172.2.28 raeburn 14099: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14100: and returns the value of a variety of different possible values,
14101: $varname should be a request string, and the other parameters can be
14102: used to specify who and what one is asking about. Ordinarily, $cid
14103: does not need to be specified, as it is retrived from
14104: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14105: within lonuserstate::loadmap() when initializing a course, before
14106: $env{'request.course.id'} has been set, so it needs to be provided
14107: in that one case.
1.243 albertel 14108:
14109: Possible values for $varname are environment.lastname (or other item
14110: from the envirnment hash), user.name (or someother aspect about the
14111: user), resource.0.maxtries (or some other part and parameter of a
14112: resource)
1.204 albertel 14113:
14114: =item *
14115:
1.243 albertel 14116: directcondval($number) : get current value of a condition; reads from a state
14117: string
1.204 albertel 14118:
14119: =item *
14120:
1.243 albertel 14121: condval($condidx) : value of condition index based on state
1.204 albertel 14122:
14123: =item *
14124:
1.243 albertel 14125: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14126: resource's metadata, $what should be either a specific key, or either
14127: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14128: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14129:
14130: this function automatically caches all requests
1.191 harris41 14131:
14132: =item *
14133:
1.243 albertel 14134: metadata_query($query,$custom,$customshow) : make a metadata query against the
14135: network of library servers; returns file handle of where SQL and regex results
14136: will be stored for query
1.191 harris41 14137:
14138: =item *
14139:
1.1172.2.66 raeburn 14140: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14141: return symbolic list entry (all arguments optional).
14142:
14143: Args: filename is the filename (including path) for the file for which a symb
14144: is required; donotrecurse, if true will prevent calls to allowed() being made
14145: to check access status if more than one resource was found in the bighash
14146: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14147: a randompick); ignorecachednull, if true will prevent a symb of '' being
14148: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14149: cause possible symbs to be checked to determine if they are subject to content
14150: blocking, if so they will not be included as possible symbs; possibles is a
14151: ref to a hash, which, as a side effect, will be populated with all possible
14152: symbs (content blocking not tested).
14153:
1.243 albertel 14154: returns the data handle
1.191 harris41 14155:
14156: =item *
14157:
1.1172.2.17 raeburn 14158: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 14159: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14160: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 14161: on failure, user must be in a course, as it assumes the existence of
14162: the course initial hash, and uses $env('request.course.id'}. The third
14163: arg is an optional reference to a scalar. If this arg is passed in the
14164: call to symbverify, it will be set to 1 if the symb has been set to be
14165: encrypted; otherwise it will be null.
1.243 albertel 14166:
1.191 harris41 14167: =item *
14168:
1.243 albertel 14169: symbclean($symb) : removes versions numbers from a symb, returns the
14170: cleaned symb
1.191 harris41 14171:
14172: =item *
14173:
1.243 albertel 14174: is_on_map($uri) : checks if the $uri is somewhere on the current
14175: course map, user must be in a course for it to work.
1.191 harris41 14176:
14177: =item *
14178:
1.243 albertel 14179: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14180:
14181: =item *
14182:
1.243 albertel 14183: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14184: a random seed, all arguments are optional, if they aren't sent it uses the
14185: environment to derive them. Note: if symb isn't sent and it can't get one
14186: from &symbread it will use the current time as its return value
1.191 harris41 14187:
14188: =item *
14189:
1.243 albertel 14190: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14191: unfakeable, receipt
1.191 harris41 14192:
14193: =item *
14194:
1.620 albertel 14195: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14196:
14197: =item *
14198:
1.243 albertel 14199: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14200:
14201: =item *
14202:
1.243 albertel 14203: 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 14204:
14205: =item *
14206:
1.243 albertel 14207: 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 14208:
14209: =item *
14210:
1.243 albertel 14211: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14212:
14213: =item *
14214:
1.243 albertel 14215: devalidate($symb) : devalidate temporary spreadsheet calculations,
14216: forcing spreadsheet to reevaluate the resource scores next time.
14217:
1.1172.2.13 raeburn 14218: =item *
14219:
14220: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14221: when viewing in course context.
14222:
14223: input: six args -- filename (decluttered), course number, course domain,
14224: url, symb (if registered) and group (if this is a
14225: group item -- e.g., bulletin board, group page etc.).
14226:
14227: output: array of five scalars --
14228: $cfile -- url for file editing if editable on current server
14229: $home -- homeserver of resource (i.e., for author if published,
14230: or course if uploaded.).
14231: $switchserver -- 1 if server switch will be needed.
14232: $forceedit -- 1 if icon/link should be to go to edit mode
14233: $forceview -- 1 if icon/link should be to go to view mode
14234:
14235: =item *
14236:
14237: is_course_upload($file,$cnum,$cdom)
14238:
14239: Used in course context to determine if current file was uploaded to
14240: the course (i.e., would be found in /userfiles/docs on the course's
14241: homeserver.
14242:
14243: input: 3 args -- filename (decluttered), course number and course domain.
14244: output: boolean -- 1 if file was uploaded.
14245:
1.243 albertel 14246: =back
14247:
14248: =head2 Storing/Retreiving Data
14249:
14250: =over 4
1.191 harris41 14251:
14252: =item *
14253:
1.1172.2.64 raeburn 14254: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14255: permanently for this url; hashref needs to be given and should be a \%hashname;
14256: the remaining args aren't required and if they aren't passed or are '' they will
14257: be derived from the env (with the exception of $laststore, which is an
14258: optional arg used when a user's submission is stored in grading).
14259: $laststore is $version=$timestamp, where $version is the most recent version
14260: number retrieved for the corresponding $symb in the $namespace db file, and
14261: $timestamp is the timestamp for that transaction (UNIX time).
14262: $laststore is currently only passed when cstore() is called by
14263: structuretags::finalize_storage().
1.191 harris41 14264:
14265: =item *
14266:
1.1172.2.64 raeburn 14267: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14268: but uses critical subroutine
1.191 harris41 14269:
14270: =item *
14271:
1.243 albertel 14272: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14273: all args are optional
1.191 harris41 14274:
14275: =item *
14276:
1.717 albertel 14277: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14278: dumps the complete (or key matching regexp) namespace into a hash
14279: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14280: normally &store()ed into
14281:
14282: $range should be either an integer '100' (give me the first 100
14283: matching records)
14284: or be two integers sperated by a - with no spaces
14285: '30-50' (give me the 30th through the 50th matching
14286: records)
14287:
14288:
14289: =item *
14290:
1.1172.2.59 raeburn 14291: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14292: replaces a &store() version of data with a replacement set of data
14293: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 14294: reference. If $tolog is true, the transaction is logged in the courselog
14295: with an action=PUTSTORE.
1.717 albertel 14296:
14297: =item *
14298:
1.243 albertel 14299: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14300: works very similar to store/cstore, but all data is stored in a
14301: temporary location and can be reset using tmpreset, $storehash should
14302: be a hash reference, returns nothing on success
1.191 harris41 14303:
14304: =item *
14305:
1.243 albertel 14306: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14307: similar to restore, but all data is stored in a temporary location and
14308: can be reset using tmpreset. Returns a hash of values on success,
14309: error string otherwise.
1.191 harris41 14310:
14311: =item *
14312:
1.243 albertel 14313: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14314: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14315:
14316: =item *
14317:
1.243 albertel 14318: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14319: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14320:
14321: =item *
14322:
1.243 albertel 14323: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14324: namesp ($udom and $uname are optional)
1.191 harris41 14325:
14326: =item *
14327:
1.702 albertel 14328: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14329: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14330: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14331:
1.702 albertel 14332: $range should be either an integer '100' (give me the first 100
14333: matching records)
14334: or be two integers sperated by a - with no spaces
14335: '30-50' (give me the 30th through the 50th matching
14336: records)
1.449 matthew 14337: =item *
14338:
14339: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14340: $store can be a scalar, an array reference, or if the amount to be
14341: incremented is > 1, a hash reference.
14342:
14343: ($udom and $uname are optional)
1.191 harris41 14344:
14345: =item *
14346:
1.243 albertel 14347: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14348: ($udom and $uname are optional)
1.191 harris41 14349:
14350: =item *
14351:
1.243 albertel 14352: cput($namespace,$storehash,$udom,$uname) : critical put
14353: ($udom and $uname are optional)
1.191 harris41 14354:
14355: =item *
14356:
1.748 albertel 14357: newput($namespace,$storehash,$udom,$uname) :
14358:
14359: Attempts to store the items in the $storehash, but only if they don't
14360: currently exist, if this succeeds you can be certain that you have
14361: successfully created a new key value pair in the $namespace db.
14362:
14363:
14364: Args:
14365: $namespace: name of database to store values to
14366: $storehash: hashref to store to the db
14367: $udom: (optional) domain of user containing the db
14368: $uname: (optional) name of user caontaining the db
14369:
14370: Returns:
14371: 'ok' -> succeeded in storing all keys of $storehash
14372: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14373: least <key> already existed in the db (other
14374: requested keys may also already exist)
1.967 bisitz 14375: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14376: 'con_lost' -> unable to contact request server
14377: 'refused' -> action was not allowed by remote machine
14378:
14379:
14380: =item *
14381:
1.243 albertel 14382: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14383: reference filled in from namesp (encrypts the return communication)
14384: ($udom and $uname are optional)
1.191 harris41 14385:
14386: =item *
14387:
1.243 albertel 14388: log($udom,$name,$home,$message) : write to permanent log for user; use
14389: critical subroutine
14390:
1.806 raeburn 14391: =item *
14392:
1.860 raeburn 14393: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14394: array reference filled in from namespace found in domain level on either
14395: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14396:
14397: =item *
14398:
1.860 raeburn 14399: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14400: domain level either on specified domain server ($uhome) or primary domain
14401: server ($udom and $uhome are optional)
1.806 raeburn 14402:
1.943 raeburn 14403: =item *
14404:
1.1172.2.35 raeburn 14405: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14406: for: authentication, language, quotas, timezone, date locale, and portal URL in
14407: the target domain.
14408:
14409: May also include additional key => value pairs for the following groups:
14410:
14411: =over
14412:
14413: =item
14414: disk quotas (MB allocated by default to portfolios and authoring spaces).
14415:
14416: =over
14417:
14418: =item defaultquota, authorquota
14419:
14420: =back
14421:
14422: =item
14423: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14424: portfolio for users).
14425:
14426: =over
14427:
14428: =item
14429: aboutme, blog, webdav, portfolio
14430:
14431: =back
14432:
14433: =item
14434: requestcourses: ability to request courses, and how requests are processed.
14435:
14436: =over
14437:
14438: =item
1.1172.2.37 raeburn 14439: official, unofficial, community, textbook
1.1172.2.35 raeburn 14440:
14441: =back
14442:
14443: =item
14444: inststatus: types of institutional affiliation, and order in which they are displayed.
14445:
14446: =over
14447:
14448: =item
1.1172.2.44 raeburn 14449: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 14450:
14451: =back
14452:
14453: =item
14454: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14455: for course's uploaded content.
14456:
14457: =over
14458:
14459: =item
1.1172.2.68 raeburn 14460: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
14461: communityquota, textbookquota
1.1172.2.35 raeburn 14462:
14463: =back
14464:
14465: =item
14466: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14467: on your servers.
14468:
14469: =over
14470:
14471: =item
14472: remotesessions, hostedsessions
14473:
14474: =back
14475:
14476: =back
14477:
14478: In cases where a domain coordinator has never used the "Set Domain Configuration"
14479: utility to create a configuration.db file on a domain's primary library server
14480: only the following domain defaults: auth_def, auth_arg_def, lang_def
14481: -- corresponding values are authentication type (internal, krb4, krb5,
14482: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14483: will be available. Values are retrieved from cache (if current), unless the
14484: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14485: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14486:
14487: Typical usage:
1.943 raeburn 14488:
1.1172.2.35 raeburn 14489: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14490:
1.243 albertel 14491: =back
14492:
14493: =head2 Network Status Functions
14494:
14495: =over 4
1.191 harris41 14496:
14497: =item *
14498:
1.1137 raeburn 14499: dirlist() : return directory list based on URI (first arg).
14500:
14501: Inputs: 1 required, 5 optional.
14502:
14503: =over
14504:
14505: =item
14506: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14507:
14508: =item
14509: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14510:
14511: =item
14512: $username - username of user/course to be listed. Extracted from $uri if absent.
14513:
14514: =item
14515: $getpropath - boolean: 1 if prepend path using &propath().
14516:
14517: =item
14518: $getuserdir - boolean: 1 if prepend path for "userfiles".
14519:
14520: =item
14521: $alternateRoot - path to prepend in place of path from $uri.
14522:
14523: =back
14524:
14525: Returns: Array of up to two items.
14526:
14527: =over
14528:
14529: a reference to an array of files/subdirectories
14530:
14531: =over
14532:
14533: Each element in the array of files/subdirectories is a & separated list of
14534: item name and the result of running stat on the item. If dirlist was requested
14535: for a file instead of a directory, the item name will be ''. For a directory
14536: listing, if the item is a metadata file, the element will end &N&M
14537: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14538: default copyright set (1).
14539:
14540: =back
14541:
14542: a scalar containing error condition (if encountered).
14543:
14544: =over
14545:
14546: =item
14547: no_host (no homeserver identified for $username:$domain).
14548:
14549: =item
14550: no_such_host (server contacted for listing not identified as valid host).
14551:
14552: =item
14553: con_lost (connection to remote server failed).
14554:
14555: =item
14556: refused (invalid $username:$domain received on lond side).
14557:
14558: =item
14559: no_such_dir (directory at specified path on lond side does not exist).
14560:
14561: =item
14562: empty (directory at specified path on lond side is empty).
14563:
14564: =over
14565:
14566: This is currently not encountered because the &ls3, &ls2,
14567: &ls (_handler) routines on the lond side do not filter out
14568: . and .. from a directory listing.
14569:
14570: =back
14571:
14572: =back
14573:
14574: =back
1.191 harris41 14575:
14576: =item *
14577:
1.243 albertel 14578: spareserver() : find server with least workload from spare.tab
14579:
1.986 foxr 14580:
14581: =item *
14582:
14583: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14584: if there is no corresponding loncapa host.
14585:
1.243 albertel 14586: =back
14587:
1.986 foxr 14588:
1.243 albertel 14589: =head2 Apache Request
14590:
14591: =over 4
1.191 harris41 14592:
14593: =item *
14594:
1.243 albertel 14595: ssi($url,%hash) : server side include, does a complete request cycle on url to
14596: localhost, posts hash
14597:
14598: =back
14599:
14600: =head2 Data to String to Data
14601:
14602: =over 4
1.191 harris41 14603:
14604: =item *
14605:
1.243 albertel 14606: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14607: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14608:
14609: =item *
14610:
1.243 albertel 14611: hashref2str($hashref) : convert a hashref into a string complete with
14612: escaping and '=' and '&' separators, supports elements that are
14613: arrayrefs and hashrefs
1.191 harris41 14614:
14615: =item *
14616:
1.243 albertel 14617: arrayref2str($arrayref) : convert an arrayref into a string complete
14618: with escaping and '&' separators, supports elements that are arrayrefs
14619: and hashrefs
1.191 harris41 14620:
14621: =item *
14622:
1.243 albertel 14623: str2hash($string) : convert string to hash using unescaping and
14624: splitting on '=' and '&', supports elements that are arrayrefs and
14625: hashrefs
1.191 harris41 14626:
14627: =item *
14628:
1.243 albertel 14629: str2array($string) : convert string to hash using unescaping and
14630: splitting on '&', supports elements that are arrayrefs and hashrefs
14631:
14632: =back
14633:
14634: =head2 Logging Routines
14635:
14636:
14637: These routines allow one to make log messages in the lonnet.log and
14638: lonnet.perm logfiles.
1.191 harris41 14639:
1.1119 foxr 14640: =over 4
14641:
1.191 harris41 14642: =item *
14643:
1.243 albertel 14644: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14645:
14646: =item *
14647:
1.243 albertel 14648: logthis() : append message to the normal lonnet.log file, it gets
14649: preiodically rolled over and deleted.
1.191 harris41 14650:
14651: =item *
14652:
1.243 albertel 14653: logperm() : append a permanent message to lonnet.perm.log, this log
14654: file never gets deleted by any automated portion of the system, only
14655: messages of critical importance should go in here.
14656:
1.1119 foxr 14657:
1.243 albertel 14658: =back
14659:
14660: =head2 General File Helper Routines
14661:
14662: =over 4
1.191 harris41 14663:
14664: =item *
14665:
1.481 raeburn 14666: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14667: (a) files in /uploaded
14668: (i) If a local copy of the file exists -
14669: compares modification date of local copy with last-modified date for
14670: definitive version stored on home server for course. If local copy is
14671: stale, requests a new version from the home server and stores it.
14672: If the original has been removed from the home server, then local copy
14673: is unlinked.
14674: (ii) If local copy does not exist -
14675: requests the file from the home server and stores it.
14676:
14677: If $caller is 'uploadrep':
14678: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14679: for request for files originally uploaded via DOCS.
14680: - returns 'ok' if fresh local copy now available, -1 otherwise.
14681:
14682: Otherwise:
14683: This indicates a call from the content generation phase of the request.
14684: - returns the entire contents of the file or -1.
14685:
14686: (b) files in /res
14687: - returns the entire contents of a file or -1;
14688: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14689:
1.712 albertel 14690:
14691: =item *
14692:
14693: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14694: reference
14695:
14696: returns either a stat() list of data about the file or an empty list
14697: if the file doesn't exist or couldn't find out about it (connection
14698: problems or user unknown)
14699:
1.191 harris41 14700: =item *
14701:
1.243 albertel 14702: filelocation($dir,$file) : returns file system location of a file
14703: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14704: directory that relative $file lookups are to looked in ($dir of /a/dir
14705: and a file of ../bob will become /a/bob)
1.191 harris41 14706:
14707: =item *
14708:
14709: hreflocation($dir,$file) : returns file system location or a URL; same as
14710: filelocation except for hrefs
14711:
14712: =item *
14713:
1.1172.2.49 raeburn 14714: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14715: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14716:
1.243 albertel 14717: =back
14718:
1.608 albertel 14719: =head2 Usererfile file routines (/uploaded*)
14720:
14721: =over 4
14722:
14723: =item *
14724:
14725: userfileupload(): main rotine for putting a file in a user or course's
14726: filespace, arguments are,
14727:
1.620 albertel 14728: formname - required - this is the name of the element in $env where the
1.608 albertel 14729: filename, and the contents of the file to create/modifed exist
1.620 albertel 14730: the filename is in $env{'form.'.$formname.'.filename'} and the
14731: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14732: context - if coursedoc, store the file in the course of the active role
14733: of the current user;
14734: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14735: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14736: subdir - required - subdirectory to put the file in under ../userfiles/
14737: if undefined, it will be placed in "unknown"
14738:
14739: (This routine calls clean_filename() to remove any dangerous
14740: characters from the filename, and then calls finuserfileupload() to
14741: complete the transaction)
14742:
14743: returns either the url of the uploaded file (/uploaded/....) if successful
14744: and /adm/notfound.html if unsuccessful
14745:
14746: =item *
14747:
14748: clean_filename(): routine for cleaing a filename up for storage in
14749: userfile space, argument is:
14750:
14751: filename - proposed filename
14752:
14753: returns: the new clean filename
14754:
14755: =item *
14756:
1.1090 raeburn 14757: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14758: userspace, probably shouldn't be called directly
14759:
14760: docuname: username or courseid of destination for the file
14761: docudom: domain of user/course of destination for the file
14762: formname: same as for userfileupload()
1.1090 raeburn 14763: fname: filename (including subdirectories) for the file
14764: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14765: allfiles: reference to hash used to store objects found by parser
14766: codebase: reference to hash used for codebases of java objects found by parser
14767: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14768: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14769: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14770: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14771: context: if 'overwrite', will move the uploaded file from its temporary location to
14772: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14773: mimetype: reference to scalar to accommodate mime type determined
14774: from File::MMagic if $parser = parse.
1.608 albertel 14775:
14776: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14777: and /adm/notfound.html if unsuccessful (or an error message if context
14778: was 'overwrite').
14779:
1.608 albertel 14780:
14781: =item *
14782:
14783: renameuserfile(): renames an existing userfile to a new name
14784:
14785: Args:
14786: docuname: username or courseid of destination for the file
14787: docudom: domain of user/course of destination for the file
14788: old: current file name (including any subdirs under userfiles)
14789: new: desired file name (including any subdirs under userfiles)
14790:
14791: =item *
14792:
14793: mkdiruserfile(): creates a directory is a userfiles dir
14794:
14795: Args:
14796: docuname: username or courseid of destination for the file
14797: docudom: domain of user/course of destination for the file
14798: dir: dir to create (including any subdirs under userfiles)
14799:
14800: =item *
14801:
14802: removeuserfile(): removes a file that exists in userfiles
14803:
14804: Args:
14805: docuname: username or courseid of destination for the file
14806: docudom: domain of user/course of destination for the file
14807: fname: filname to delete (including any subdirs under userfiles)
14808:
14809: =item *
14810:
14811: removeuploadedurl(): convience function for removeuserfile()
14812:
14813: Args:
14814: url: a full /uploaded/... url to delete
14815:
1.747 albertel 14816: =item *
14817:
14818: get_portfile_permissions():
14819: Args:
14820: domain: domain of user or course contain the portfolio files
14821: user: name of user or num of course contain the portfolio files
14822: Returns:
14823: hashref of a dump of the proper file_permissions.db
14824:
14825:
14826: =item *
14827:
14828: get_access_controls():
14829:
14830: Args:
14831: current_permissions: the hash ref returned from get_portfile_permissions()
14832: group: (optional) the group you want the files associated with
14833: file: (optional) the file you want access info on
14834:
14835: Returns:
1.749 raeburn 14836: a hash (keys are file names) of hashes containing
14837: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14838: values are XML containing access control settings (see below)
1.747 albertel 14839:
14840: Internal notes:
14841:
1.749 raeburn 14842: access controls are stored in file_permissions.db as key=value pairs.
14843: key -> path to file/file_name\0uniqueID:scope_end_start
14844: where scope -> public,guest,course,group,domains or users.
14845: end -> UNIX time for end of access (0 -> no end date)
14846: start -> UNIX time for start of access
14847:
14848: value -> XML description of access control
14849: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14850: <start></start>
14851: <end></end>
14852:
14853: <password></password> for scope type = guest
14854:
14855: <domain></domain> for scope type = course or group
14856: <number></number>
14857: <roles id="">
14858: <role></role>
14859: <access></access>
14860: <section></section>
14861: <group></group>
14862: </roles>
14863:
14864: <dom></dom> for scope type = domains
14865:
14866: <users> for scope type = users
14867: <user>
14868: <uname></uname>
14869: <udom></udom>
14870: </user>
14871: </users>
14872: </scope>
14873:
14874: Access data is also aggregated for each file in an additional key=value pair:
14875: key -> path to file/file_name\0accesscontrol
14876: value -> reference to hash
14877: hash contains key = value pairs
14878: where key = uniqueID:scope_end_start
14879: value = UNIX time record was last updated
14880:
14881: Used to improve speed of look-ups of access controls for each file.
14882:
14883: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14884:
1.1172.2.13 raeburn 14885: =item *
14886:
1.749 raeburn 14887: modify_access_controls():
14888:
14889: Modifies access controls for a portfolio file
14890: Args
14891: 1. file name
14892: 2. reference to hash of required changes,
14893: 3. domain
14894: 4. username
14895: where domain,username are the domain of the portfolio owner
14896: (either a user or a course)
14897:
14898: Returns:
14899: 1. result of additions or updates ('ok' or 'error', with error message).
14900: 2. result of deletions ('ok' or 'error', with error message).
14901: 3. reference to hash of any new or updated access controls.
14902: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14903: key = integer (inbound ID)
1.1172.2.13 raeburn 14904: value = uniqueID
14905:
14906: =item *
14907:
14908: get_timebased_id():
14909:
14910: Attempts to get a unique timestamp-based suffix for use with items added to a
14911: course via the Course Editor (e.g., folders, composite pages,
14912: group bulletin boards).
14913:
14914: Args: (first three required; six others optional)
14915:
14916: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14917: docssequence, or name of group
14918:
14919: 2. keyid (alphanumeric): name of temporary locking key in hash,
14920: e.g., num, boardids
14921:
14922: 3. namespace: name of gdbm file used to store suffixes already assigned;
14923: file will be named nohist_namespace.db
14924:
14925: 4. cdom: domain of course; default is current course domain from %env
14926:
14927: 5. cnum: course number; default is current course number from %env
14928:
14929: 6. idtype: set to concat if an additional digit is to be appended to the
14930: unix timestamp to form the suffix, if the plain timestamp is already
14931: in use. Default is to not do this, but simply increment the unix
14932: timestamp by 1 until a unique key is obtained.
14933:
14934: 7. who: holder of locking key; defaults to user:domain for user.
14935:
14936: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14937: retrying); default is 3.
14938:
14939: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14940:
14941: Returns:
14942:
14943: 1. suffix obtained (numeric)
14944:
14945: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14946:
14947: 3. error: contains (localized) error message if an error occurred.
14948:
1.747 albertel 14949:
1.608 albertel 14950: =back
14951:
1.243 albertel 14952: =head2 HTTP Helper Routines
14953:
14954: =over 4
14955:
1.191 harris41 14956: =item *
14957:
14958: escape() : unpack non-word characters into CGI-compatible hex codes
14959:
14960: =item *
14961:
14962: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14963:
1.243 albertel 14964: =back
14965:
14966: =head1 PRIVATE SUBROUTINES
14967:
14968: =head2 Underlying communication routines (Shouldn't call)
14969:
14970: =over 4
14971:
14972: =item *
14973:
14974: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14975:
14976: =item *
14977:
14978: reply() : uses subreply to send a message to remote machine, logs all failures
14979:
14980: =item *
14981:
14982: critical() : passes a critical message to another server; if cannot
14983: get through then place message in connection buffer directory and
14984: returns con_delayed, if incapable of saving message, returns
14985: con_failed
14986:
14987: =item *
14988:
14989: reconlonc() : tries to reconnect lonc client processes.
14990:
14991: =back
14992:
14993: =head2 Resource Access Logging
14994:
14995: =over 4
14996:
14997: =item *
14998:
14999: flushcourselogs() : flush (save) buffer logs and access logs
15000:
15001: =item *
15002:
15003: courselog($what) : save message for course in hash
15004:
15005: =item *
15006:
15007: courseacclog($what) : save message for course using &courselog(). Perform
15008: special processing for specific resource types (problems, exams, quizzes, etc).
15009:
1.191 harris41 15010: =item *
15011:
15012: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15013: as a PerlChildExitHandler
1.243 albertel 15014:
15015: =back
15016:
15017: =head2 Other
15018:
15019: =over 4
15020:
15021: =item *
15022:
15023: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15024:
15025: =back
15026:
15027: =cut
1.877 foxr 15028:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>