Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.84
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.84! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.83 2016/09/27 18:09:06 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 92: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.1172.2.79 raeburn 105: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 373: sleep(0.1);
1.549 foxr 374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.1172.2.79 raeburn 391: sleep(0.1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
1.1172.2.79 raeburn 484: sleep 1;
1.1 albertel 485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 847: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
848: $try_server));
1.1123 raeburn 849: ($spare_server, $lowest_load) =
850: &compare_server_load($try_server, $spare_server, $lowest_load);
851: }
1.1083 raeburn 852: }
1.784 albertel 853:
1.1123 raeburn 854: my $found_server = ($spare_server ne '' && $lowest_load < 100);
855:
856: if (!$found_server) {
857: if (ref($spareshash->{'default'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,
860: $remotesessions,$try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
1.1172.2.41 raeburn 884: my ($try_server, $spare_server, $lowest_load, $required) = @_;
885:
886: if ($required) {
887: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
888: my $remoterev = &get_server_loncaparev(undef,$try_server);
889: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
890: if (($major eq '' && $minor eq '') ||
891: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
892: return ($spare_server,$lowest_load);
893: }
894: }
1.784 albertel 895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1172.2.47 raeburn 955: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1172.2.47 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
960: if ($skiploadbal) {
961: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
962: unless (defined($cached)) {
963: my $cachetime = 60*60*24;
964: my %domconfig =
965: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
966: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
967: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
968: $cachetime);
969: }
970: }
971: }
1.1076 raeburn 972: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 973: my $loginvia;
1.1172.2.47 raeburn 974: if ($skiploadbal) {
975: if (ref($balancers) eq 'HASH') {
976: next if (exists($balancers->{$lonhost}));
977: }
978: }
1.1115 raeburn 979: if ($checkloginvia) {
980: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 981: if ($loginvia) {
982: my ($server,$path) = split(/:/,$loginvia);
983: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 984: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 985: if ($login_host eq $server) {
986: $portal_path = $path;
1.1151 raeburn 987: $isredirect = 1;
1.1116 raeburn 988: }
989: } else {
990: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 992: if ($login_host eq $lonhost) {
993: $portal_path = '';
1.1151 raeburn 994: $isredirect = '';
1.1116 raeburn 995: }
996: }
997: } else {
1.1076 raeburn 998: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 999: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1000: }
1001: }
1002: if ($login_host ne '') {
1.1116 raeburn 1003: $hostname = &hostname($login_host);
1.1076 raeburn 1004: }
1.1151 raeburn 1005: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1006: }
1007:
1.202 matthew 1008: # --------------------------------------------- Try to change a user's password
1009:
1010: sub changepass {
1.799 raeburn 1011: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1012: $currentpass = &escape($currentpass);
1013: $newpass = &escape($newpass);
1.1030 raeburn 1014: my $lonhost = $perlvar{'lonHostID'};
1015: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1016: $server);
1017: if (! $answer) {
1018: &logthis("No reply on password change request to $server ".
1019: "by $uname in domain $udom.");
1020: } elsif ($answer =~ "^ok") {
1021: &logthis("$uname in $udom successfully changed their password ".
1022: "on $server.");
1023: } elsif ($answer =~ "^pwchange_failure") {
1024: &logthis("$uname in $udom was unable to change their password ".
1025: "on $server. The action was blocked by either lcpasswd ".
1026: "or pwchange");
1027: } elsif ($answer =~ "^non_authorized") {
1028: &logthis("$uname in $udom did not get their password correct when ".
1029: "attempting to change it on $server.");
1030: } elsif ($answer =~ "^auth_mode_error") {
1031: &logthis("$uname in $udom attempted to change their password despite ".
1032: "not being locally or internally authenticated on $server.");
1033: } elsif ($answer =~ "^unknown_user") {
1034: &logthis("$uname in $udom attempted to change their password ".
1035: "on $server but were unable to because $server is not ".
1036: "their home server.");
1037: } elsif ($answer =~ "^refused") {
1038: &logthis("$server refused to change $uname in $udom password because ".
1039: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1040: } elsif ($answer =~ "invalid_client") {
1041: &logthis("$server refused to change $uname in $udom password because ".
1042: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1043: }
1044: return $answer;
1.1 albertel 1045: }
1046:
1.169 harris41 1047: # ----------------------- Try to determine user's current authentication scheme
1048:
1049: sub queryauthenticate {
1050: my ($uname,$udom)=@_;
1.456 albertel 1051: my $uhome=&homeserver($uname,$udom);
1052: if (!$uhome) {
1053: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1054: return 'no_host';
1055: }
1056: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1057: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1059: }
1.456 albertel 1060: return $answer;
1.169 harris41 1061: }
1062:
1.1 albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1064:
1.1 albertel 1065: sub authenticate {
1.1073 raeburn 1066: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1067: $upass=&escape($upass);
1068: $uname= &LONCAPA::clean_username($uname);
1.836 www 1069: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1070: my $newhome;
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: # Maybe the machine was offline and only re-appeared again recently?
1073: &reconlonc();
1074: # One more
1.952 raeburn 1075: $uhome=&homeserver($uname,$udom,1);
1076: if (($uhome eq 'no_host') && $checkdefauth) {
1077: if (defined(&domain($udom,'primary'))) {
1078: $newhome=&domain($udom,'primary');
1079: }
1080: if ($newhome ne '') {
1081: $uhome = $newhome;
1082: }
1083: }
1.836 www 1084: if ((!$uhome) || ($uhome eq 'no_host')) {
1085: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1086: return 'no_host';
1087: }
1.1 albertel 1088: }
1.1073 raeburn 1089: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1090: if ($answer eq 'authorized') {
1.952 raeburn 1091: if ($newhome) {
1092: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1093: return 'no_account_on_host';
1094: } else {
1095: &logthis("User $uname at $udom authorized by $uhome");
1096: return $uhome;
1097: }
1.471 albertel 1098: }
1099: if ($answer eq 'non_authorized') {
1100: &logthis("User $uname at $udom rejected by $uhome");
1101: return 'no_host';
1.9 www 1102: }
1.471 albertel 1103: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1104: return 'no_host';
1105: }
1106:
1.1073 raeburn 1107: sub can_host_session {
1.1074 raeburn 1108: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1109: my $canhost = 1;
1.1074 raeburn 1110: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1111: if (ref($remotesessions) eq 'HASH') {
1112: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1113: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1114: $canhost = 0;
1115: } else {
1116: $canhost = 1;
1117: }
1118: }
1119: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1120: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1121: $canhost = 1;
1122: } else {
1123: $canhost = 0;
1124: }
1125: }
1126: if ($canhost) {
1127: if ($remotesessions->{'version'} ne '') {
1128: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1129: if ($reqmajor ne '' && $reqminor ne '') {
1130: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1131: my $major = $1;
1132: my $minor = $2;
1133: if (($major < $reqmajor ) ||
1134: (($major == $reqmajor) && ($minor < $reqminor))) {
1135: $canhost = 0;
1136: }
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: }
1144: if ($canhost) {
1145: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1146: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1147: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1148: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1151: $canhost = 0;
1152: } else {
1153: $canhost = 1;
1154: }
1155: }
1156: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1157: if (($uint_dom ne '') &&
1158: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1159: $canhost = 1;
1160: } else {
1161: $canhost = 0;
1162: }
1163: }
1164: }
1165: }
1166: return $canhost;
1167: }
1168:
1.1083 raeburn 1169: sub spare_can_host {
1170: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1171: my $canhost=1;
1.1172.2.62 raeburn 1172: my $try_server_hostname = &hostname($try_server);
1173: my $serverhomeID = &get_server_homeID($try_server_hostname);
1174: my $serverhomedom = &host_domain($serverhomeID);
1175: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1176: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1177: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1178: $canhost = 0;
1179: }
1180: }
1181: if (($canhost) && ($uint_dom)) {
1182: my @intdoms;
1183: my $internet_names = &get_internet_names($try_server);
1184: if (ref($internet_names) eq 'ARRAY') {
1185: @intdoms = @{$internet_names};
1186: }
1187: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1188: my $remoterev = &get_server_loncaparev(undef,$try_server);
1189: $canhost = &can_host_session($udom,$try_server,$remoterev,
1190: $remotesessions,
1191: $defdomdefaults{'hostedsessions'});
1192: }
1.1083 raeburn 1193: }
1194: return $canhost;
1195: }
1196:
1.1123 raeburn 1197: sub this_host_spares {
1198: my ($dom) = @_;
1.1126 raeburn 1199: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1200: my @hosts = ¤t_machine_ids();
1201: foreach my $lonhost (@hosts) {
1202: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1203: $dom_in_use = $dom;
1204: $lonhost_in_use = $lonhost;
1.1123 raeburn 1205: last;
1206: }
1207: }
1.1126 raeburn 1208: if ($dom_in_use ne '') {
1209: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1210: }
1211: if (ref($result) ne 'HASH') {
1212: $lonhost_in_use = $perlvar{'lonHostID'};
1213: $dom_in_use = &host_domain($lonhost_in_use);
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: if (ref($result) ne 'HASH') {
1216: $result = \%spareid;
1217: }
1218: }
1219: return $result;
1220: }
1221:
1222: sub spares_for_offload {
1223: my ($dom_in_use,$lonhost_in_use) = @_;
1224: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1225: if (defined($cached)) {
1226: return $result;
1227: } else {
1.1126 raeburn 1228: my $cachetime = 60*60*24;
1229: my %domconfig =
1230: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1231: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1232: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1234: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1235: }
1236: }
1237: }
1238: }
1.1126 raeburn 1239: return;
1.1123 raeburn 1240: }
1241:
1.1129 raeburn 1242: sub get_lonbalancer_config {
1243: my ($servers) = @_;
1244: my ($currbalancer,$currtargets);
1245: if (ref($servers) eq 'HASH') {
1246: foreach my $server (keys(%{$servers})) {
1247: my %what = (
1248: spareid => 1,
1249: perlvar => 1,
1250: );
1251: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1252: if ($result eq 'ok') {
1253: if (ref($returnhash) eq 'HASH') {
1254: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1255: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1256: $currbalancer = $server;
1257: $currtargets = {};
1258: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1259: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1260: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1261: }
1262: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1263: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1264: }
1265: }
1266: last;
1267: }
1268: }
1269: }
1270: }
1271: }
1272: }
1273: return ($currbalancer,$currtargets);
1274: }
1275:
1276: sub check_loadbalancing {
1277: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1278: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1279: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1280: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1281: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1282: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1283: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1284: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1285: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1286: my $domneedscache;
1.1129 raeburn 1287: my $cachetime = 60*60*24;
1288:
1289: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1290: $dom_in_use = $udom;
1291: $homeintdom = 1;
1292: } else {
1293: $dom_in_use = $serverhomedom;
1294: }
1295: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1296: unless (defined($cached)) {
1297: my %domconfig =
1298: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1299: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1300: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1301: } else {
1302: $domneedscache = $dom_in_use;
1.1129 raeburn 1303: }
1304: }
1305: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1306: ($is_balancer,$currtargets,$currrules) =
1307: &check_balancer_result($result,@hosts);
1.1129 raeburn 1308: if ($is_balancer) {
1309: if (ref($currrules) eq 'HASH') {
1310: if ($homeintdom) {
1311: if ($uname ne '') {
1312: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1313: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1314: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1315: $rule_in_effect = $currrules->{'_LC_author'};
1316: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1317: $rule_in_effect = $currrules->{'_LC_adv'}
1318: }
1319: }
1320: if ($rule_in_effect eq '') {
1321: my %userenv = &userenvironment($udom,$uname,'inststatus');
1322: if ($userenv{'inststatus'} ne '') {
1323: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1324: my ($othertitle,$usertypes,$types) =
1325: &Apache::loncommon::sorted_inst_types($udom);
1326: if (ref($types) eq 'ARRAY') {
1327: foreach my $type (@{$types}) {
1328: if (grep(/^\Q$type\E$/,@statuses)) {
1329: if (exists($currrules->{$type})) {
1330: $rule_in_effect = $currrules->{$type};
1331: }
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: }
1341: } else {
1342: if (exists($currrules->{'default'})) {
1343: $rule_in_effect = $currrules->{'default'};
1344: }
1345: }
1346: } else {
1347: if ($currrules->{'_LC_external'} ne '') {
1348: $rule_in_effect = $currrules->{'_LC_external'};
1349: }
1350: }
1351: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1352: $uname,$udom);
1353: }
1354: }
1355: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1356: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1357: unless (defined($cached)) {
1358: my %domconfig =
1359: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1360: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1361: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1362: } else {
1363: $domneedscache = $serverhomedom;
1.1129 raeburn 1364: }
1365: }
1366: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1367: ($is_balancer,$currtargets,$currrules) =
1368: &check_balancer_result($result,@hosts);
1369: if ($is_balancer) {
1.1129 raeburn 1370: if (ref($currrules) eq 'HASH') {
1371: if ($currrules->{'_LC_internetdom'} ne '') {
1372: $rule_in_effect = $currrules->{'_LC_internetdom'};
1373: }
1374: }
1375: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1376: $uname,$udom);
1377: }
1378: } else {
1379: if ($perlvar{'lonBalancer'} eq 'yes') {
1380: $is_balancer = 1;
1381: $offloadto = &this_host_spares($dom_in_use);
1382: }
1.1172.2.75 raeburn 1383: unless (defined($cached)) {
1384: $domneedscache = $serverhomedom;
1385: }
1.1129 raeburn 1386: }
1387: } else {
1388: if ($perlvar{'lonBalancer'} eq 'yes') {
1389: $is_balancer = 1;
1390: $offloadto = &this_host_spares($dom_in_use);
1391: }
1.1172.2.75 raeburn 1392: unless (defined($cached)) {
1393: $domneedscache = $serverhomedom;
1394: }
1395: }
1396: if ($domneedscache) {
1397: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1398: }
1.1172.2.5 raeburn 1399: if ($is_balancer) {
1400: my $lowest_load = 30000;
1401: if (ref($offloadto) eq 'HASH') {
1402: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1403: foreach my $try_server (@{$offloadto->{'primary'}}) {
1404: ($otherserver,$lowest_load) =
1405: &compare_server_load($try_server,$otherserver,$lowest_load);
1406: }
1.1129 raeburn 1407: }
1.1172.2.5 raeburn 1408: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1409:
1.1172.2.5 raeburn 1410: if (!$found_server) {
1411: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1412: foreach my $try_server (@{$offloadto->{'default'}}) {
1413: ($otherserver,$lowest_load) =
1414: &compare_server_load($try_server,$otherserver,$lowest_load);
1415: }
1416: }
1417: }
1418: } elsif (ref($offloadto) eq 'ARRAY') {
1419: if (@{$offloadto} == 1) {
1420: $otherserver = $offloadto->[0];
1421: } elsif (@{$offloadto} > 1) {
1422: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1423: ($otherserver,$lowest_load) =
1424: &compare_server_load($try_server,$otherserver,$lowest_load);
1425: }
1426: }
1427: }
1.1172.2.5 raeburn 1428: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1429: $is_balancer = 0;
1430: if ($uname ne '' && $udom ne '') {
1431: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1432:
1433: &appenv({'user.loadbalexempt' => $lonhost,
1434: 'user.loadbalcheck.time' => time});
1435: }
1.1129 raeburn 1436: }
1437: }
1438: }
1439: return ($is_balancer,$otherserver);
1440: }
1441:
1.1172.2.12 raeburn 1442: sub check_balancer_result {
1443: my ($result,@hosts) = @_;
1444: my ($is_balancer,$currtargets,$currrules);
1445: if (ref($result) eq 'HASH') {
1446: if ($result->{'lonhost'} ne '') {
1447: my $currbalancer = $result->{'lonhost'};
1448: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1449: $is_balancer = 1;
1450: $currtargets = $result->{'targets'};
1451: $currrules = $result->{'rules'};
1452: }
1453: } else {
1454: foreach my $key (keys(%{$result})) {
1455: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1456: (ref($result->{$key}) eq 'HASH')) {
1457: $is_balancer = 1;
1458: $currrules = $result->{$key}{'rules'};
1459: $currtargets = $result->{$key}{'targets'};
1460: last;
1461: }
1462: }
1463: }
1464: }
1465: return ($is_balancer,$currtargets,$currrules);
1466: }
1467:
1.1129 raeburn 1468: sub get_loadbalancer_targets {
1469: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1470: my $offloadto;
1.1172.2.4 raeburn 1471: if ($rule_in_effect eq 'none') {
1472: return [$perlvar{'lonHostID'}];
1473: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1474: $offloadto = $currtargets;
1475: } else {
1476: if ($rule_in_effect eq 'homeserver') {
1477: my $homeserver = &homeserver($uname,$udom);
1478: if ($homeserver ne 'no_host') {
1479: $offloadto = [$homeserver];
1480: }
1481: } elsif ($rule_in_effect eq 'externalbalancer') {
1482: my %domconfig =
1483: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1484: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1485: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1486: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1487: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1488: }
1489: }
1490: } else {
1.1172.2.7 raeburn 1491: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1492: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1493: if (&hostname($remotebalancer) ne '') {
1494: $offloadto = [$remotebalancer];
1495: }
1496: }
1497: } elsif (&hostname($rule_in_effect) ne '') {
1498: $offloadto = [$rule_in_effect];
1499: }
1500: }
1501: return $offloadto;
1502: }
1503:
1.1127 raeburn 1504: sub internet_dom_servers {
1505: my ($dom) = @_;
1506: my (%uniqservers,%servers);
1507: my $primaryserver = &hostname(&domain($dom,'primary'));
1508: my @machinedoms = &machine_domains($primaryserver);
1509: foreach my $mdom (@machinedoms) {
1510: my %currservers = %servers;
1511: my %server = &get_servers($mdom);
1512: %servers = (%currservers,%server);
1513: }
1514: my %by_hostname;
1515: foreach my $id (keys(%servers)) {
1516: push(@{$by_hostname{$servers{$id}}},$id);
1517: }
1518: foreach my $hostname (sort(keys(%by_hostname))) {
1519: if (@{$by_hostname{$hostname}} > 1) {
1520: my $match = 0;
1521: foreach my $id (@{$by_hostname{$hostname}}) {
1522: if (&host_domain($id) eq $dom) {
1523: $uniqservers{$id} = $hostname;
1524: $match = 1;
1525: }
1526: }
1527: unless ($match) {
1528: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1529: }
1530: } else {
1531: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1532: }
1533: }
1534: return %uniqservers;
1535: }
1536:
1.1 albertel 1537: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1538:
1.599 albertel 1539: my %homecache;
1.1 albertel 1540: sub homeserver {
1.230 stredwic 1541: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1542: my $index="$uname:$udom";
1.426 albertel 1543:
1.599 albertel 1544: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1545:
1546: my %servers = &get_servers($udom,'library');
1547: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1548: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1549: exists($badServerCache{$tryserver}));
1.841 albertel 1550:
1551: my $answer=reply("home:$udom:$uname",$tryserver);
1552: if ($answer eq 'found') {
1553: delete($badServerCache{$tryserver});
1554: return $homecache{$index}=$tryserver;
1555: } elsif ($answer eq 'no_host') {
1556: $badServerCache{$tryserver}=1;
1557: }
1.1 albertel 1558: }
1559: return 'no_host';
1.70 www 1560: }
1561:
1562: # ------------------------------------- Find the usernames behind a list of IDs
1563:
1564: sub idget {
1565: my ($udom,@ids)=@_;
1566: my %returnhash=();
1567:
1.841 albertel 1568: my %servers = &get_servers($udom,'library');
1569: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1570: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1571: $idlist=~tr/A-Z/a-z/;
1572: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1573: my @answer=();
1574: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1575: @answer=split(/\&/,$reply);
1576: } ;
1577: my $i;
1578: for ($i=0;$i<=$#ids;$i++) {
1579: if ($answer[$i]) {
1.1172.2.73 raeburn 1580: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1581: }
1582: }
1583: }
1.70 www 1584: return %returnhash;
1585: }
1586:
1587: # ------------------------------------- Find the IDs behind a list of usernames
1588:
1589: sub idrget {
1590: my ($udom,@unames)=@_;
1591: my %returnhash=();
1.800 albertel 1592: foreach my $uname (@unames) {
1593: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1594: }
1.70 www 1595: return %returnhash;
1596: }
1597:
1598: # ------------------------------- Store away a list of names and associated IDs
1599:
1600: sub idput {
1601: my ($udom,%ids)=@_;
1602: my %servers=();
1.800 albertel 1603: foreach my $uname (keys(%ids)) {
1604: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1605: my $uhom=&homeserver($uname,$udom);
1.70 www 1606: if ($uhom ne 'no_host') {
1.800 albertel 1607: my $id=&escape($ids{$uname});
1.70 www 1608: $id=~tr/A-Z/a-z/;
1.800 albertel 1609: my $esc_unam=&escape($uname);
1.70 www 1610: if ($servers{$uhom}) {
1.800 albertel 1611: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1612: } else {
1.800 albertel 1613: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1614: }
1615: }
1.191 harris41 1616: }
1.800 albertel 1617: foreach my $server (keys(%servers)) {
1618: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1619: }
1.344 www 1620: }
1621:
1.1172.2.30 raeburn 1622: # ---------------------------------------- Delete unwanted IDs from ids.db file
1623:
1624: sub iddel {
1625: my ($udom,$idshashref,$uhome)=@_;
1626: my %result=();
1627: unless (ref($idshashref) eq 'HASH') {
1628: return %result;
1629: }
1630: my %servers=();
1631: while (my ($id,$uname) = each(%{$idshashref})) {
1632: my $uhom;
1633: if ($uhome) {
1634: $uhom = $uhome;
1635: } else {
1636: $uhom=&homeserver($uname,$udom);
1637: }
1638: if ($uhom ne 'no_host') {
1639: if ($servers{$uhom}) {
1640: $servers{$uhom}.='&'.&escape($id);
1641: } else {
1642: $servers{$uhom}=&escape($id);
1643: }
1644: }
1645: }
1646: foreach my $server (keys(%servers)) {
1647: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1648: }
1649: return %result;
1650: }
1651:
1.1023 raeburn 1652: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1653: sub dump_dom {
1.1165 droeschl 1654: my ($namespace, $udom, $regexp) = @_;
1655:
1656: $udom ||= $env{'user.domain'};
1657:
1658: return () unless $udom;
1659:
1660: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1661: }
1662:
1.1023 raeburn 1663: # ------------------------------------------ get items from domain db files
1.806 raeburn 1664:
1665: sub get_dom {
1.860 raeburn 1666: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1667: return if ($udom eq 'public');
1.806 raeburn 1668: my $items='';
1669: foreach my $item (@$storearr) {
1670: $items.=&escape($item).'&';
1671: }
1672: $items=~s/\&$//;
1.860 raeburn 1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1675: return if ($udom eq 'public');
1.860 raeburn 1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: } else {
1.874 albertel 1679: undef($uhome);
1.860 raeburn 1680: }
1681: } else {
1682: if (!$uhome) {
1683: if (defined(&domain($udom,'primary'))) {
1684: $uhome=&domain($udom,'primary');
1685: }
1686: }
1687: }
1688: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1689: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1690: my %returnhash;
1.875 albertel 1691: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1692: return %returnhash;
1693: }
1.806 raeburn 1694: my @pairs=split(/\&/,$rep);
1695: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1696: return @pairs;
1697: }
1698: my $i=0;
1699: foreach my $item (@$storearr) {
1700: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1701: $i++;
1702: }
1703: return %returnhash;
1704: } else {
1.880 banghart 1705: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1706: }
1707: }
1708:
1709: # -------------------------------------------- put items in domain db files
1710:
1711: sub put_dom {
1.860 raeburn 1712: my ($namespace,$storehash,$udom,$uhome)=@_;
1713: if (!$udom) {
1714: $udom=$env{'user.domain'};
1715: if (defined(&domain($udom,'primary'))) {
1716: $uhome=&domain($udom,'primary');
1717: } else {
1.874 albertel 1718: undef($uhome);
1.860 raeburn 1719: }
1720: } else {
1721: if (!$uhome) {
1722: if (defined(&domain($udom,'primary'))) {
1723: $uhome=&domain($udom,'primary');
1724: }
1725: }
1726: }
1727: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1728: my $items='';
1729: foreach my $item (keys(%$storehash)) {
1730: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1731: }
1732: $items=~s/\&$//;
1733: return &reply("putdom:$udom:$namespace:$items",$uhome);
1734: } else {
1.860 raeburn 1735: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1736: }
1737: }
1738:
1.1023 raeburn 1739: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1740: sub newput_dom {
1.1023 raeburn 1741: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1742: my $result;
1743: if (!$udom) {
1744: $udom=$env{'user.domain'};
1745: }
1.1023 raeburn 1746: if ($udom) {
1747: my $uname = &get_domainconfiguser($udom);
1748: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1749: }
1750: return $result;
1751: }
1752:
1.1023 raeburn 1753: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1754: sub del_dom {
1.1023 raeburn 1755: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1756: if (ref($storearr) eq 'ARRAY') {
1757: if (!$udom) {
1758: $udom=$env{'user.domain'};
1759: }
1.1023 raeburn 1760: if ($udom) {
1761: my $uname = &get_domainconfiguser($udom);
1762: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1763: }
1764: }
1765: }
1766:
1.1023 raeburn 1767: # ----------------------------------construct domainconfig user for a domain
1768: sub get_domainconfiguser {
1769: my ($udom) = @_;
1770: return $udom.'-domainconfig';
1771: }
1772:
1.837 raeburn 1773: sub retrieve_inst_usertypes {
1774: my ($udom) = @_;
1775: my (%returnhash,@order);
1.989 raeburn 1776: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1777: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1778: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1779: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1780: } else {
1781: if (defined(&domain($udom,'primary'))) {
1782: my $uhome=&domain($udom,'primary');
1783: my $rep=&reply("inst_usertypes:$udom",$uhome);
1784: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1785: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1786: return (\%returnhash,\@order);
1787: }
1788: my ($hashitems,$orderitems) = split(/:/,$rep);
1789: my @pairs=split(/\&/,$hashitems);
1790: foreach my $item (@pairs) {
1791: my ($key,$value)=split(/=/,$item,2);
1792: $key = &unescape($key);
1793: next if ($key =~ /^error: 2 /);
1794: $returnhash{$key}=&thaw_unescape($value);
1795: }
1796: my @esc_order = split(/\&/,$orderitems);
1797: foreach my $item (@esc_order) {
1798: push(@order,&unescape($item));
1799: }
1800: } else {
1.1172.2.44 raeburn 1801: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1802: }
1.1172.2.44 raeburn 1803: return (\%returnhash,\@order);
1.837 raeburn 1804: }
1805: }
1806:
1.868 raeburn 1807: sub is_domainimage {
1808: my ($url) = @_;
1.1172.2.74 raeburn 1809: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1810: if (&domain($1) ne '') {
1811: return '1';
1812: }
1813: }
1814: return;
1815: }
1816:
1.899 raeburn 1817: sub inst_directory_query {
1818: my ($srch) = @_;
1819: my $udom = $srch->{'srchdomain'};
1820: my %results;
1821: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1822: my $outcome;
1.899 raeburn 1823: if ($homeserver ne '') {
1.904 albertel 1824: my $queryid=&reply("querysend:instdirsearch:".
1825: &escape($srch->{'srchby'}).':'.
1826: &escape($srch->{'srchterm'}).':'.
1827: &escape($srch->{'srchtype'}),$homeserver);
1828: my $host=&hostname($homeserver);
1829: if ($queryid !~/^\Q$host\E\_/) {
1830: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1831: return;
1832: }
1833: my $response = &get_query_reply($queryid);
1834: my $maxtries = 5;
1835: my $tries = 1;
1836: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1837: $response = &get_query_reply($queryid);
1838: $tries ++;
1839: }
1840:
1841: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1842: if ($response eq 'unavailable') {
1843: $outcome = $response;
1844: } else {
1845: $outcome = 'ok';
1846: my @matches = split(/\n/,$response);
1847: foreach my $match (@matches) {
1848: my ($key,$value) = split(/=/,$match);
1849: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1850: }
1.899 raeburn 1851: }
1852: }
1853: }
1.909 raeburn 1854: return ($outcome,%results);
1.899 raeburn 1855: }
1856:
1857: sub usersearch {
1858: my ($srch) = @_;
1859: my $dom = $srch->{'srchdomain'};
1860: my %results;
1861: my %libserv = &all_library();
1862: my $query = 'usersearch';
1863: foreach my $tryserver (keys(%libserv)) {
1864: if (&host_domain($tryserver) eq $dom) {
1865: my $host=&hostname($tryserver);
1866: my $queryid=
1.911 raeburn 1867: &reply("querysend:".&escape($query).':'.
1868: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1869: &escape($srch->{'srchtype'}).':'.
1870: &escape($srch->{'srchterm'}),$tryserver);
1871: if ($queryid !~/^\Q$host\E\_/) {
1872: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1873: next;
1.899 raeburn 1874: }
1875: my $reply = &get_query_reply($queryid);
1876: my $maxtries = 1;
1877: my $tries = 1;
1878: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1879: $reply = &get_query_reply($queryid);
1880: $tries ++;
1881: }
1882: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1883: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1884: } else {
1.911 raeburn 1885: my @matches;
1886: if ($reply =~ /\n/) {
1887: @matches = split(/\n/,$reply);
1888: } else {
1889: @matches = split(/\&/,$reply);
1890: }
1.899 raeburn 1891: foreach my $match (@matches) {
1892: my ($uname,$udom,%userhash);
1.911 raeburn 1893: foreach my $entry (split(/:/,$match)) {
1894: my ($key,$value) =
1895: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1896: $userhash{$key} = $value;
1897: if ($key eq 'username') {
1898: $uname = $value;
1899: } elsif ($key eq 'domain') {
1900: $udom = $value;
1.911 raeburn 1901: }
1.899 raeburn 1902: }
1903: $results{$uname.':'.$udom} = \%userhash;
1904: }
1905: }
1906: }
1907: }
1908: return %results;
1909: }
1910:
1.912 raeburn 1911: sub get_instuser {
1912: my ($udom,$uname,$id) = @_;
1913: my $homeserver = &domain($udom,'primary');
1914: my ($outcome,%results);
1915: if ($homeserver ne '') {
1916: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1917: &escape($id).':'.&escape($udom),$homeserver);
1918: my $host=&hostname($homeserver);
1919: if ($queryid !~/^\Q$host\E\_/) {
1920: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1921: return;
1922: }
1923: my $response = &get_query_reply($queryid);
1924: my $maxtries = 5;
1925: my $tries = 1;
1926: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1927: $response = &get_query_reply($queryid);
1928: $tries ++;
1929: }
1930: if (!&error($response) && $response ne 'refused') {
1931: if ($response eq 'unavailable') {
1932: $outcome = $response;
1933: } else {
1934: $outcome = 'ok';
1935: my @matches = split(/\n/,$response);
1936: foreach my $match (@matches) {
1937: my ($key,$value) = split(/=/,$match);
1938: $results{&unescape($key)} = &thaw_unescape($value);
1939: }
1940: }
1941: }
1942: }
1943: my %userinfo;
1944: if (ref($results{$uname}) eq 'HASH') {
1945: %userinfo = %{$results{$uname}};
1946: }
1947: return ($outcome,%userinfo);
1948: }
1949:
1.1172.2.69 raeburn 1950: sub get_multiple_instusers {
1951: my ($udom,$users,$caller) = @_;
1952: my ($outcome,$results);
1953: if (ref($users) eq 'HASH') {
1954: my $count = keys(%{$users});
1955: my $requested = &freeze_escape($users);
1956: my $homeserver = &domain($udom,'primary');
1957: if ($homeserver ne '') {
1958: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1959: my $host=&hostname($homeserver);
1960: if ($queryid !~/^\Q$host\E\_/) {
1961: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1962: ' for host: '.$homeserver.'in domain '.$udom);
1963: return ($outcome,$results);
1964: }
1965: my $response = &get_query_reply($queryid);
1966: my $maxtries = 5;
1967: if ($count > 100) {
1968: $maxtries = 1+int($count/20);
1969: }
1970: my $tries = 1;
1971: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1972: $response = &get_query_reply($queryid);
1973: $tries ++;
1974: }
1975: if ($response eq '') {
1976: $results = {};
1977: foreach my $key (keys(%{$users})) {
1978: my ($uname,$id);
1979: if ($caller eq 'id') {
1980: $id = $key;
1981: } else {
1982: $uname = $key;
1983: }
1984: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1985: $outcome = $resp;
1986: if ($resp eq 'ok') {
1987: %{$results} = (%{$results}, %info);
1988: } else {
1989: last;
1990: }
1991: }
1992: } elsif(!&error($response) && ($response ne 'refused')) {
1993: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
1994: $outcome = $response;
1995: } else {
1996: ($outcome,my $userdata) = split(/=/,$response,2);
1997: if ($outcome eq 'ok') {
1998: $results = &thaw_unescape($userdata);
1999: }
2000: }
2001: }
2002: }
2003: }
2004: return ($outcome,$results);
2005: }
2006:
1.912 raeburn 2007: sub inst_rulecheck {
1.923 raeburn 2008: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2009: my %returnhash;
2010: if ($udom ne '') {
2011: if (ref($rules) eq 'ARRAY') {
2012: @{$rules} = map {&escape($_);} (@{$rules});
2013: my $rulestr = join(':',@{$rules});
2014: my $homeserver=&domain($udom,'primary');
2015: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2016: my $response;
2017: if ($item eq 'username') {
2018: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2019: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2020: $homeserver));
1.923 raeburn 2021: } elsif ($item eq 'id') {
2022: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2023: ':'.&escape($id).':'.$rulestr,
2024: $homeserver));
1.945 raeburn 2025: } elsif ($item eq 'selfcreate') {
2026: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2027: &escape($udom).':'.&escape($uname).
2028: ':'.$rulestr,$homeserver));
1.923 raeburn 2029: }
1.912 raeburn 2030: if ($response ne 'refused') {
2031: my @pairs=split(/\&/,$response);
2032: foreach my $item (@pairs) {
2033: my ($key,$value)=split(/=/,$item,2);
2034: $key = &unescape($key);
2035: next if ($key =~ /^error: 2 /);
2036: $returnhash{$key}=&thaw_unescape($value);
2037: }
2038: }
2039: }
2040: }
2041: }
2042: return %returnhash;
2043: }
2044:
2045: sub inst_userrules {
1.923 raeburn 2046: my ($udom,$check) = @_;
1.912 raeburn 2047: my (%ruleshash,@ruleorder);
2048: if ($udom ne '') {
2049: my $homeserver=&domain($udom,'primary');
2050: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2051: my $response;
2052: if ($check eq 'id') {
2053: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2054: $homeserver);
1.943 raeburn 2055: } elsif ($check eq 'email') {
2056: $response=&reply('instemailrules:'.&escape($udom),
2057: $homeserver);
1.923 raeburn 2058: } else {
2059: $response=&reply('instuserrules:'.&escape($udom),
2060: $homeserver);
2061: }
1.912 raeburn 2062: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2063: ($response ne 'unknown_cmd') &&
1.912 raeburn 2064: ($response ne 'no_such_host')) {
2065: my ($hashitems,$orderitems) = split(/:/,$response);
2066: my @pairs=split(/\&/,$hashitems);
2067: foreach my $item (@pairs) {
2068: my ($key,$value)=split(/=/,$item,2);
2069: $key = &unescape($key);
2070: next if ($key =~ /^error: 2 /);
2071: $ruleshash{$key}=&thaw_unescape($value);
2072: }
2073: my @esc_order = split(/\&/,$orderitems);
2074: foreach my $item (@esc_order) {
2075: push(@ruleorder,&unescape($item));
2076: }
2077: }
2078: }
2079: }
2080: return (\%ruleshash,\@ruleorder);
2081: }
2082:
1.976 raeburn 2083: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2084:
2085: sub get_domain_defaults {
1.1172.2.35 raeburn 2086: my ($domain,$ignore_cache) = @_;
2087: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2088: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2089: unless ($ignore_cache) {
2090: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2091: if (defined($cached)) {
2092: if (ref($result) eq 'HASH') {
2093: return %{$result};
2094: }
1.943 raeburn 2095: }
2096: }
2097: my %domdefaults;
2098: my %domconfig =
1.989 raeburn 2099: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2100: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2101: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2102: 'requestauthor','selfenrollment',
1.1172.2.76 raeburn 2103: 'coursecategories','autoenroll'],$domain);
1.1172.2.41 raeburn 2104: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2105: if (ref($domconfig{'defaults'}) eq 'HASH') {
2106: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2107: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2108: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2109: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2110: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2111: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2112: } else {
2113: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2114: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2115: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2116: }
1.976 raeburn 2117: if (ref($domconfig{'quotas'}) eq 'HASH') {
2118: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2119: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2120: } else {
2121: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2122: }
1.1172.2.6 raeburn 2123: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2124: foreach my $item (@usertools) {
2125: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2126: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2127: }
2128: }
1.1172.2.29 raeburn 2129: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2130: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2131: }
1.976 raeburn 2132: }
1.985 raeburn 2133: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2134: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2135: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2136: }
2137: }
1.1172.2.9 raeburn 2138: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2139: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2140: }
1.989 raeburn 2141: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2142: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2143: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2144: }
2145: }
1.1047 raeburn 2146: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2147: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2148: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2149: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2150: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2151: }
1.1172.2.41 raeburn 2152: foreach my $type (@coursetypes) {
2153: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2154: unless ($type eq 'community') {
2155: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2156: }
2157: }
2158: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2159: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2160: }
1.1172.2.60 raeburn 2161: if ($domdefaults{'postsubmit'} eq 'on') {
2162: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2163: $domdefaults{$type.'postsubtimeout'} =
2164: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2165: }
2166: }
1.1172.2.30 raeburn 2167: }
1.1172.2.67 raeburn 2168: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2169: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2170: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2171: if (@clonecodes) {
2172: $domdefaults{'canclone'} = join('+',@clonecodes);
2173: }
2174: }
2175: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2176: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2177: }
1.1047 raeburn 2178: }
1.1073 raeburn 2179: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2180: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2181: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2182: }
2183: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2184: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2185: }
1.1172.2.62 raeburn 2186: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2187: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2188: }
1.1073 raeburn 2189: }
1.1172.2.41 raeburn 2190: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2191: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2192: my @settings = ('types','registered','enroll_dates','access_dates','section',
2193: 'approval','limit');
2194: foreach my $type (@coursetypes) {
2195: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2196: my @mgrdc = ();
2197: foreach my $item (@settings) {
2198: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2199: push(@mgrdc,$item);
2200: }
2201: }
2202: if (@mgrdc) {
2203: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2204: }
2205: }
2206: }
2207: }
2208: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2209: foreach my $type (@coursetypes) {
2210: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2211: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2212: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2213: }
2214: }
2215: }
2216: }
2217: }
1.1172.2.46 raeburn 2218: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2219: $domdefaults{'catauth'} = 'std';
2220: $domdefaults{'catunauth'} = 'std';
2221: if ($domconfig{'coursecategories'}{'auth'}) {
2222: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2223: }
2224: if ($domconfig{'coursecategories'}{'unauth'}) {
2225: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2226: }
2227: }
1.1172.2.76 raeburn 2228: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2229: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2230: }
1.1172.2.23 raeburn 2231: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2232: return %domdefaults;
2233: }
2234:
1.344 www 2235: # --------------------------------------------------- Assign a key to a student
2236:
2237: sub assign_access_key {
1.364 www 2238: #
2239: # a valid key looks like uname:udom#comments
2240: # comments are being appended
2241: #
1.498 www 2242: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2243: $kdom=
1.620 albertel 2244: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2245: $knum=
1.620 albertel 2246: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2247: $cdom=
1.620 albertel 2248: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2249: $cnum=
1.620 albertel 2250: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2251: $udom=$env{'user.name'} unless (defined($udom));
2252: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2253: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2254: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2255: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2256: # assigned to this person
2257: # - this should not happen,
1.345 www 2258: # unless something went wrong
2259: # the first time around
2260: # ready to assign
1.364 www 2261: $logentry=$1.'; '.$logentry;
1.496 www 2262: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2263: $kdom,$knum) eq 'ok') {
1.345 www 2264: # key now belongs to user
1.346 www 2265: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2266: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2267: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2268: return 'ok';
2269: } else {
2270: return
2271: 'error: Count not permanently assign key, will need to be re-entered later.';
2272: }
2273: } else {
2274: return 'error: Could not assign key, try again later.';
2275: }
1.364 www 2276: } elsif (!$existing{$ckey}) {
1.345 www 2277: # the key does not exist
2278: return 'error: The key does not exist';
2279: } else {
2280: # the key is somebody else's
2281: return 'error: The key is already in use';
2282: }
1.344 www 2283: }
2284:
1.364 www 2285: # ------------------------------------------ put an additional comment on a key
2286:
2287: sub comment_access_key {
2288: #
2289: # a valid key looks like uname:udom#comments
2290: # comments are being appended
2291: #
2292: my ($ckey,$cdom,$cnum,$logentry)=@_;
2293: $cdom=
1.620 albertel 2294: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2295: $cnum=
1.620 albertel 2296: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2297: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2298: if ($existing{$ckey}) {
2299: $existing{$ckey}.='; '.$logentry;
2300: # ready to assign
1.367 www 2301: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2302: $cdom,$cnum) eq 'ok') {
2303: return 'ok';
2304: } else {
2305: return 'error: Count not store comment.';
2306: }
2307: } else {
2308: # the key does not exist
2309: return 'error: The key does not exist';
2310: }
2311: }
2312:
1.344 www 2313: # ------------------------------------------------------ Generate a set of keys
2314:
2315: sub generate_access_keys {
1.364 www 2316: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2317: $cdom=
1.620 albertel 2318: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2319: $cnum=
1.620 albertel 2320: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2321: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2322: unless (($cdom) && ($cnum)) { return 0; }
2323: if ($number>10000) { return 0; }
2324: sleep(2); # make sure don't get same seed twice
2325: srand(time()^($$+($$<<15))); # from "Programming Perl"
2326: my $total=0;
2327: for (my $i=1;$i<=$number;$i++) {
2328: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2329: sprintf("%lx",int(100000*rand)).'-'.
2330: sprintf("%lx",int(100000*rand));
2331: $newkey=~s/1/g/g; # folks mix up 1 and l
2332: $newkey=~s/0/h/g; # and also 0 and O
2333: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2334: if ($existing{$newkey}) {
2335: $i--;
2336: } else {
1.364 www 2337: if (&put('accesskeys',
2338: { $newkey => '# generated '.localtime().
1.620 albertel 2339: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2340: '; '.$logentry },
2341: $cdom,$cnum) eq 'ok') {
1.344 www 2342: $total++;
2343: }
2344: }
2345: }
1.620 albertel 2346: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2347: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2348: return $total;
2349: }
2350:
2351: # ------------------------------------------------------- Validate an accesskey
2352:
2353: sub validate_access_key {
2354: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2355: $cdom=
1.620 albertel 2356: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2357: $cnum=
1.620 albertel 2358: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2359: $udom=$env{'user.domain'} unless (defined($udom));
2360: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2361: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2362: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2363: }
2364:
2365: # ------------------------------------- Find the section of student in a course
1.652 albertel 2366: sub devalidate_getsection_cache {
2367: my ($udom,$unam,$courseid)=@_;
2368: my $hashid="$udom:$unam:$courseid";
2369: &devalidate_cache_new('getsection',$hashid);
2370: }
1.298 matthew 2371:
1.815 albertel 2372: sub courseid_to_courseurl {
2373: my ($courseid) = @_;
2374: #already url style courseid
2375: return $courseid if ($courseid =~ m{^/});
2376:
2377: if (exists($env{'course.'.$courseid.'.num'})) {
2378: my $cnum = $env{'course.'.$courseid.'.num'};
2379: my $cdom = $env{'course.'.$courseid.'.domain'};
2380: return "/$cdom/$cnum";
2381: }
2382:
2383: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2384: if (exists($courseinfo{'num'})) {
2385: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2386: }
2387:
2388: return undef;
2389: }
2390:
1.298 matthew 2391: sub getsection {
2392: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2393: my $cachetime=1800;
1.551 albertel 2394:
2395: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2396: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2397: if (defined($cached)) { return $result; }
2398:
1.298 matthew 2399: my %Pending;
2400: my %Expired;
2401: #
2402: # Each role can either have not started yet (pending), be active,
2403: # or have expired.
2404: #
2405: # If there is an active role, we are done.
2406: #
2407: # If there is more than one role which has not started yet,
2408: # choose the one which will start sooner
2409: # If there is one role which has not started yet, return it.
2410: #
2411: # If there is more than one expired role, choose the one which ended last.
2412: # If there is a role which has expired, return it.
2413: #
1.815 albertel 2414: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2415: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2416: foreach my $key (keys(%roleshash)) {
1.479 albertel 2417: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2418: my $section=$1;
2419: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2420: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2421: my $now=time;
1.548 albertel 2422: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2423: $Expired{$end}=$section;
2424: next;
2425: }
1.548 albertel 2426: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2427: $Pending{$start}=$section;
2428: next;
2429: }
1.599 albertel 2430: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2431: }
2432: #
2433: # Presumedly there will be few matching roles from the above
2434: # loop and the sorting time will be negligible.
2435: if (scalar(keys(%Pending))) {
2436: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2437: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2438: }
2439: if (scalar(keys(%Expired))) {
2440: my @sorted = sort {$a <=> $b} keys(%Expired);
2441: my $time = pop(@sorted);
1.599 albertel 2442: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2443: }
1.599 albertel 2444: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2445: }
1.70 www 2446:
1.599 albertel 2447: sub save_cache {
2448: &purge_remembered();
1.722 albertel 2449: #&Apache::loncommon::validate_page();
1.620 albertel 2450: undef(%env);
1.780 albertel 2451: undef($env_loaded);
1.599 albertel 2452: }
1.452 albertel 2453:
1.599 albertel 2454: my $to_remember=-1;
2455: my %remembered;
2456: my %accessed;
2457: my $kicks=0;
2458: my $hits=0;
1.849 albertel 2459: sub make_key {
2460: my ($name,$id) = @_;
1.872 albertel 2461: if (length($id) > 65
2462: && length(&escape($id)) > 200) {
2463: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2464: }
1.849 albertel 2465: return &escape($name.':'.$id);
2466: }
2467:
1.599 albertel 2468: sub devalidate_cache_new {
2469: my ($name,$id,$debug) = @_;
2470: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2471: my $remembered_id=$name.':'.$id;
1.849 albertel 2472: $id=&make_key($name,$id);
1.599 albertel 2473: $memcache->delete($id);
1.1172.2.81 raeburn 2474: delete($remembered{$remembered_id});
2475: delete($accessed{$remembered_id});
1.599 albertel 2476: }
2477:
2478: sub is_cached_new {
2479: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2480: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2481: # keys in %remembered hash, which persists for
2482: # duration of request (no restriction on key length).
2483: if (exists($remembered{$remembered_id})) {
2484: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2485: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2486: $hits++;
1.1172.2.81 raeburn 2487: return ($remembered{$remembered_id},1);
1.599 albertel 2488: }
1.1172.2.81 raeburn 2489: $id=&make_key($name,$id);
1.599 albertel 2490: my $value = $memcache->get($id);
2491: if (!(defined($value))) {
2492: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2493: return (undef,undef);
1.416 albertel 2494: }
1.599 albertel 2495: if ($value eq '__undef__') {
2496: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2497: $value=undef;
2498: }
1.1172.2.81 raeburn 2499: &make_room($remembered_id,$value,$debug);
1.599 albertel 2500: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2501: return ($value,1);
2502: }
2503:
2504: sub do_cache_new {
2505: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2506: my $remembered_id=$name.':'.$id;
1.849 albertel 2507: $id=&make_key($name,$id);
1.599 albertel 2508: my $setvalue=$value;
2509: if (!defined($setvalue)) {
2510: $setvalue='__undef__';
2511: }
1.623 albertel 2512: if (!defined($time) ) {
2513: $time=600;
2514: }
1.599 albertel 2515: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2516: my $result = $memcache->set($id,$setvalue,$time);
2517: if (! $result) {
1.872 albertel 2518: &logthis("caching of id -> $id failed");
1.910 albertel 2519: $memcache->disconnect_all();
1.872 albertel 2520: }
1.600 albertel 2521: # need to make a copy of $value
1.1172.2.81 raeburn 2522: &make_room($remembered_id,$value,$debug);
1.599 albertel 2523: return $value;
2524: }
2525:
2526: sub make_room {
1.1172.2.81 raeburn 2527: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2528:
1.1172.2.81 raeburn 2529: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2530: : $value;
1.599 albertel 2531: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2532: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2533: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2534: my $to_kick;
2535: my $max_time=0;
2536: foreach my $other (keys(%accessed)) {
2537: if (&tv_interval($accessed{$other}) > $max_time) {
2538: $to_kick=$other;
2539: $max_time=&tv_interval($accessed{$other});
2540: }
2541: }
2542: delete($remembered{$to_kick});
2543: delete($accessed{$to_kick});
2544: $kicks++;
2545: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2546: return;
2547: }
2548:
1.599 albertel 2549: sub purge_remembered {
1.604 albertel 2550: #&logthis("Tossing ".scalar(keys(%remembered)));
2551: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2552: undef(%remembered);
2553: undef(%accessed);
1.428 albertel 2554: }
1.70 www 2555: # ------------------------------------- Read an entry from a user's environment
2556:
2557: sub userenvironment {
2558: my ($udom,$unam,@what)=@_;
1.976 raeburn 2559: my $items;
2560: foreach my $item (@what) {
2561: $items.=&escape($item).'&';
2562: }
2563: $items=~s/\&$//;
1.70 www 2564: my %returnhash=();
1.1009 raeburn 2565: my $uhome = &homeserver($unam,$udom);
2566: unless ($uhome eq 'no_host') {
2567: my @answer=split(/\&/,
2568: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2569: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2570: return %returnhash;
2571: }
1.1009 raeburn 2572: my $i;
2573: for ($i=0;$i<=$#what;$i++) {
2574: $returnhash{$what[$i]}=&unescape($answer[$i]);
2575: }
1.70 www 2576: }
2577: return %returnhash;
1.1 albertel 2578: }
2579:
1.617 albertel 2580: # ---------------------------------------------------------- Get a studentphoto
2581: sub studentphoto {
2582: my ($udom,$unam,$ext) = @_;
2583: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2584: if (defined($env{'request.course.id'})) {
1.708 raeburn 2585: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2586: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2587: return(&retrievestudentphoto($udom,$unam,$ext));
2588: } else {
2589: my ($result,$perm_reqd)=
1.707 albertel 2590: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2591: if ($result eq 'ok') {
2592: if (!($perm_reqd eq 'yes')) {
2593: return(&retrievestudentphoto($udom,$unam,$ext));
2594: }
2595: }
2596: }
2597: }
2598: } else {
2599: my ($result,$perm_reqd) =
1.707 albertel 2600: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2601: if ($result eq 'ok') {
2602: if (!($perm_reqd eq 'yes')) {
2603: return(&retrievestudentphoto($udom,$unam,$ext));
2604: }
2605: }
2606: }
2607: return '/adm/lonKaputt/lonlogo_broken.gif';
2608: }
2609:
2610: sub retrievestudentphoto {
2611: my ($udom,$unam,$ext,$type) = @_;
2612: my $home=&Apache::lonnet::homeserver($unam,$udom);
2613: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2614: if ($ret eq 'ok') {
2615: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2616: if ($type eq 'thumbnail') {
2617: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2618: }
2619: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2620: return $tokenurl;
2621: } else {
2622: if ($type eq 'thumbnail') {
2623: return '/adm/lonKaputt/genericstudent_tn.gif';
2624: } else {
2625: return '/adm/lonKaputt/lonlogo_broken.gif';
2626: }
1.617 albertel 2627: }
2628: }
2629:
1.263 www 2630: # -------------------------------------------------------------------- New chat
2631:
2632: sub chatsend {
1.724 raeburn 2633: my ($newentry,$anon,$group)=@_;
1.620 albertel 2634: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2635: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2636: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2637: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2638: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2639: &escape($newentry)).':'.$group,$chome);
1.292 www 2640: }
2641:
2642: # ------------------------------------------ Find current version of a resource
2643:
2644: sub getversion {
2645: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2646: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2647: return ¤tversion(&filelocation('',$fname));
2648: }
2649:
2650: sub currentversion {
2651: my $fname=shift;
2652: my $author=$fname;
2653: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2654: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2655: my $home=&homeserver($uname,$udom);
1.292 www 2656: if ($home eq 'no_host') {
2657: return -1;
2658: }
1.1112 www 2659: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2660: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2661: return -1;
2662: }
1.1112 www 2663: return $answer;
1.263 www 2664: }
2665:
1.1111 www 2666: #
2667: # Return special version number of resource if set by override, empty otherwise
2668: #
2669: sub usedversion {
2670: my $fname=shift;
2671: unless ($fname) { $fname=$env{'request.uri'}; }
2672: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2673: if ($urlversion) { return $urlversion; }
2674: return '';
2675: }
2676:
1.1 albertel 2677: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2678:
1.1 albertel 2679: sub subscribe {
2680: my $fname=shift;
1.761 raeburn 2681: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2682: $fname=~s/[\n\r]//g;
1.1 albertel 2683: my $author=$fname;
2684: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2685: my ($udom,$uname)=split(/\//,$author);
2686: my $home=homeserver($uname,$udom);
1.335 albertel 2687: if ($home eq 'no_host') {
2688: return 'not_found';
1.1 albertel 2689: }
2690: my $answer=reply("sub:$fname",$home);
1.64 www 2691: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2692: $answer.=' by '.$home;
2693: }
1.1 albertel 2694: return $answer;
2695: }
2696:
1.8 www 2697: # -------------------------------------------------------------- Replicate file
2698:
2699: sub repcopy {
2700: my $filename=shift;
1.23 www 2701: $filename=~s/\/+/\//g;
1.1142 raeburn 2702: my $londocroot = $perlvar{'lonDocRoot'};
2703: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2704: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2705: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2706: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2707: return &repcopy_userfile($filename);
2708: }
1.532 albertel 2709: $filename=~s/[\n\r]//g;
1.8 www 2710: my $transname="$filename.in.transfer";
1.828 www 2711: # FIXME: this should flock
1.607 raeburn 2712: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2713: my $remoteurl=subscribe($filename);
1.64 www 2714: if ($remoteurl =~ /^con_lost by/) {
2715: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2716: return 'unavailable';
1.8 www 2717: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2718: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2719: return 'not_found';
1.64 www 2720: } elsif ($remoteurl =~ /^rejected by/) {
2721: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2722: return 'forbidden';
1.20 www 2723: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2724: return 'ok';
1.8 www 2725: } else {
1.290 www 2726: my $author=$filename;
2727: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2728: my ($udom,$uname)=split(/\//,$author);
2729: my $home=homeserver($uname,$udom);
2730: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2731: my @parts=split(/\//,$filename);
2732: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2733: if ($path ne "$londocroot/res") {
1.8 www 2734: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2735: return 'bad_request';
1.8 www 2736: }
2737: my $count;
2738: for ($count=5;$count<$#parts;$count++) {
2739: $path.="/$parts[$count]";
2740: if ((-e $path)!=1) {
2741: mkdir($path,0777);
2742: }
2743: }
2744: my $ua=new LWP::UserAgent;
2745: my $request=new HTTP::Request('GET',"$remoteurl");
2746: my $response=$ua->request($request,$transname);
2747: if ($response->is_error()) {
2748: unlink($transname);
2749: my $message=$response->status_line;
1.672 albertel 2750: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2751: ." LWP get: $message: $filename</font>");
1.607 raeburn 2752: return 'unavailable';
1.8 www 2753: } else {
1.16 www 2754: if ($remoteurl!~/\.meta$/) {
2755: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2756: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2757: if ($mresponse->is_error()) {
2758: unlink($filename.'.meta');
2759: &logthis(
1.672 albertel 2760: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2761: }
2762: }
1.8 www 2763: rename($transname,$filename);
1.607 raeburn 2764: return 'ok';
1.8 www 2765: }
1.290 www 2766: }
1.8 www 2767: }
1.330 www 2768: }
2769:
2770: # ------------------------------------------------ Get server side include body
2771: sub ssi_body {
1.381 albertel 2772: my ($filelink,%form)=@_;
1.606 matthew 2773: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2774: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2775: }
1.953 www 2776: my $output='';
2777: my $response;
1.980 raeburn 2778: if ($filelink=~/^https?\:/) {
1.954 raeburn 2779: ($output,$response)=&externalssi($filelink);
1.953 www 2780: } else {
1.1004 droeschl 2781: $filelink .= $filelink=~/\?/ ? '&' : '?';
2782: $filelink .= 'inhibitmenu=yes';
1.953 www 2783: ($output,$response)=&ssi($filelink,%form);
2784: }
1.778 albertel 2785: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2786: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2787: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2788: if (wantarray) {
2789: return ($output, $response);
2790: } else {
2791: return $output;
2792: }
1.8 www 2793: }
2794:
1.15 www 2795: # --------------------------------------------------------- Server Side Include
2796:
1.782 albertel 2797: sub absolute_url {
2798: my ($host_name) = @_;
2799: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2800: if ($host_name eq '') {
2801: $host_name = $ENV{'SERVER_NAME'};
2802: }
2803: return $protocol.$host_name;
2804: }
2805:
1.942 foxr 2806: #
2807: # Server side include.
2808: # Parameters:
2809: # fn Possibly encrypted resource name/id.
2810: # form Hash that describes how the rendering should be done
2811: # and other things.
1.944 foxr 2812: # Returns:
1.950 raeburn 2813: # Scalar context: The content of the response.
2814: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2815: #
1.15 www 2816: sub ssi {
2817:
1.944 foxr 2818: my ($fn,%form)=@_;
1.15 www 2819: my $ua=new LWP::UserAgent;
1.23 www 2820: my $request;
1.711 albertel 2821:
2822: $form{'no_update_last_known'}=1;
1.895 albertel 2823: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2824: if (%form) {
1.782 albertel 2825: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2826: $request->content(join('&',map {
2827: my $name = escape($_);
2828: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2829: ? join("&$name=", map {escape($_) } @{$form{$_}})
2830: : &escape($form{$_}) );
2831: } keys(%form)));
1.23 www 2832: } else {
1.782 albertel 2833: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2834: }
2835:
1.15 www 2836: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2837: my $response= $ua->request($request);
1.944 foxr 2838: if (wantarray) {
1.1172.2.3 raeburn 2839: return ($response->content, $response);
1.944 foxr 2840: } else {
1.1172.2.3 raeburn 2841: return $response->content;
1.942 foxr 2842: }
1.324 www 2843: }
2844:
2845: sub externalssi {
2846: my ($url)=@_;
2847: my $ua=new LWP::UserAgent;
2848: my $request=new HTTP::Request('GET',$url);
2849: my $response=$ua->request($request);
1.954 raeburn 2850: if (wantarray) {
2851: return ($response->content, $response);
2852: } else {
2853: return $response->content;
2854: }
1.15 www 2855: }
1.254 www 2856:
1.492 albertel 2857: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2858:
2859: sub allowuploaded {
2860: my ($srcurl,$url)=@_;
2861: $url=&clutter(&declutter($url));
2862: my $dir=$url;
2863: $dir=~s/\/[^\/]+$//;
2864: my %httpref=();
2865: my $httpurl=&hreflocation('',$url);
2866: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2867: &Apache::lonnet::appenv(\%httpref);
1.254 www 2868: }
1.477 raeburn 2869:
1.1172.2.13 raeburn 2870: #
2871: # Determine if the current user should be able to edit a particular resource,
2872: # when viewing in course context.
2873: # (a) When viewing resource used to determine if "Edit" item is included in
2874: # Functions.
2875: # (b) When displaying folder contents in course editor, used to determine if
2876: # "Edit" link will be displayed alongside resource.
2877: #
2878: # input: six args -- filename (decluttered), course number, course domain,
2879: # url, symb (if registered) and group (if this is a group
2880: # item -- e.g., bulletin board, group page etc.).
2881: # output: array of five scalars --
2882: # $cfile -- url for file editing if editable on current server
2883: # $home -- homeserver of resource (i.e., for author if published,
2884: # or course if uploaded.).
2885: # $switchserver -- 1 if server switch will be needed.
2886: # $forceedit -- 1 if icon/link should be to go to edit mode
2887: # $forceview -- 1 if icon/link should be to go to view mode
2888: #
2889:
2890: sub can_edit_resource {
2891: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2892: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2893: #
2894: # For aboutme pages user can only edit his/her own.
2895: #
2896: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2897: my ($sdom,$sname) = ($1,$2);
2898: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2899: $home = $env{'user.home'};
2900: $cfile = $resurl;
2901: if ($env{'form.forceedit'}) {
2902: $forceview = 1;
2903: } else {
2904: $forceedit = 1;
2905: }
2906: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2907: } else {
2908: return;
2909: }
2910: }
2911:
2912: if ($env{'request.course.id'}) {
2913: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2914: if ($group ne '') {
2915: # if this is a group homepage or group bulletin board, check group privs
2916: my $allowed = 0;
2917: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2918: if ((&allowed('mdg',$env{'request.course.id'}.
2919: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2920: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2921: $allowed = 1;
2922: }
2923: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2924: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2925: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2926: $allowed = 1;
2927: }
2928: }
2929: if ($allowed) {
2930: $home=&homeserver($cnum,$cdom);
2931: if ($env{'form.forceedit'}) {
2932: $forceview = 1;
2933: } else {
2934: $forceedit = 1;
2935: }
2936: $cfile = $resurl;
2937: } else {
2938: return;
2939: }
2940: } else {
1.1172.2.15 raeburn 2941: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2942: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2943: return;
2944: }
2945: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2946: #
2947: # No edit allowed where CC has switched to student role.
2948: #
2949: return;
2950: }
2951: }
2952: }
2953:
2954: if ($file ne '') {
2955: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2956: if (&is_course_upload($file,$cnum,$cdom)) {
2957: $uploaded = 1;
2958: $incourse = 1;
2959: if ($file =~/\.(htm|html|css|js|txt)$/) {
2960: $cfile = &hreflocation('',$file);
2961: if ($env{'form.forceedit'}) {
2962: $forceview = 1;
2963: } else {
2964: $forceedit = 1;
2965: }
2966: }
2967: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2968: $incourse = 1;
2969: if ($env{'form.forceedit'}) {
2970: $forceview = 1;
2971: } else {
2972: $forceedit = 1;
2973: }
2974: $cfile = $resurl;
2975: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2976: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2977: $incourse = 1;
2978: if ($env{'form.forceedit'}) {
2979: $forceview = 1;
2980: } else {
2981: $forceedit = 1;
2982: }
2983: $cfile = $resurl;
2984: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2985: $incourse = 1;
2986: $cfile = $resurl.'/smpedit';
2987: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2988: $incourse = 1;
2989: if ($env{'form.forceedit'}) {
2990: $forceview = 1;
2991: } else {
2992: $forceedit = 1;
2993: }
2994: $cfile = $resurl;
1.1172.2.15 raeburn 2995: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2996: $incourse = 1;
2997: if ($env{'form.forceedit'}) {
2998: $forceview = 1;
2999: } else {
3000: $forceedit = 1;
3001: }
3002: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3003: }
3004: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3005: my $template = '/res/lib/templates/simpleproblem.problem';
3006: if (&is_on_map($template)) {
3007: $incourse = 1;
3008: $forceview = 1;
3009: $cfile = $template;
3010: }
3011: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3012: $incourse = 1;
3013: if ($env{'form.forceedit'}) {
3014: $forceview = 1;
3015: } else {
3016: $forceedit = 1;
3017: }
3018: $cfile = $resurl;
3019: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3020: $incourse = 1;
3021: $forceview = 1;
3022: if ($symb) {
3023: my ($map,$id,$res)=&decode_symb($symb);
3024: $env{'request.symb'} = $symb;
3025: $cfile = &clutter($res);
3026: } else {
3027: $cfile = $env{'form.suppurl'};
3028: $cfile =~ s{^http://}{};
3029: $cfile = '/adm/wrapper/ext/'.$cfile;
3030: }
1.1172.2.31 raeburn 3031: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3032: if ($env{'form.forceedit'}) {
3033: $forceview = 1;
3034: } else {
3035: $forceedit = 1;
3036: }
3037: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3038: }
3039: }
3040: if ($uploaded || $incourse) {
3041: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3042: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3043: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3044: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3045: # Check that the user has permission to edit this resource
3046: my $setpriv = 1;
3047: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3048: if (defined($cfudom)) {
3049: $home=&homeserver($cfuname,$cfudom);
3050: $cfile=$file;
3051: }
3052: }
3053: if (($cfile ne '') && (!$incourse || $uploaded) &&
3054: (($home ne '') && ($home ne 'no_host'))) {
3055: my @ids=¤t_machine_ids();
3056: unless (grep(/^\Q$home\E$/,@ids)) {
3057: $switchserver=1;
3058: }
3059: }
3060: }
3061: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3062: }
3063:
3064: sub is_course_upload {
3065: my ($file,$cnum,$cdom) = @_;
3066: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3067: $uploadpath =~ s{^\/}{};
3068: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3069: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3070: return 1;
3071: }
3072: return;
3073: }
3074:
3075: sub in_course {
3076: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3077: if ($hideprivileged) {
3078: my $skipuser;
1.1172.2.23 raeburn 3079: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3080: my @possdoms = ($cdom);
3081: if ($coursehash{'checkforpriv'}) {
3082: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3083: }
3084: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3085: $skipuser = 1;
3086: if ($coursehash{'nothideprivileged'}) {
3087: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3088: my $user;
3089: if ($item =~ /:/) {
3090: $user = $item;
3091: } else {
3092: $user = join(':',split(/[\@]/,$item));
3093: }
3094: if ($user eq $uname.':'.$udom) {
3095: undef($skipuser);
3096: last;
3097: }
3098: }
3099: }
3100: if ($skipuser) {
3101: return 0;
3102: }
3103: }
3104: }
3105: $type ||= 'any';
3106: if (!defined($cdom) || !defined($cnum)) {
3107: my $cid = $env{'request.course.id'};
3108: $cdom = $env{'course.'.$cid.'.domain'};
3109: $cnum = $env{'course.'.$cid.'.num'};
3110: }
3111: my $typesref;
3112: if (($type eq 'any') || ($type eq 'all')) {
3113: $typesref = ['active','previous','future'];
3114: } elsif ($type eq 'previous' || $type eq 'future') {
3115: $typesref = [$type];
3116: }
3117: my %roles = &get_my_roles($uname,$udom,'userroles',
3118: $typesref,undef,[$cdom]);
3119: my ($tmp) = keys(%roles);
3120: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3121: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3122: if (@course_roles > 0) {
3123: return 1;
3124: }
3125: return 0;
3126: }
3127:
1.478 albertel 3128: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3129: # input: action, courseID, current domain, intended
1.637 raeburn 3130: # path to file, source of file, instruction to parse file for objects,
3131: # ref to hash for embedded objects,
3132: # ref to hash for codebase of java objects.
1.1095 raeburn 3133: # reference to scalar to accommodate mime type determined
3134: # from File::MMagic if $parser = parse.
1.637 raeburn 3135: #
1.485 raeburn 3136: # output: url to file (if action was uploaddoc),
3137: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3138: #
1.478 albertel 3139: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3140: # course.
1.477 raeburn 3141: #
1.478 albertel 3142: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3143: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3144: # course's home server.
1.477 raeburn 3145: #
1.478 albertel 3146: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3147: # be copied from $source (current location) to
3148: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3149: # and will then be copied to
3150: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3151: # course's home server.
1.485 raeburn 3152: #
1.481 raeburn 3153: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3154: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3155: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3156: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3157: # in course's home server.
1.637 raeburn 3158: #
1.477 raeburn 3159:
3160: sub process_coursefile {
1.1095 raeburn 3161: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3162: $mimetype)=@_;
1.477 raeburn 3163: my $fetchresult;
1.638 albertel 3164: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3165: if ($action eq 'propagate') {
1.638 albertel 3166: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3167: $home);
1.481 raeburn 3168: } else {
1.477 raeburn 3169: my $fpath = '';
3170: my $fname = $file;
1.478 albertel 3171: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3172: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3173: my $filepath = &build_filepath($fpath);
1.481 raeburn 3174: if ($action eq 'copy') {
3175: if ($source eq '') {
3176: $fetchresult = 'no source file';
3177: return $fetchresult;
3178: } else {
3179: my $destination = $filepath.'/'.$fname;
3180: rename($source,$destination);
3181: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3182: $home);
1.481 raeburn 3183: }
3184: } elsif ($action eq 'uploaddoc') {
3185: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3186: print $fh $env{'form.'.$source};
1.481 raeburn 3187: close($fh);
1.637 raeburn 3188: if ($parser eq 'parse') {
1.1024 raeburn 3189: my $mm = new File::MMagic;
1.1095 raeburn 3190: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3191: if ($type eq 'text/html') {
1.1024 raeburn 3192: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3193: unless ($parse_result eq 'ok') {
3194: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3195: }
1.637 raeburn 3196: }
1.1095 raeburn 3197: if (ref($mimetype)) {
3198: $$mimetype = $type;
3199: }
1.637 raeburn 3200: }
1.477 raeburn 3201: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3202: $home);
1.481 raeburn 3203: if ($fetchresult eq 'ok') {
3204: return '/uploaded/'.$fpath.'/'.$fname;
3205: } else {
3206: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3207: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3208: return '/adm/notfound.html';
3209: }
1.477 raeburn 3210: }
3211: }
1.485 raeburn 3212: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3213: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3214: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3215: }
3216: return $fetchresult;
3217: }
3218:
1.637 raeburn 3219: sub build_filepath {
3220: my ($fpath) = @_;
3221: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3222: unless ($fpath eq '') {
3223: my @parts=split('/',$fpath);
3224: foreach my $part (@parts) {
3225: $filepath.= '/'.$part;
3226: if ((-e $filepath)!=1) {
3227: mkdir($filepath,0777);
3228: }
3229: }
3230: }
3231: return $filepath;
3232: }
3233:
3234: sub store_edited_file {
1.638 albertel 3235: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3236: my $file = $primary_url;
3237: $file =~ s#^/uploaded/$docudom/$docuname/##;
3238: my $fpath = '';
3239: my $fname = $file;
3240: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3241: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3242: my $filepath = &build_filepath($fpath);
3243: open(my $fh,'>'.$filepath.'/'.$fname);
3244: print $fh $content;
3245: close($fh);
1.638 albertel 3246: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3247: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3248: $home);
1.637 raeburn 3249: if ($$fetchresult eq 'ok') {
3250: return '/uploaded/'.$fpath.'/'.$fname;
3251: } else {
1.638 albertel 3252: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3253: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3254: return '/adm/notfound.html';
3255: }
3256: }
3257:
1.531 albertel 3258: sub clean_filename {
1.831 albertel 3259: my ($fname,$args)=@_;
1.315 www 3260: # Replace Windows backslashes by forward slashes
1.257 www 3261: $fname=~s/\\/\//g;
1.831 albertel 3262: if (!$args->{'keep_path'}) {
3263: # Get rid of everything but the actual filename
3264: $fname=~s/^.*\/([^\/]+)$/$1/;
3265: }
1.315 www 3266: # Replace spaces by underscores
3267: $fname=~s/\s+/\_/g;
3268: # Replace all other weird characters by nothing
1.831 albertel 3269: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3270: # Replace all .\d. sequences with _\d. so they no longer look like version
3271: # numbers
3272: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3273: return $fname;
3274: }
1.1051 raeburn 3275: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3276: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3277: # image with the same aspect ratio as the original, but with dimensions which do
3278: # not exceed $resizewidth and $resizeheight.
3279:
1.984 neumanie 3280: sub resizeImage {
1.1051 raeburn 3281: my ($img_path,$resizewidth,$resizeheight) = @_;
3282: my $ima = Image::Magick->new;
3283: my $resized;
3284: if (-e $img_path) {
3285: $ima->Read($img_path);
3286: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3287: my $width = $ima->Get('width');
3288: my $height = $ima->Get('height');
3289: if ($width > $resizewidth) {
3290: my $factor = $width/$resizewidth;
3291: my $newheight = $height/$factor;
3292: $ima->Scale(width=>$resizewidth,height=>$newheight);
3293: $resized = 1;
3294: }
3295: }
3296: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3297: my $width = $ima->Get('width');
3298: my $height = $ima->Get('height');
3299: if ($height > $resizeheight) {
3300: my $factor = $height/$resizeheight;
3301: my $newwidth = $width/$factor;
3302: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3303: $resized = 1;
3304: }
3305: }
3306: if ($resized) {
3307: $ima->Write($img_path);
3308: }
3309: }
3310: return;
1.977 amueller 3311: }
3312:
1.608 albertel 3313: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3314: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3315: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3316: # $context - possible values: coursedoc, existingfile, overwrite,
3317: # canceloverwrite, or ''.
3318: # if 'coursedoc': upload to the current course
3319: # if 'existingfile': write file to tmp/overwrites directory
3320: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3321: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3322: # $subdir - directory in userfile to store the file into
1.858 raeburn 3323: # $parser - instruction to parse file for objects ($parser = parse)
3324: # $allfiles - reference to hash for embedded objects
3325: # $codebase - reference to hash for codebase of java objects
3326: # $desuname - username for permanent storage of uploaded file
3327: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3328: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3329: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3330: # $resizewidth - width (pixels) to which to resize uploaded image
3331: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3332: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3333: # from File::MMagic.
1.858 raeburn 3334: #
1.686 albertel 3335: # output: url of file in userspace, or error: <message>
3336: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3337:
1.531 albertel 3338: sub userfileupload {
1.1090 raeburn 3339: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3340: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3341: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3342: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3343: $fname=&clean_filename($fname);
1.1090 raeburn 3344: # See if there is anything left
1.257 www 3345: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3346: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3347: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3348: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3349: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3350: my $now = time;
1.1090 raeburn 3351: my $filepath;
1.1095 raeburn 3352: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3353: $filepath = 'tmp/helprequests/'.$now;
3354: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3355: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3356: '_'.$env{'user.domain'}.'/pending';
3357: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3358: my ($docuname,$docudom);
3359: if ($destudom) {
3360: $docudom = $destudom;
3361: } else {
3362: $docudom = $env{'user.domain'};
3363: }
3364: if ($destuname) {
3365: $docuname = $destuname;
3366: } else {
3367: $docuname = $env{'user.name'};
3368: }
3369: if (exists($env{'form.group'})) {
3370: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3371: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3372: }
3373: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3374: if ($context eq 'canceloverwrite') {
3375: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3376: if (-e $tempfile) {
3377: my @info = stat($tempfile);
3378: if ($info[9] eq $env{'form.timestamp'}) {
3379: unlink($tempfile);
3380: }
3381: }
3382: return;
1.523 raeburn 3383: }
3384: }
1.1090 raeburn 3385: # Create the directory if not present
1.741 raeburn 3386: my @parts=split(/\//,$filepath);
3387: my $fullpath = $perlvar{'lonDaemons'};
3388: for (my $i=0;$i<@parts;$i++) {
3389: $fullpath .= '/'.$parts[$i];
3390: if ((-e $fullpath)!=1) {
3391: mkdir($fullpath,0777);
3392: }
3393: }
3394: open(my $fh,'>'.$fullpath.'/'.$fname);
3395: print $fh $env{'form.'.$formname};
3396: close($fh);
1.1090 raeburn 3397: if ($context eq 'existingfile') {
3398: my @info = stat($fullpath.'/'.$fname);
3399: return ($fullpath.'/'.$fname,$info[9]);
3400: } else {
3401: return $fullpath.'/'.$fname;
3402: }
1.523 raeburn 3403: }
1.995 raeburn 3404: if ($subdir eq 'scantron') {
3405: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3406: } else {
1.995 raeburn 3407: $fname="$subdir/$fname";
3408: }
1.1090 raeburn 3409: if ($context eq 'coursedoc') {
1.638 albertel 3410: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3411: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3412: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3413: return &finishuserfileupload($docuname,$docudom,
3414: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3415: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3416: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3417: } else {
1.1172.2.21 raeburn 3418: if ($env{'form.folder'}) {
3419: $fname=$env{'form.folder'}.'/'.$fname;
3420: }
1.638 albertel 3421: return &process_coursefile('uploaddoc',$docuname,$docudom,
3422: $fname,$formname,$parser,
1.1095 raeburn 3423: $allfiles,$codebase,$mimetype);
1.481 raeburn 3424: }
1.719 banghart 3425: } elsif (defined($destuname)) {
3426: my $docuname=$destuname;
3427: my $docudom=$destudom;
1.860 raeburn 3428: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3429: $parser,$allfiles,$codebase,
1.1051 raeburn 3430: $thumbwidth,$thumbheight,
1.1095 raeburn 3431: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3432: } else {
1.638 albertel 3433: my $docuname=$env{'user.name'};
3434: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3435: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3436: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3437: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3438: }
1.860 raeburn 3439: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3440: $parser,$allfiles,$codebase,
1.1051 raeburn 3441: $thumbwidth,$thumbheight,
1.1095 raeburn 3442: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3443: }
1.271 www 3444: }
3445:
3446: sub finishuserfileupload {
1.860 raeburn 3447: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3448: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3449: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3450: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3451:
1.860 raeburn 3452: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3453: $file=$fname;
3454: if ($fname=~m|/|) {
3455: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3456: $path.=$fnamepath.'/';
3457: }
1.259 www 3458: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3459: my $count;
3460: for ($count=4;$count<=$#parts;$count++) {
3461: $filepath.="/$parts[$count]";
3462: if ((-e $filepath)!=1) {
3463: mkdir($filepath,0777);
3464: }
3465: }
1.984 neumanie 3466:
1.258 www 3467: # Save the file
3468: {
1.701 albertel 3469: if (!open(FH,'>'.$filepath.'/'.$file)) {
3470: &logthis('Failed to create '.$filepath.'/'.$file);
3471: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3472: return '/adm/notfound.html';
3473: }
1.1090 raeburn 3474: if ($context eq 'overwrite') {
1.1117 foxr 3475: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3476: my $target = $filepath.'/'.$file;
3477: if (-e $source) {
3478: my @info = stat($source);
3479: if ($info[9] eq $env{'form.timestamp'}) {
3480: unless (&File::Copy::move($source,$target)) {
3481: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3482: return "Moving from $source failed";
3483: }
3484: } else {
3485: return "Temporary file: $source had unexpected date/time for last modification";
3486: }
3487: } else {
3488: return "Temporary file: $source missing";
3489: }
3490: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3491: &logthis('Failed to write to '.$filepath.'/'.$file);
3492: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3493: return '/adm/notfound.html';
3494: }
1.570 albertel 3495: close(FH);
1.1051 raeburn 3496: if ($resizewidth && $resizeheight) {
3497: my $mm = new File::MMagic;
3498: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3499: if ($mime_type =~ m{^image/}) {
3500: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3501: }
1.977 amueller 3502: }
1.258 www 3503: }
1.1152 raeburn 3504: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3505: if (ref($mimetype)) {
3506: if ($$mimetype eq '') {
3507: my $mm = new File::MMagic;
3508: my $type = $mm->checktype_filename($filepath.'/'.$file);
3509: $$mimetype = $type;
3510: }
3511: }
3512: }
1.637 raeburn 3513: if ($parser eq 'parse') {
1.1152 raeburn 3514: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3515: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3516: $allfiles,$codebase);
3517: unless ($parse_result eq 'ok') {
3518: &logthis('Failed to parse '.$filepath.$file.
3519: ' for embedded media: '.$parse_result);
3520: }
1.637 raeburn 3521: }
3522: }
1.860 raeburn 3523: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3524: my $input = $filepath.'/'.$file;
3525: my $output = $filepath.'/'.'tn-'.$file;
3526: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3527: system("convert -sample $thumbsize $input $output");
3528: if (-e $filepath.'/'.'tn-'.$file) {
3529: $fetchthumb = 1;
3530: }
3531: }
1.858 raeburn 3532:
1.259 www 3533: # Notify homeserver to grep it
3534: #
1.984 neumanie 3535: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3536: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3537: if ($fetchresult eq 'ok') {
1.860 raeburn 3538: if ($fetchthumb) {
3539: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3540: if ($thumbresult ne 'ok') {
3541: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3542: $docuhome.': '.$thumbresult);
3543: }
3544: }
1.259 www 3545: #
1.258 www 3546: # Return the URL to it
1.494 albertel 3547: return '/uploaded/'.$path.$file;
1.263 www 3548: } else {
1.494 albertel 3549: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3550: ': '.$fetchresult);
1.263 www 3551: return '/adm/notfound.html';
1.858 raeburn 3552: }
1.493 albertel 3553: }
3554:
1.637 raeburn 3555: sub extract_embedded_items {
1.961 raeburn 3556: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3557: my @state = ();
1.1164 raeburn 3558: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3559: my %javafiles = (
3560: codebase => '',
3561: code => '',
3562: archive => ''
3563: );
3564: my %mediafiles = (
3565: src => '',
3566: movie => '',
3567: );
1.648 raeburn 3568: my $p;
3569: if ($content) {
3570: $p = HTML::LCParser->new($content);
3571: } else {
1.961 raeburn 3572: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3573: }
1.641 albertel 3574: while (my $t=$p->get_token()) {
1.640 albertel 3575: if ($t->[0] eq 'S') {
3576: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3577: push(@state, $tagname);
1.648 raeburn 3578: if (lc($tagname) eq 'allow') {
3579: &add_filetype($allfiles,$attr->{'src'},'src');
3580: }
1.640 albertel 3581: if (lc($tagname) eq 'img') {
3582: &add_filetype($allfiles,$attr->{'src'},'src');
3583: }
1.886 albertel 3584: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3585: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3586: &add_filetype($allfiles,$attr->{'href'},'href');
3587: }
1.886 albertel 3588: }
1.645 raeburn 3589: if (lc($tagname) eq 'script') {
1.1164 raeburn 3590: my $src;
1.645 raeburn 3591: if ($attr->{'archive'} =~ /\.jar$/i) {
3592: &add_filetype($allfiles,$attr->{'archive'},'archive');
3593: } else {
1.1164 raeburn 3594: if ($attr->{'src'} ne '') {
3595: $src = $attr->{'src'};
3596: &add_filetype($allfiles,$src,'src');
3597: }
3598: }
3599: my $text = $p->get_trimmed_text();
3600: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3601: my @swfargs = split(/,/,$1);
3602: foreach my $item (@swfargs) {
3603: $item =~ s/["']//g;
3604: $item =~ s/^\s+//;
3605: $item =~ s/\s+$//;
3606: }
3607: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3608: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3609: push(@{$related{$swfargs[0]}},$swfargs[2]);
3610: } else {
3611: $related{$swfargs[0]} = [$swfargs[2]];
3612: }
3613: }
1.645 raeburn 3614: }
3615: }
3616: if (lc($tagname) eq 'link') {
3617: if (lc($attr->{'rel'}) eq 'stylesheet') {
3618: &add_filetype($allfiles,$attr->{'href'},'href');
3619: }
3620: }
1.640 albertel 3621: if (lc($tagname) eq 'object' ||
3622: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3623: foreach my $item (keys(%javafiles)) {
3624: $javafiles{$item} = '';
3625: }
1.1164 raeburn 3626: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3627: $lastids{lc($tagname)} = $attr->{'id'};
3628: }
1.640 albertel 3629: }
3630: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3631: my $name = lc($attr->{'name'});
3632: foreach my $item (keys(%javafiles)) {
3633: if ($name eq $item) {
3634: $javafiles{$item} = $attr->{'value'};
3635: last;
3636: }
3637: }
1.1164 raeburn 3638: my $pathfrom;
1.640 albertel 3639: foreach my $item (keys(%mediafiles)) {
3640: if ($name eq $item) {
1.1164 raeburn 3641: $pathfrom = $attr->{'value'};
3642: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3643: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3644: last;
3645: }
3646: }
1.1164 raeburn 3647: if ($name eq 'flashvars') {
3648: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3649: }
3650: if ($pathfrom ne '') {
3651: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3652: $pathfrom);
3653: }
1.640 albertel 3654: }
3655: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3656: foreach my $item (keys(%javafiles)) {
3657: if ($attr->{$item}) {
3658: $javafiles{$item} = $attr->{$item};
3659: last;
3660: }
3661: }
3662: foreach my $item (keys(%mediafiles)) {
3663: if ($attr->{$item}) {
3664: &add_filetype($allfiles,$attr->{$item},$item);
3665: last;
3666: }
3667: }
1.1164 raeburn 3668: if (lc($tagname) eq 'embed') {
3669: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3670: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3671: $attr->{'src'});
3672: }
3673: }
1.640 albertel 3674: }
1.1172.2.35 raeburn 3675: if (lc($tagname) eq 'iframe') {
3676: my $src = $attr->{'src'} ;
3677: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3678: &add_filetype($allfiles,$src,'src');
3679: } elsif ($src =~ m{^/}) {
3680: if ($env{'request.course.id'}) {
3681: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3682: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3683: my $url = &hreflocation('',$fullpath);
3684: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3685: my $relpath = $1;
3686: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3687: &add_filetype($allfiles,$1,'src');
3688: }
3689: }
3690: }
3691: }
3692: }
1.1164 raeburn 3693: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3694: pop(@state);
1.1164 raeburn 3695: }
1.640 albertel 3696: } elsif ($t->[0] eq 'E') {
3697: my ($tagname) = ($t->[1]);
3698: if ($javafiles{'codebase'} ne '') {
3699: $javafiles{'codebase'} .= '/';
3700: }
3701: if (lc($tagname) eq 'applet' ||
3702: lc($tagname) eq 'object' ||
3703: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3704: ) {
3705: foreach my $item (keys(%javafiles)) {
3706: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3707: my $file=$javafiles{'codebase'}.$javafiles{$item};
3708: &add_filetype($allfiles,$file,$item);
3709: }
3710: }
3711: }
3712: pop @state;
3713: }
3714: }
1.1164 raeburn 3715: foreach my $id (sort(keys(%flashvars))) {
3716: if ($shockwave{$id} ne '') {
3717: my @pairs = split(/\&/,$flashvars{$id});
3718: foreach my $pair (@pairs) {
3719: my ($key,$value) = split(/\=/,$pair);
3720: if ($key eq 'thumb') {
3721: &add_filetype($allfiles,$value,$key);
3722: } elsif ($key eq 'content') {
3723: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3724: my ($ext) = ($value =~ /\.([^.]+)$/);
3725: if ($ext ne '') {
3726: &add_filetype($allfiles,$path.$value,$ext);
3727: }
3728: }
3729: }
3730: }
3731: }
1.637 raeburn 3732: return 'ok';
3733: }
3734:
1.639 albertel 3735: sub add_filetype {
3736: my ($allfiles,$file,$type)=@_;
3737: if (exists($allfiles->{$file})) {
3738: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3739: push(@{$allfiles->{$file}}, &escape($type));
3740: }
3741: } else {
3742: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3743: }
3744: }
3745:
1.1164 raeburn 3746: sub embedded_dependency {
3747: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3748: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3749: if (($identifier ne '') &&
3750: (ref($related->{$identifier}) eq 'ARRAY') &&
3751: ($pathfrom ne '')) {
3752: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3753: foreach my $dep (@{$related->{$identifier}}) {
3754: &add_filetype($allfiles,$path.$dep,'object');
3755: }
3756: }
3757: }
3758: return;
3759: }
3760:
1.493 albertel 3761: sub removeuploadedurl {
1.984 neumanie 3762: my ($url)=@_;
3763: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3764: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3765: }
3766:
3767: sub removeuserfile {
3768: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3769: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3770: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3771: if ($result eq 'ok') {
1.798 raeburn 3772: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3773: my $metafile = $fname.'.meta';
3774: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3775: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3776: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3777: my $sqlresult =
1.823 albertel 3778: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3779: 'portfolio_metadata',$group,
3780: 'delete');
1.798 raeburn 3781: }
3782: }
3783: return $result;
1.257 www 3784: }
1.15 www 3785:
1.530 albertel 3786: sub mkdiruserfile {
3787: my ($docuname,$docudom,$dir)=@_;
3788: my $home=&homeserver($docuname,$docudom);
3789: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3790: }
3791:
1.531 albertel 3792: sub renameuserfile {
3793: my ($docuname,$docudom,$old,$new)=@_;
3794: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3795: my $result = &reply("renameuserfile:$docudom:$docuname:".
3796: &escape("$old").':'.&escape("$new"),$home);
3797: if ($result eq 'ok') {
3798: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3799: my $oldmeta = $old.'.meta';
3800: my $newmeta = $new.'.meta';
3801: my $metaresult =
3802: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3803: my $url = "/uploaded/$docudom/$docuname/$old";
3804: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3805: my $sqlresult =
1.823 albertel 3806: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3807: 'portfolio_metadata',$group,
3808: 'delete');
1.798 raeburn 3809: }
3810: }
3811: return $result;
1.531 albertel 3812: }
3813:
1.14 www 3814: # ------------------------------------------------------------------------- Log
3815:
3816: sub log {
3817: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3818: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3819: }
3820:
3821: # ------------------------------------------------------------------ Course Log
1.352 www 3822: #
3823: # This routine flushes several buffers of non-mission-critical nature
3824: #
1.157 www 3825:
3826: sub flushcourselogs {
1.352 www 3827: &logthis('Flushing log buffers');
3828: #
3829: # course logs
3830: # This is a log of all transactions in a course, which can be used
3831: # for data mining purposes
3832: #
3833: # It also collects the courseid database, which lists last transaction
3834: # times and course titles for all courseids
3835: #
3836: my %courseidbuffer=();
1.921 raeburn 3837: foreach my $crsid (keys(%courselogs)) {
1.352 www 3838: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3839: &escape($courselogs{$crsid}),
3840: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3841: delete $courselogs{$crsid};
3842: } else {
3843: &logthis('Failed to flush log buffer for '.$crsid);
3844: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3845: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3846: " exceeded maximum size, deleting.</font>");
3847: delete $courselogs{$crsid};
3848: }
1.352 www 3849: }
1.920 raeburn 3850: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3851: 'description' => $coursedescrbuf{$crsid},
3852: 'inst_code' => $courseinstcodebuf{$crsid},
3853: 'type' => $coursetypebuf{$crsid},
3854: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3855: };
1.191 harris41 3856: }
1.352 www 3857: #
3858: # Write course id database (reverse lookup) to homeserver of courses
3859: # Is used in pickcourse
3860: #
1.840 albertel 3861: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3862: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3863: $courseidbuffer{$crs_home},
3864: $crs_home,'timeonly');
1.352 www 3865: }
3866: #
3867: # File accesses
3868: # Writes to the dynamic metadata of resources to get hit counts, etc.
3869: #
1.449 matthew 3870: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3871: if ($entry =~ /___count$/) {
3872: my ($dom,$name);
1.807 albertel 3873: ($dom,$name,undef)=
1.811 albertel 3874: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3875: if (! defined($dom) || $dom eq '' ||
3876: ! defined($name) || $name eq '') {
1.620 albertel 3877: my $cid = $env{'request.course.id'};
3878: $dom = $env{'request.'.$cid.'.domain'};
3879: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3880: }
1.450 matthew 3881: my $value = $accesshash{$entry};
3882: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3883: my %temphash=($url => $value);
1.449 matthew 3884: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3885: if ($result eq 'ok') {
3886: delete $accesshash{$entry};
3887: }
3888: } else {
1.811 albertel 3889: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3890: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3891: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3892: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3893: delete $accesshash{$entry};
3894: }
1.185 www 3895: }
1.191 harris41 3896: }
1.352 www 3897: #
3898: # Roles
3899: # Reverse lookup of user roles for course faculty/staff and co-authorship
3900: #
1.800 albertel 3901: foreach my $entry (keys(%userrolehash)) {
1.351 www 3902: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3903: split(/\:/,$entry);
3904: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3905: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3906: $rudom,$runame) eq 'ok') {
3907: delete $userrolehash{$entry};
3908: }
3909: }
1.662 raeburn 3910: #
1.1172.2.84! raeburn 3911: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662 raeburn 3912: #
3913: my %domrolebuffer = ();
1.1000 raeburn 3914: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3915: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3916: if ($domrolebuffer{$rudom}) {
3917: $domrolebuffer{$rudom}.='&'.&escape($entry).
3918: '='.&escape($domainrolehash{$entry});
3919: } else {
3920: $domrolebuffer{$rudom}.=&escape($entry).
3921: '='.&escape($domainrolehash{$entry});
3922: }
3923: delete $domainrolehash{$entry};
3924: }
3925: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 3926: my %servers;
3927: if (defined(&domain($dom,'primary'))) {
3928: my $primary=&domain($dom,'primary');
3929: my $hostname=&hostname($primary);
3930: $servers{$primary} = $hostname;
3931: } else {
3932: %servers = &get_servers($dom,'library');
3933: }
1.841 albertel 3934: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 3935: if (&reply('domroleput:'.$dom.':'.
3936: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3937: last;
3938: } else {
1.841 albertel 3939: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3940: }
1.662 raeburn 3941: }
3942: }
1.186 www 3943: $dumpcount++;
1.157 www 3944: }
3945:
3946: sub courselog {
3947: my $what=shift;
1.158 www 3948: $what=time.':'.$what;
1.620 albertel 3949: unless ($env{'request.course.id'}) { return ''; }
3950: $coursedombuf{$env{'request.course.id'}}=
3951: $env{'course.'.$env{'request.course.id'}.'.domain'};
3952: $coursenumbuf{$env{'request.course.id'}}=
3953: $env{'course.'.$env{'request.course.id'}.'.num'};
3954: $coursehombuf{$env{'request.course.id'}}=
3955: $env{'course.'.$env{'request.course.id'}.'.home'};
3956: $coursedescrbuf{$env{'request.course.id'}}=
3957: $env{'course.'.$env{'request.course.id'}.'.description'};
3958: $courseinstcodebuf{$env{'request.course.id'}}=
3959: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3960: $courseownerbuf{$env{'request.course.id'}}=
3961: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3962: $coursetypebuf{$env{'request.course.id'}}=
3963: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3964: if (defined $courselogs{$env{'request.course.id'}}) {
3965: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3966: } else {
1.620 albertel 3967: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3968: }
1.620 albertel 3969: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3970: &flushcourselogs();
3971: }
1.158 www 3972: }
3973:
3974: sub courseacclog {
3975: my $fnsymb=shift;
1.620 albertel 3976: unless ($env{'request.course.id'}) { return ''; }
3977: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3978: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3979: $what.=':POST';
1.583 matthew 3980: # FIXME: Probably ought to escape things....
1.800 albertel 3981: foreach my $key (keys(%env)) {
3982: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3983: my $formitem = $1;
3984: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3985: $what.=':'.$formitem.'='.$env{$key};
3986: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3987: $what.=':'.$formitem.'='.$env{$key};
3988: }
1.158 www 3989: }
1.191 harris41 3990: }
1.583 matthew 3991: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3992: # FIXME: We should not be depending on a form parameter that someone
3993: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3994: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3995: $what.= ':POST';
3996: # FIXME: Probably ought to escape things....
3997: foreach my $element ('courseexp','crsfulltext','crsrelated',
3998: 'crsdiscuss') {
1.620 albertel 3999: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4000: }
4001: }
1.158 www 4002: }
4003: &courselog($what);
1.149 www 4004: }
4005:
1.185 www 4006: sub countacc {
4007: my $url=&declutter(shift);
1.458 matthew 4008: return if (! defined($url) || $url eq '');
1.620 albertel 4009: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4010: #
4011: # Mark that this url was used in this course
4012: #
1.620 albertel 4013: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4014: #
4015: # Increase the access count for this resource in this child process
4016: #
1.281 www 4017: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4018: $accesshash{$key}++;
1.185 www 4019: }
1.349 www 4020:
1.361 www 4021: sub linklog {
4022: my ($from,$to)=@_;
4023: $from=&declutter($from);
4024: $to=&declutter($to);
4025: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4026: $accesshash{$to.'___'.$from.'___goto'}=1;
4027: }
1.1160 www 4028:
4029: sub statslog {
4030: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4031: if ($users<2) { return; }
4032: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4033: 'course' => $env{'request.course.id'},
4034: 'sections' => '"all"',
4035: 'num_students' => $users,
4036: 'part' => $part,
4037: 'symb' => $symb,
4038: 'mean_tries' => $av_attempts,
4039: 'deg_of_diff' => $degdiff});
4040: foreach my $key (keys(%dynstore)) {
4041: $accesshash{$key}=$dynstore{$key};
4042: }
4043: }
1.361 www 4044:
1.349 www 4045: sub userrolelog {
4046: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4047: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4048: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4049: $userrolehash
4050: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4051: =$tend.':'.$tstart;
1.662 raeburn 4052: }
1.1169 droeschl 4053: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4054: $userrolehash
4055: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4056: =$tend.':'.$tstart;
4057: }
1.1172.2.84! raeburn 4058: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662 raeburn 4059: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4060: $domainrolehash
4061: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4062: = $tend.':'.$tstart;
4063: }
1.351 www 4064: }
4065:
1.957 raeburn 4066: sub courserolelog {
4067: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4068: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4069: my $cdom = $1;
4070: my $cnum = $2;
4071: my $sec = $3;
4072: my $namespace = 'rolelog';
4073: my %storehash = (
4074: role => $trole,
4075: start => $tstart,
4076: end => $tend,
4077: selfenroll => $selfenroll,
4078: context => $context,
4079: );
4080: if ($trole eq 'gr') {
4081: $namespace = 'groupslog';
4082: $storehash{'group'} = $sec;
4083: } else {
4084: $storehash{'section'} = $sec;
4085: }
4086: &write_log('course',$namespace,\%storehash,$delflag,$username,
4087: $domain,$cnum,$cdom);
4088: if (($trole ne 'st') || ($sec ne '')) {
4089: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4090: }
4091: }
4092: return;
4093: }
4094:
1.1172.2.9 raeburn 4095: sub domainrolelog {
4096: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4097: if ($area =~ m{^/($match_domain)/$}) {
4098: my $cdom = $1;
4099: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4100: my $namespace = 'rolelog';
4101: my %storehash = (
4102: role => $trole,
4103: start => $tstart,
4104: end => $tend,
4105: context => $context,
4106: );
4107: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4108: $domain,$domconfiguser,$cdom);
4109: }
4110: return;
4111:
4112: }
4113:
4114: sub coauthorrolelog {
4115: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4116: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4117: my $audom = $1;
4118: my $auname = $2;
4119: my $namespace = 'rolelog';
4120: my %storehash = (
4121: role => $trole,
4122: start => $tstart,
4123: end => $tend,
4124: context => $context,
4125: );
4126: &write_log('author',$namespace,\%storehash,$delflag,$username,
4127: $domain,$auname,$audom);
4128: }
4129: return;
4130: }
4131:
1.351 www 4132: sub get_course_adv_roles {
1.948 raeburn 4133: my ($cid,$codes) = @_;
1.620 albertel 4134: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4135: my %coursehash=&coursedescription($cid);
1.988 raeburn 4136: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4137: my %nothide=();
1.800 albertel 4138: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4139: if ($user !~ /:/) {
4140: $nothide{join(':',split(/[\@]/,$user))}=1;
4141: } else {
4142: $nothide{$user}=1;
4143: }
1.470 www 4144: }
1.1172.2.23 raeburn 4145: my @possdoms = ($coursehash{'domain'});
4146: if ($coursehash{'checkforpriv'}) {
4147: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4148: }
1.351 www 4149: my %returnhash=();
4150: my %dumphash=
4151: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4152: my $now=time;
1.997 raeburn 4153: my %privileged;
1.1000 raeburn 4154: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4155: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4156: if (($tstart) && ($tstart<0)) { next; }
4157: if (($tend) && ($tend<$now)) { next; }
4158: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4159: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4160: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4161: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4162: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4163: if ($role eq 'cr') { next; }
1.948 raeburn 4164: if ($codes) {
4165: if ($section) { $role .= ':'.$section; }
4166: if ($returnhash{$role}) {
4167: $returnhash{$role}.=','.$username.':'.$domain;
4168: } else {
4169: $returnhash{$role}=$username.':'.$domain;
4170: }
1.351 www 4171: } else {
1.988 raeburn 4172: my $key=&plaintext($role,$crstype);
1.973 bisitz 4173: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4174: if ($returnhash{$key}) {
4175: $returnhash{$key}.=','.$username.':'.$domain;
4176: } else {
4177: $returnhash{$key}=$username.':'.$domain;
4178: }
1.351 www 4179: }
1.948 raeburn 4180: }
1.400 www 4181: return %returnhash;
4182: }
4183:
4184: sub get_my_roles {
1.937 raeburn 4185: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4186: unless (defined($uname)) { $uname=$env{'user.name'}; }
4187: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4188: my (%dumphash,%nothide);
1.1086 raeburn 4189: if ($context eq 'userroles') {
1.1166 raeburn 4190: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4191: } else {
1.1172.2.23 raeburn 4192: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4193: if ($hidepriv) {
4194: my %coursehash=&coursedescription($udom.'_'.$uname);
4195: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4196: if ($user !~ /:/) {
4197: $nothide{join(':',split(/[\@]/,$user))} = 1;
4198: } else {
4199: $nothide{$user} = 1;
4200: }
4201: }
4202: }
1.858 raeburn 4203: }
1.400 www 4204: my %returnhash=();
4205: my $now=time;
1.999 raeburn 4206: my %privileged;
1.800 albertel 4207: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4208: my ($role,$tend,$tstart);
4209: if ($context eq 'userroles') {
1.1149 raeburn 4210: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4211: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4212: } else {
4213: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4214: }
1.400 www 4215: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4216: my $status = 'active';
1.939 raeburn 4217: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4218: $status = 'previous';
4219: }
4220: if (($tstart) && ($now<$tstart)) {
4221: $status = 'future';
4222: }
4223: if (ref($types) eq 'ARRAY') {
4224: if (!grep(/^\Q$status\E$/,@{$types})) {
4225: next;
4226: }
4227: } else {
4228: if ($status ne 'active') {
4229: next;
4230: }
4231: }
1.867 raeburn 4232: my ($rolecode,$username,$domain,$section,$area);
4233: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4234: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4235: (undef,$domain,$username,$section) = split(/\//,$area);
4236: } else {
4237: ($role,$username,$domain,$section) = split(/\:/,$entry);
4238: }
1.832 raeburn 4239: if (ref($roledoms) eq 'ARRAY') {
4240: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4241: next;
4242: }
4243: }
4244: if (ref($roles) eq 'ARRAY') {
4245: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4246: if ($role =~ /^cr\//) {
4247: if (!grep(/^cr$/,@{$roles})) {
4248: next;
4249: }
1.1104 raeburn 4250: } elsif ($role =~ /^gr\//) {
4251: if (!grep(/^gr$/,@{$roles})) {
4252: next;
4253: }
1.922 raeburn 4254: } else {
4255: next;
4256: }
1.832 raeburn 4257: }
1.867 raeburn 4258: }
1.937 raeburn 4259: if ($hidepriv) {
1.1172.2.23 raeburn 4260: my @privroles = ('dc','su');
1.999 raeburn 4261: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4262: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4263: } else {
1.1172.2.23 raeburn 4264: my $possdoms = [$domain];
4265: if (ref($roledoms) eq 'ARRAY') {
4266: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4267: }
1.1172.2.23 raeburn 4268: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4269: if (!$nothide{$username.':'.$domain}) {
4270: next;
4271: }
4272: }
1.937 raeburn 4273: }
4274: }
1.933 raeburn 4275: if ($withsec) {
4276: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4277: $tstart.':'.$tend;
4278: } else {
4279: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4280: }
1.832 raeburn 4281: }
1.373 www 4282: return %returnhash;
1.399 www 4283: }
4284:
4285: # ----------------------------------------------------- Frontpage Announcements
4286: #
4287: #
4288:
4289: sub postannounce {
4290: my ($server,$text)=@_;
1.844 albertel 4291: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4292: unless ($text=~/\w/) { $text=''; }
4293: return &reply('setannounce:'.&escape($text),$server);
4294: }
4295:
4296: sub getannounce {
1.448 albertel 4297:
4298: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4299: my $announcement='';
1.800 albertel 4300: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4301: close($fh);
1.399 www 4302: if ($announcement=~/\w/) {
4303: return
4304: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4305: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4306: } else {
4307: return '';
4308: }
4309: } else {
4310: return '';
4311: }
1.351 www 4312: }
1.353 www 4313:
4314: # ---------------------------------------------------------- Course ID routines
4315: # Deal with domain's nohist_courseid.db files
4316: #
4317:
4318: sub courseidput {
1.921 raeburn 4319: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4320: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4321: my $outcome;
4322: if ($caller eq 'timeonly') {
4323: my $cids = '';
4324: foreach my $item (keys(%$storehash)) {
4325: $cids.=&escape($item).'&';
4326: }
4327: $cids=~s/\&$//;
4328: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4329: $coursehome);
4330: } else {
4331: my $items = '';
4332: foreach my $item (keys(%$storehash)) {
4333: $items.= &escape($item).'='.
4334: &freeze_escape($$storehash{$item}).'&';
4335: }
4336: $items=~s/\&$//;
4337: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4338: $coursehome);
1.918 raeburn 4339: }
4340: if ($outcome eq 'unknown_cmd') {
4341: my $what;
4342: foreach my $cid (keys(%$storehash)) {
4343: $what .= &escape($cid).'=';
1.921 raeburn 4344: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4345: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4346: }
4347: $what =~ s/\:$/&/;
4348: }
4349: $what =~ s/\&$//;
4350: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4351: } else {
4352: return $outcome;
4353: }
1.353 www 4354: }
4355:
4356: sub courseiddump {
1.921 raeburn 4357: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4358: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4359: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4360: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4361: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4362: my $as_hash = 1;
4363: my %returnhash;
4364: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4365: my %libserv = &all_library();
4366: foreach my $tryserver (keys(%libserv)) {
4367: if ( ( $hostidflag == 1
4368: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4369: || (!defined($hostidflag)) ) {
4370:
1.918 raeburn 4371: if (($domfilter eq '') ||
4372: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4373: my $rep;
4374: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4375: $rep = &LONCAPA::Lond::dump_course_id_handler(
4376: join(":", (&host_domain($tryserver), $sincefilter,
4377: &escape($descfilter), &escape($instcodefilter),
4378: &escape($ownerfilter), &escape($coursefilter),
4379: &escape($typefilter), &escape($regexp_ok),
4380: $as_hash, &escape($selfenrollonly),
4381: &escape($catfilter), $showhidden, $caller,
4382: &escape($cloner), &escape($cc_clone), $cloneonly,
4383: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4384: &escape($creationcontext),$domcloner,$hasuniquecode,
4385: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4386: } else {
4387: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4388: $sincefilter.':'.&escape($descfilter).':'.
4389: &escape($instcodefilter).':'.&escape($ownerfilter).
4390: ':'.&escape($coursefilter).':'.&escape($typefilter).
4391: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4392: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4393: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4394: &escape($cc_clone).':'.$cloneonly.':'.
4395: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4396: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4397: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4398: }
4399:
1.918 raeburn 4400: my @pairs=split(/\&/,$rep);
4401: foreach my $item (@pairs) {
4402: my ($key,$value)=split(/\=/,$item,2);
4403: $key = &unescape($key);
4404: next if ($key =~ /^error: 2 /);
4405: my $result = &thaw_unescape($value);
4406: if (ref($result) eq 'HASH') {
4407: $returnhash{$key}=$result;
4408: } else {
1.921 raeburn 4409: my @responses = split(/:/,$value);
4410: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4411: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4412: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4413: }
1.1008 raeburn 4414: }
1.353 www 4415: }
4416: }
4417: }
4418: }
4419: return %returnhash;
4420: }
4421:
1.1055 raeburn 4422: sub courselastaccess {
4423: my ($cdom,$cnum,$hostidref) = @_;
4424: my %returnhash;
4425: if ($cdom && $cnum) {
4426: my $chome = &homeserver($cnum,$cdom);
4427: if ($chome ne 'no_host') {
4428: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4429: &extract_lastaccess(\%returnhash,$rep);
4430: }
4431: } else {
4432: if (!$cdom) { $cdom=''; }
4433: my %libserv = &all_library();
4434: foreach my $tryserver (keys(%libserv)) {
4435: if (ref($hostidref) eq 'ARRAY') {
4436: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4437: }
4438: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4439: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4440: &extract_lastaccess(\%returnhash,$rep);
4441: }
4442: }
4443: }
4444: return %returnhash;
4445: }
4446:
4447: sub extract_lastaccess {
4448: my ($returnhash,$rep) = @_;
4449: if (ref($returnhash) eq 'HASH') {
4450: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4451: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4452: $rep eq '') {
4453: my @pairs=split(/\&/,$rep);
4454: foreach my $item (@pairs) {
4455: my ($key,$value)=split(/\=/,$item,2);
4456: $key = &unescape($key);
4457: next if ($key =~ /^error: 2 /);
4458: $returnhash->{$key} = &thaw_unescape($value);
4459: }
4460: }
4461: }
4462: return;
4463: }
4464:
1.658 raeburn 4465: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4466:
4467: sub dcmailput {
1.685 raeburn 4468: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4469: my $status = &Apache::lonnet::critical(
1.740 www 4470: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4471: &escape($message),$server);
1.662 raeburn 4472: return $status;
4473: }
4474:
1.658 raeburn 4475: sub dcmaildump {
4476: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4477: my %returnhash=();
1.846 albertel 4478:
4479: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4480: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4481: &escape($enddate).':';
4482: my @esc_senders=map { &escape($_)} @$senders;
4483: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4484: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4485: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4486: if (($key) && ($value)) {
4487: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4488: }
4489: }
4490: }
4491: return %returnhash;
4492: }
1.662 raeburn 4493: # ---------------------------------------------------------- Domain roles
4494:
4495: sub get_domain_roles {
4496: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4497: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4498: $startdate = '.';
4499: }
1.1018 raeburn 4500: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4501: $enddate = '.';
4502: }
1.922 raeburn 4503: my $rolelist;
4504: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4505: $rolelist = join('&',@{$roles});
1.922 raeburn 4506: }
1.662 raeburn 4507: my %personnel = ();
1.841 albertel 4508:
4509: my %servers = &get_servers($dom,'library');
4510: foreach my $tryserver (keys(%servers)) {
4511: %{$personnel{$tryserver}}=();
4512: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4513: &escape($startdate).':'.
4514: &escape($enddate).':'.
4515: &escape($rolelist), $tryserver))) {
4516: my ($key,$value) = split(/\=/,$line,2);
4517: if (($key) && ($value)) {
4518: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4519: }
4520: }
1.662 raeburn 4521: }
4522: return %personnel;
4523: }
1.658 raeburn 4524:
1.1057 www 4525: # ----------------------------------------------------------- Interval timing
1.149 www 4526:
1.1153 www 4527: {
4528: # Caches needed for speedup of navmaps
4529: # We don't want to cache this for very long at all (5 seconds at most)
4530: #
4531: # The user for whom we cache
4532: my $cachedkey='';
4533: # The cached times for this user
4534: my %cachedtimes=();
4535: # When this was last done
1.1172.2.66 raeburn 4536: my $cachedtime='';
1.1153 www 4537:
4538: sub load_all_first_access {
1.1154 raeburn 4539: my ($uname,$udom)=@_;
1.1156 www 4540: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4541: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4542: return;
4543: }
4544: $cachedtime=time;
4545: $cachedkey=$uname.':'.$udom;
4546: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4547: }
4548:
1.504 albertel 4549: sub get_first_access {
1.1162 raeburn 4550: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4551: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4552: if ($argsymb) { $symb=$argsymb; }
4553: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4554: if ($argmap) { $map = $argmap; }
1.926 albertel 4555: if ($type eq 'course') {
4556: $res='course';
4557: } elsif ($type eq 'map') {
1.588 albertel 4558: $res=&symbread($map);
4559: } else {
4560: $res=$symb;
4561: }
1.1153 www 4562: &load_all_first_access($uname,$udom);
4563: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4564: }
4565:
4566: sub set_first_access {
1.1162 raeburn 4567: my ($type,$interval)=@_;
1.790 albertel 4568: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4569: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4570: if ($type eq 'course') {
4571: $res='course';
4572: } elsif ($type eq 'map') {
1.588 albertel 4573: $res=&symbread($map);
4574: } else {
4575: $res=$symb;
4576: }
1.1153 www 4577: $cachedkey='';
1.1162 raeburn 4578: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4579: if (!$firstaccess) {
1.1162 raeburn 4580: my $start = time;
4581: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4582: $udom,$uname);
4583: if ($putres eq 'ok') {
4584: &put('timerinterval',{"$courseid\0$res"=>$interval},
4585: $udom,$uname);
4586: &appenv(
4587: {
4588: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4589: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4590: }
4591: );
4592: }
4593: return $putres;
1.505 albertel 4594: }
4595: return 'already_set';
1.504 albertel 4596: }
1.1153 www 4597: }
1.1172.2.32 raeburn 4598:
4599: sub checkout {
4600: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4601: my $now=time;
4602: my $lonhost=$perlvar{'lonHostID'};
4603: my $infostr=&escape(
4604: 'CHECKOUTTOKEN&'.
4605: $tuname.'&'.
4606: $tudom.'&'.
4607: $tcrsid.'&'.
4608: $symb.'&'.
4609: $now.'&'.$ENV{'REMOTE_ADDR'});
4610: my $token=&reply('tmpput:'.$infostr,$lonhost);
4611: if ($token=~/^error\:/) {
4612: &logthis("<font color=\"blue\">WARNING: ".
4613: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4614: "</font>");
4615: return '';
4616: }
4617:
4618: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4619: $token=~tr/a-z/A-Z/;
4620:
4621: my %infohash=('resource.0.outtoken' => $token,
4622: 'resource.0.checkouttime' => $now,
4623: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4624:
4625: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4626: return '';
4627: } else {
4628: &logthis("<font color=\"blue\">WARNING: ".
4629: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4630: "</font>");
4631: }
4632:
4633: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4634: &escape('Checkout '.$infostr.' - '.
4635: $token)) ne 'ok') {
4636: return '';
4637: } else {
4638: &logthis("<font color=\"blue\">WARNING: ".
4639: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4640: "</font>");
4641: }
4642: return $token;
4643: }
4644:
4645: # ------------------------------------------------------------ Check in an item
4646:
4647: sub checkin {
4648: my $token=shift;
4649: my $now=time;
4650: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4651: $lonhost=~tr/A-Z/a-z/;
4652: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4653: $dtoken=~s/\W/\_/g;
4654: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4655: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4656:
4657: unless (($tuname) && ($tudom)) {
4658: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4659: return '';
4660: }
4661:
4662: unless (&allowed('mgr',$tcrsid)) {
4663: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4664: $env{'user.name'}.' - '.$env{'user.domain'});
4665: return '';
4666: }
4667:
4668: my %infohash=('resource.0.intoken' => $token,
4669: 'resource.0.checkintime' => $now,
4670: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4671:
4672: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4673: return '';
4674: }
4675:
4676: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4677: &escape('Checkin - '.$token)) ne 'ok') {
4678: return '';
4679: }
4680:
4681: return ($symb,$tuname,$tudom,$tcrsid);
4682: }
4683:
1.110 www 4684: # --------------------------------------------- Set Expire Date for Spreadsheet
4685:
4686: sub expirespread {
4687: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4688: my $cid=$env{'request.course.id'};
1.110 www 4689: if ($cid) {
4690: my $now=time;
4691: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4692: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4693: $env{'course.'.$cid.'.num'}.
1.110 www 4694: ':nohist_expirationdates:'.
4695: &escape($key).'='.$now,
1.620 albertel 4696: $env{'course.'.$cid.'.home'})
1.110 www 4697: }
4698: return 'ok';
1.14 www 4699: }
4700:
1.109 www 4701: # ----------------------------------------------------- Devalidate Spreadsheets
4702:
4703: sub devalidate {
1.325 www 4704: my ($symb,$uname,$udom)=@_;
1.620 albertel 4705: my $cid=$env{'request.course.id'};
1.109 www 4706: if ($cid) {
1.391 matthew 4707: # delete the stored spreadsheets for
4708: # - the student level sheet of this user in course's homespace
4709: # - the assessment level sheet for this resource
4710: # for this user in user's homespace
1.553 albertel 4711: # - current conditional state info
1.325 www 4712: my $key=$uname.':'.$udom.':';
1.109 www 4713: my $status=
1.299 matthew 4714: &del('nohist_calculatedsheets',
1.391 matthew 4715: [$key.'studentcalc:'],
1.620 albertel 4716: $env{'course.'.$cid.'.domain'},
4717: $env{'course.'.$cid.'.num'})
1.133 albertel 4718: .' '.
4719: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4720: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4721: unless ($status eq 'ok ok') {
4722: &logthis('Could not devalidate spreadsheet '.
1.325 www 4723: $uname.' at '.$udom.' for '.
1.109 www 4724: $symb.': '.$status);
1.133 albertel 4725: }
1.553 albertel 4726: &delenv('user.state.'.$cid);
1.109 www 4727: }
4728: }
4729:
1.265 albertel 4730: sub get_scalar {
4731: my ($string,$end) = @_;
4732: my $value;
4733: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4734: $value = $1;
4735: } elsif ($$string =~ s/^([^&]*?)&//) {
4736: $value = $1;
4737: }
4738: return &unescape($value);
4739: }
4740:
4741: sub array2str {
4742: my (@array) = @_;
4743: my $result=&arrayref2str(\@array);
4744: $result=~s/^__ARRAY_REF__//;
4745: $result=~s/__END_ARRAY_REF__$//;
4746: return $result;
4747: }
4748:
1.204 albertel 4749: sub arrayref2str {
4750: my ($arrayref) = @_;
1.265 albertel 4751: my $result='__ARRAY_REF__';
1.204 albertel 4752: foreach my $elem (@$arrayref) {
1.265 albertel 4753: if(ref($elem) eq 'ARRAY') {
4754: $result.=&arrayref2str($elem).'&';
4755: } elsif(ref($elem) eq 'HASH') {
4756: $result.=&hashref2str($elem).'&';
4757: } elsif(ref($elem)) {
4758: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4759: } else {
4760: $result.=&escape($elem).'&';
4761: }
4762: }
4763: $result=~s/\&$//;
1.265 albertel 4764: $result .= '__END_ARRAY_REF__';
1.204 albertel 4765: return $result;
4766: }
4767:
1.168 albertel 4768: sub hash2str {
1.204 albertel 4769: my (%hash) = @_;
4770: my $result=&hashref2str(\%hash);
1.265 albertel 4771: $result=~s/^__HASH_REF__//;
4772: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4773: return $result;
4774: }
4775:
4776: sub hashref2str {
4777: my ($hashref)=@_;
1.265 albertel 4778: my $result='__HASH_REF__';
1.800 albertel 4779: foreach my $key (sort(keys(%$hashref))) {
4780: if (ref($key) eq 'ARRAY') {
4781: $result.=&arrayref2str($key).'=';
4782: } elsif (ref($key) eq 'HASH') {
4783: $result.=&hashref2str($key).'=';
4784: } elsif (ref($key)) {
1.265 albertel 4785: $result.='=';
1.800 albertel 4786: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4787: } else {
1.1132 raeburn 4788: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4789: }
4790:
1.800 albertel 4791: if(ref($hashref->{$key}) eq 'ARRAY') {
4792: $result.=&arrayref2str($hashref->{$key}).'&';
4793: } elsif(ref($hashref->{$key}) eq 'HASH') {
4794: $result.=&hashref2str($hashref->{$key}).'&';
4795: } elsif(ref($hashref->{$key})) {
1.265 albertel 4796: $result.='&';
1.800 albertel 4797: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4798: } else {
1.800 albertel 4799: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4800: }
4801: }
1.168 albertel 4802: $result=~s/\&$//;
1.265 albertel 4803: $result .= '__END_HASH_REF__';
1.168 albertel 4804: return $result;
4805: }
4806:
4807: sub str2hash {
1.265 albertel 4808: my ($string)=@_;
4809: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4810: return %$hash;
4811: }
4812:
4813: sub str2hashref {
1.168 albertel 4814: my ($string) = @_;
1.265 albertel 4815:
4816: my %hash;
4817:
4818: if($string !~ /^__HASH_REF__/) {
4819: if (! ($string eq '' || !defined($string))) {
4820: $hash{'error'}='Not hash reference';
4821: }
4822: return (\%hash, $string);
4823: }
4824:
4825: $string =~ s/^__HASH_REF__//;
4826:
4827: while($string !~ /^__END_HASH_REF__/) {
4828: #key
4829: my $key='';
4830: if($string =~ /^__HASH_REF__/) {
4831: ($key, $string)=&str2hashref($string);
4832: if(defined($key->{'error'})) {
4833: $hash{'error'}='Bad data';
4834: return (\%hash, $string);
4835: }
4836: } elsif($string =~ /^__ARRAY_REF__/) {
4837: ($key, $string)=&str2arrayref($string);
4838: if($key->[0] eq 'Array reference error') {
4839: $hash{'error'}='Bad data';
4840: return (\%hash, $string);
4841: }
4842: } else {
4843: $string =~ s/^(.*?)=//;
1.267 albertel 4844: $key=&unescape($1);
1.265 albertel 4845: }
4846: $string =~ s/^=//;
4847:
4848: #value
4849: my $value='';
4850: if($string =~ /^__HASH_REF__/) {
4851: ($value, $string)=&str2hashref($string);
4852: if(defined($value->{'error'})) {
4853: $hash{'error'}='Bad data';
4854: return (\%hash, $string);
4855: }
4856: } elsif($string =~ /^__ARRAY_REF__/) {
4857: ($value, $string)=&str2arrayref($string);
4858: if($value->[0] eq 'Array reference error') {
4859: $hash{'error'}='Bad data';
4860: return (\%hash, $string);
4861: }
4862: } else {
4863: $value=&get_scalar(\$string,'__END_HASH_REF__');
4864: }
4865: $string =~ s/^&//;
4866:
4867: $hash{$key}=$value;
1.204 albertel 4868: }
1.265 albertel 4869:
4870: $string =~ s/^__END_HASH_REF__//;
4871:
4872: return (\%hash, $string);
1.204 albertel 4873: }
4874:
4875: sub str2array {
1.265 albertel 4876: my ($string)=@_;
4877: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4878: return @$array;
4879: }
4880:
4881: sub str2arrayref {
1.204 albertel 4882: my ($string) = @_;
1.265 albertel 4883: my @array;
4884:
4885: if($string !~ /^__ARRAY_REF__/) {
4886: if (! ($string eq '' || !defined($string))) {
4887: $array[0]='Array reference error';
4888: }
4889: return (\@array, $string);
4890: }
4891:
4892: $string =~ s/^__ARRAY_REF__//;
4893:
4894: while($string !~ /^__END_ARRAY_REF__/) {
4895: my $value='';
4896: if($string =~ /^__HASH_REF__/) {
4897: ($value, $string)=&str2hashref($string);
4898: if(defined($value->{'error'})) {
4899: $array[0] ='Array reference error';
4900: return (\@array, $string);
4901: }
4902: } elsif($string =~ /^__ARRAY_REF__/) {
4903: ($value, $string)=&str2arrayref($string);
4904: if($value->[0] eq 'Array reference error') {
4905: $array[0] ='Array reference error';
4906: return (\@array, $string);
4907: }
4908: } else {
4909: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4910: }
4911: $string =~ s/^&//;
4912:
4913: push(@array, $value);
1.191 harris41 4914: }
1.265 albertel 4915:
4916: $string =~ s/^__END_ARRAY_REF__//;
4917:
4918: return (\@array, $string);
1.168 albertel 4919: }
4920:
1.167 albertel 4921: # -------------------------------------------------------------------Temp Store
4922:
1.168 albertel 4923: sub tmpreset {
4924: my ($symb,$namespace,$domain,$stuname) = @_;
4925: if (!$symb) {
4926: $symb=&symbread();
1.620 albertel 4927: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4928: }
4929: $symb=escape($symb);
4930:
1.620 albertel 4931: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4932: $namespace=~s/\//\_/g;
4933: $namespace=~s/\W//g;
4934:
1.620 albertel 4935: if (!$domain) { $domain=$env{'user.domain'}; }
4936: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4937: if ($domain eq 'public' && $stuname eq 'public') {
4938: $stuname=$ENV{'REMOTE_ADDR'};
4939: }
1.1117 foxr 4940: my $path=LONCAPA::tempdir();
1.168 albertel 4941: my %hash;
4942: if (tie(%hash,'GDBM_File',
4943: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4944: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4945: foreach my $key (keys(%hash)) {
1.180 albertel 4946: if ($key=~ /:$symb/) {
1.168 albertel 4947: delete($hash{$key});
4948: }
4949: }
4950: }
4951: }
4952:
1.167 albertel 4953: sub tmpstore {
1.168 albertel 4954: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4955:
4956: if (!$symb) {
4957: $symb=&symbread();
1.620 albertel 4958: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4959: }
4960: $symb=escape($symb);
4961:
4962: if (!$namespace) {
4963: # I don't think we would ever want to store this for a course.
4964: # it seems this will only be used if we don't have a course.
1.620 albertel 4965: #$namespace=$env{'request.course.id'};
1.168 albertel 4966: #if (!$namespace) {
1.620 albertel 4967: $namespace=$env{'request.state'};
1.168 albertel 4968: #}
4969: }
4970: $namespace=~s/\//\_/g;
4971: $namespace=~s/\W//g;
1.620 albertel 4972: if (!$domain) { $domain=$env{'user.domain'}; }
4973: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4974: if ($domain eq 'public' && $stuname eq 'public') {
4975: $stuname=$ENV{'REMOTE_ADDR'};
4976: }
1.168 albertel 4977: my $now=time;
4978: my %hash;
1.1117 foxr 4979: my $path=LONCAPA::tempdir();
1.168 albertel 4980: if (tie(%hash,'GDBM_File',
4981: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4982: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4983: $hash{"version:$symb"}++;
4984: my $version=$hash{"version:$symb"};
4985: my $allkeys='';
4986: foreach my $key (keys(%$storehash)) {
4987: $allkeys.=$key.':';
1.591 albertel 4988: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4989: }
4990: $hash{"$version:$symb:timestamp"}=$now;
4991: $allkeys.='timestamp';
4992: $hash{"$version:keys:$symb"}=$allkeys;
4993: if (untie(%hash)) {
4994: return 'ok';
4995: } else {
4996: return "error:$!";
4997: }
4998: } else {
4999: return "error:$!";
5000: }
5001: }
1.167 albertel 5002:
1.168 albertel 5003: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5004:
1.168 albertel 5005: sub tmprestore {
5006: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5007:
1.168 albertel 5008: if (!$symb) {
5009: $symb=&symbread();
1.620 albertel 5010: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5011: }
5012: $symb=escape($symb);
5013:
1.620 albertel 5014: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5015:
1.620 albertel 5016: if (!$domain) { $domain=$env{'user.domain'}; }
5017: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5018: if ($domain eq 'public' && $stuname eq 'public') {
5019: $stuname=$ENV{'REMOTE_ADDR'};
5020: }
1.168 albertel 5021: my %returnhash;
5022: $namespace=~s/\//\_/g;
5023: $namespace=~s/\W//g;
5024: my %hash;
1.1117 foxr 5025: my $path=LONCAPA::tempdir();
1.168 albertel 5026: if (tie(%hash,'GDBM_File',
5027: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5028: &GDBM_READER(),0640)) {
1.168 albertel 5029: my $version=$hash{"version:$symb"};
5030: $returnhash{'version'}=$version;
5031: my $scope;
5032: for ($scope=1;$scope<=$version;$scope++) {
5033: my $vkeys=$hash{"$scope:keys:$symb"};
5034: my @keys=split(/:/,$vkeys);
5035: my $key;
5036: $returnhash{"$scope:keys"}=$vkeys;
5037: foreach $key (@keys) {
1.591 albertel 5038: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5039: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5040: }
5041: }
1.168 albertel 5042: if (!(untie(%hash))) {
5043: return "error:$!";
5044: }
5045: } else {
5046: return "error:$!";
5047: }
5048: return %returnhash;
1.167 albertel 5049: }
5050:
1.9 www 5051: # ----------------------------------------------------------------------- Store
5052:
5053: sub store {
1.1172.2.64 raeburn 5054: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5055: my $home='';
5056:
1.168 albertel 5057: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5058:
1.213 www 5059: $symb=&symbclean($symb);
1.122 albertel 5060: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5061:
1.620 albertel 5062: if (!$domain) { $domain=$env{'user.domain'}; }
5063: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5064:
5065: &devalidate($symb,$stuname,$domain);
1.109 www 5066:
5067: $symb=escape($symb);
1.187 www 5068: if (!$namespace) {
1.620 albertel 5069: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5070: return '';
5071: }
5072: }
1.620 albertel 5073: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5074:
5075: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5076: $$storehash{'host'}=$perlvar{'lonHostID'};
5077:
1.12 www 5078: my $namevalue='';
1.800 albertel 5079: foreach my $key (keys(%$storehash)) {
5080: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5081: }
1.12 www 5082: $namevalue=~s/\&$//;
1.187 www 5083: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5084: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5085: }
5086:
1.47 www 5087: # -------------------------------------------------------------- Critical Store
5088:
5089: sub cstore {
1.1172.2.64 raeburn 5090: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5091: my $home='';
5092:
1.168 albertel 5093: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5094:
1.213 www 5095: $symb=&symbclean($symb);
1.122 albertel 5096: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5097:
1.620 albertel 5098: if (!$domain) { $domain=$env{'user.domain'}; }
5099: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5100:
5101: &devalidate($symb,$stuname,$domain);
1.109 www 5102:
5103: $symb=escape($symb);
1.187 www 5104: if (!$namespace) {
1.620 albertel 5105: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5106: return '';
5107: }
5108: }
1.620 albertel 5109: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5110:
5111: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5112: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5113:
1.47 www 5114: my $namevalue='';
1.800 albertel 5115: foreach my $key (keys(%$storehash)) {
5116: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5117: }
1.47 www 5118: $namevalue=~s/\&$//;
1.187 www 5119: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5120: return critical
1.1172.2.64 raeburn 5121: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5122: }
5123:
1.9 www 5124: # --------------------------------------------------------------------- Restore
5125:
5126: sub restore {
1.124 www 5127: my ($symb,$namespace,$domain,$stuname) = @_;
5128: my $home='';
5129:
1.168 albertel 5130: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5131:
1.122 albertel 5132: if (!$symb) {
1.1172.2.26 raeburn 5133: return if ($namespace eq 'courserequests');
5134: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5135: } else {
1.1172.2.26 raeburn 5136: unless ($namespace eq 'courserequests') {
5137: $symb=&escape(&symbclean($symb));
5138: }
1.122 albertel 5139: }
1.188 www 5140: if (!$namespace) {
1.620 albertel 5141: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5142: return '';
5143: }
5144: }
1.620 albertel 5145: if (!$domain) { $domain=$env{'user.domain'}; }
5146: if (!$stuname) { $stuname=$env{'user.name'}; }
5147: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5148: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5149:
1.12 www 5150: my %returnhash=();
1.800 albertel 5151: foreach my $line (split(/\&/,$answer)) {
5152: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5153: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5154: }
1.75 www 5155: my $version;
5156: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5157: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5158: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5159: }
1.75 www 5160: }
1.13 www 5161: return %returnhash;
1.34 www 5162: }
5163:
5164: # ---------------------------------------------------------- Course Description
1.1118 foxr 5165: #
5166: #
1.34 www 5167:
5168: sub coursedescription {
1.731 albertel 5169: my ($courseid,$args)=@_;
1.34 www 5170: $courseid=~s/^\///;
1.49 www 5171: $courseid=~s/\_/\//g;
1.34 www 5172: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5173: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5174: my $normalid=$cdomain.'_'.$cnum;
5175: # need to always cache even if we get errors otherwise we keep
5176: # trying and trying and trying to get the course description.
5177: my %envhash=();
5178: my %returnhash=();
1.731 albertel 5179:
5180: my $expiretime=600;
5181: if ($env{'request.course.id'} eq $normalid) {
5182: $expiretime=120;
5183: }
5184:
5185: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5186: if (!$args->{'freshen_cache'}
5187: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5188: foreach my $key (keys(%env)) {
5189: next if ($key !~ /^\Q$prefix\E(.*)/);
5190: my ($setting) = $1;
5191: $returnhash{$setting} = $env{$key};
5192: }
5193: return %returnhash;
5194: }
5195:
1.1118 foxr 5196: # get the data again
5197:
1.731 albertel 5198: if (!$args->{'one_time'}) {
5199: $envhash{'course.'.$normalid.'.last_cache'}=time;
5200: }
1.811 albertel 5201:
1.34 www 5202: if ($chome ne 'no_host') {
1.302 albertel 5203: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5204: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5205: my $username = $env{'user.name'}; # Defult username
5206: if(defined $args->{'user'}) {
5207: $username = $args->{'user'};
5208: }
1.129 albertel 5209: $returnhash{'home'}= $chome;
5210: $returnhash{'domain'} = $cdomain;
5211: $returnhash{'num'} = $cnum;
1.741 raeburn 5212: if (!defined($returnhash{'type'})) {
5213: $returnhash{'type'} = 'Course';
5214: }
1.130 albertel 5215: while (my ($name,$value) = each %returnhash) {
1.53 www 5216: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5217: }
1.270 www 5218: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5219: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5220: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5221: $envhash{'course.'.$normalid.'.home'}=$chome;
5222: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5223: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5224: }
5225: }
1.731 albertel 5226: if (!$args->{'one_time'}) {
1.949 raeburn 5227: &appenv(\%envhash);
1.731 albertel 5228: }
1.302 albertel 5229: return %returnhash;
1.461 www 5230: }
5231:
1.1080 raeburn 5232: sub update_released_required {
5233: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5234: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5235: $cid = $env{'request.course.id'};
5236: $cdom = $env{'course.'.$cid.'.domain'};
5237: $cnum = $env{'course.'.$cid.'.num'};
5238: $chome = $env{'course.'.$cid.'.home'};
5239: }
5240: if ($needsrelease) {
5241: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5242: my $needsupdate;
5243: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5244: $needsupdate = 1;
5245: } else {
5246: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5247: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5248: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5249: $needsupdate = 1;
5250: }
5251: }
5252: if ($needsupdate) {
5253: my %needshash = (
5254: 'internal.releaserequired' => $needsrelease,
5255: );
5256: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5257: if ($putresult eq 'ok') {
5258: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5259: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5260: if (ref($crsinfo{$cid}) eq 'HASH') {
5261: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5262: &courseidput($cdom,\%crsinfo,$chome,'notime');
5263: }
5264: }
5265: }
5266: }
5267: return;
5268: }
5269:
1.461 www 5270: # -------------------------------------------------See if a user is privileged
5271:
5272: sub privileged {
1.1172.2.23 raeburn 5273: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5274: my $now = time;
1.1172.2.23 raeburn 5275: my $roles;
5276: if (ref($possroles) eq 'ARRAY') {
5277: $roles = $possroles;
5278: } else {
5279: $roles = ['dc','su'];
5280: }
5281: if (ref($possdomains) eq 'ARRAY') {
5282: my %privileged = &privileged_by_domain($possdomains,$roles);
5283: foreach my $dom (@{$possdomains}) {
5284: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5285: (ref($privileged{$dom}) eq 'HASH')) {
5286: foreach my $role (@{$roles}) {
5287: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5288: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5289: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5290: return 1 unless (($end && $end < $now) ||
5291: ($start && $start > $now));
5292: }
5293: }
5294: }
5295: }
5296: }
5297: } else {
5298: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5299: my $now = time;
1.1170 droeschl 5300:
1.1172.2.58 raeburn 5301: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5302: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5303: if (grep(/^\Q$trole\E$/,@{$roles})) {
5304: return 1 unless ($tend && $tend < $now)
5305: or ($tstart && $tstart > $now);
1.1170 droeschl 5306: }
1.1172.2.23 raeburn 5307: }
5308: }
1.461 www 5309: return 0;
1.9 www 5310: }
1.1 albertel 5311:
1.1172.2.23 raeburn 5312: sub privileged_by_domain {
5313: my ($domains,$roles) = @_;
5314: my %privileged = ();
5315: my $cachetime = 60*60*24;
5316: my $now = time;
5317: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5318: return %privileged;
5319: }
5320: foreach my $dom (@{$domains}) {
5321: next if (ref($privileged{$dom}) eq 'HASH');
5322: my $needroles;
5323: foreach my $role (@{$roles}) {
5324: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5325: if (defined($cached)) {
5326: if (ref($result) eq 'HASH') {
5327: $privileged{$dom}{$role} = $result;
5328: }
5329: } else {
5330: $needroles = 1;
5331: }
5332: }
5333: if ($needroles) {
5334: my %dompersonnel = &get_domain_roles($dom,$roles);
5335: $privileged{$dom} = {};
5336: foreach my $server (keys(%dompersonnel)) {
5337: if (ref($dompersonnel{$server}) eq 'HASH') {
5338: foreach my $item (keys(%{$dompersonnel{$server}})) {
5339: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5340: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5341: next if ($end && $end < $now);
5342: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5343: $dompersonnel{$server}{$item};
5344: }
5345: }
5346: }
5347: if (ref($privileged{$dom}) eq 'HASH') {
5348: foreach my $role (@{$roles}) {
5349: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5350: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5351: } else {
5352: my %hash = ();
5353: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5354: }
5355: }
5356: }
5357: }
5358: }
5359: return %privileged;
5360: }
5361:
1.103 harris41 5362: # -------------------------------------------------------- Get user privileges
1.11 www 5363:
5364: sub rolesinit {
1.1169 droeschl 5365: my ($domain, $username) = @_;
5366: my %userroles = ('user.login.time' => time);
5367: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5368:
5369: # firstaccess and timerinterval are related to timed maps/resources.
5370: # also, blocking can be triggered by an activating timer
5371: # it's saved in the user's %env.
5372: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5373: my %timerinterval = &dump('timerinterval', $domain, $username);
5374: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5375: %timerintchk, %timerintenv);
5376:
1.1162 raeburn 5377: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5378: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5379: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5380: }
1.1169 droeschl 5381:
1.1162 raeburn 5382: foreach my $key (keys(%timerinterval)) {
5383: my ($cid,$rest) = split(/\0/,$key);
5384: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5385: }
1.1169 droeschl 5386:
1.11 www 5387: my %allroles=();
1.1162 raeburn 5388: my %allgroups=();
1.11 www 5389:
1.1172.2.58 raeburn 5390: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5391: my $role = $rolesdump{$area};
5392: $area =~ s/\_\w\w$//;
5393:
5394: my ($trole, $tend, $tstart, $group_privs);
5395:
5396: if ($role =~ /^cr/) {
5397: # Custom role, defined by a user
5398: # e.g., user.role.cr/msu/smith/mynewrole
5399: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5400: $trole = $1;
5401: ($tend, $tstart) = split('_', $2);
5402: } else {
5403: $trole = $role;
5404: }
5405: } elsif ($role =~ m|^gr/|) {
5406: # Role of member in a group, defined within a course/community
5407: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5408: ($trole, $tend, $tstart) = split(/_/, $role);
5409: next if $tstart eq '-1';
5410: ($trole, $group_privs) = split(/\//, $trole);
5411: $group_privs = &unescape($group_privs);
5412: } else {
5413: # Just a normal role, defined in roles.tab
5414: ($trole, $tend, $tstart) = split(/_/,$role);
5415: }
5416:
5417: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5418: $username);
5419: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5420:
5421: # role expired or not available yet?
5422: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5423: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5424:
5425: next if $area eq '' or $trole eq '';
5426:
5427: my $spec = "$trole.$area";
5428: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5429:
5430: if ($trole =~ /^cr\//) {
5431: # Custom role, defined by a user
5432: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5433: } elsif ($trole eq 'gr') {
5434: # Role of a member in a group, defined within a course/community
5435: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5436: next;
5437: } else {
5438: # Normal role, defined in roles.tab
5439: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5440: }
5441:
5442: my $cid = $tdomain.'_'.$trest;
5443: unless ($firstaccchk{$cid}) {
5444: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5445: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5446: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5447: $coursetimerstarts{$cid}{$item};
5448: }
5449: }
5450: $firstaccchk{$cid} = 1;
5451: }
5452: unless ($timerintchk{$cid}) {
5453: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5454: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5455: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5456: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5457: }
1.12 www 5458: }
1.1169 droeschl 5459: $timerintchk{$cid} = 1;
1.191 harris41 5460: }
1.11 www 5461: }
1.1169 droeschl 5462:
5463: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5464: \%allroles, \%allgroups);
5465: $env{'user.adv'} = $userroles{'user.adv'};
5466:
1.1162 raeburn 5467: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5468: }
5469:
1.567 raeburn 5470: sub set_arearole {
1.1172.2.19 raeburn 5471: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5472: unless ($nolog) {
1.567 raeburn 5473: # log the associated role with the area
1.1172.2.19 raeburn 5474: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5475: }
1.743 albertel 5476: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5477: }
5478:
5479: sub custom_roleprivs {
5480: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5481: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5482: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5483: if (&hostname($homsvr) ne '') {
1.567 raeburn 5484: my ($rdummy,$roledef)=
5485: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5486: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5487: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5488: if (defined($syspriv)) {
1.1043 raeburn 5489: if ($trest =~ /^$match_community$/) {
5490: $syspriv =~ s/bre\&S//;
5491: }
1.567 raeburn 5492: $$allroles{'cm./'}.=':'.$syspriv;
5493: $$allroles{$spec.'./'}.=':'.$syspriv;
5494: }
5495: if ($tdomain ne '') {
5496: if (defined($dompriv)) {
5497: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5498: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5499: }
5500: if (($trest ne '') && (defined($coursepriv))) {
5501: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5502: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5503: }
5504: }
5505: }
5506: }
5507: }
5508:
1.678 raeburn 5509: sub group_roleprivs {
5510: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5511: my $access = 1;
5512: my $now = time;
5513: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5514: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5515: if ($access) {
1.811 albertel 5516: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5517: $$allgroups{$course}{$group} .=':'.$group_privs;
5518: }
5519: }
1.567 raeburn 5520:
5521: sub standard_roleprivs {
5522: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5523: if (defined($pr{$trole.':s'})) {
5524: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5525: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5526: }
5527: if ($tdomain ne '') {
5528: if (defined($pr{$trole.':d'})) {
5529: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5530: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5531: }
5532: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5533: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5534: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5535: }
5536: }
5537: }
5538:
5539: sub set_userprivs {
1.1064 raeburn 5540: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5541: my $author=0;
5542: my $adv=0;
1.678 raeburn 5543: my %grouproles = ();
5544: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5545: my @groupkeys;
1.1000 raeburn 5546: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5547: push(@groupkeys,$role);
5548: }
5549: if (ref($groups_roles) eq 'HASH') {
5550: foreach my $key (keys(%{$groups_roles})) {
5551: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5552: push(@groupkeys,$key);
5553: }
5554: }
5555: }
5556: if (@groupkeys > 0) {
5557: foreach my $role (@groupkeys) {
5558: my ($trole,$area,$sec,$extendedarea);
5559: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5560: $trole = $1;
5561: $area = $2;
5562: $sec = $3;
5563: $extendedarea = $area.$sec;
5564: if (exists($$allgroups{$area})) {
5565: foreach my $group (keys(%{$$allgroups{$area}})) {
5566: my $spec = $trole.'.'.$extendedarea;
5567: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5568: $$allgroups{$area}{$group};
1.1064 raeburn 5569: }
1.678 raeburn 5570: }
5571: }
5572: }
5573: }
5574: }
1.800 albertel 5575: foreach my $group (keys(%grouproles)) {
5576: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5577: }
1.800 albertel 5578: foreach my $role (keys(%{$allroles})) {
5579: my %thesepriv;
1.941 raeburn 5580: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5581: foreach my $item (split(/:/,$$allroles{$role})) {
5582: if ($item ne '') {
5583: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5584: if ($restrictions eq '') {
5585: $thesepriv{$privilege}='F';
5586: } elsif ($thesepriv{$privilege} ne 'F') {
5587: $thesepriv{$privilege}.=$restrictions;
5588: }
5589: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5590: }
5591: }
5592: my $thesestr='';
1.1104 raeburn 5593: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5594: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5595: }
5596: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5597: }
5598: return ($author,$adv);
5599: }
5600:
1.994 raeburn 5601: sub role_status {
1.1104 raeburn 5602: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5603: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5604: my ($one,$two) = split(m{\./},$rolekey,2);
5605: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5606: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5607: $$where = '/'.$two;
1.994 raeburn 5608: $$trolecode=$$role.'.'.$$where;
5609: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5610: $$tstatus='is';
1.1104 raeburn 5611: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5612: $$tstatus='future';
1.1034 raeburn 5613: if ($$tstart<$now) {
5614: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5615: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5616: my (%allroles,%allgroups,$group_privs,
5617: %groups_roles,@rolecodes);
1.1002 raeburn 5618: my %userroles = (
5619: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5620: );
1.1064 raeburn 5621: @rolecodes = ('cm');
1.1002 raeburn 5622: my $spec=$$role.'.'.$$where;
5623: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5624: if ($$role =~ /^cr\//) {
5625: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5626: push(@rolecodes,'cr');
1.1002 raeburn 5627: } elsif ($$role eq 'gr') {
1.1064 raeburn 5628: push(@rolecodes,$$role);
1.1002 raeburn 5629: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5630: $env{'user.name'});
1.1064 raeburn 5631: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5632: (undef,my $group_privs) = split(/\//,$trole);
5633: $group_privs = &unescape($group_privs);
5634: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5635: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 5636: &get_groups_roles($tdomain,$trest,
5637: \%course_roles,\@rolecodes,
5638: \%groups_roles);
1.1002 raeburn 5639: } else {
1.1064 raeburn 5640: push(@rolecodes,$$role);
1.1002 raeburn 5641: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5642: }
1.1064 raeburn 5643: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5644: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5645: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5646: }
5647: }
1.1034 raeburn 5648: $$tstatus = 'is';
1.1002 raeburn 5649: }
1.994 raeburn 5650: }
5651: if ($$tend) {
1.1104 raeburn 5652: if ($$tend<$update) {
1.994 raeburn 5653: $$tstatus='expired';
5654: } elsif ($$tend<$now) {
5655: $$tstatus='will_not';
5656: }
5657: }
5658: }
5659: }
5660: }
5661:
1.1104 raeburn 5662: sub get_groups_roles {
5663: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5664: return unless((ref($cdom_courseroles) eq 'HASH') &&
5665: (ref($rolecodes) eq 'ARRAY') &&
5666: (ref($groups_roles) eq 'HASH'));
5667: if (keys(%{$cdom_courseroles}) > 0) {
5668: my ($cnum) = ($rest =~ /^($match_courseid)/);
5669: if ($cdom ne '' && $cnum ne '') {
5670: foreach my $key (keys(%{$cdom_courseroles})) {
5671: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5672: my $crsrole = $1;
5673: my $crssec = $2;
5674: if ($crsrole =~ /^cr/) {
5675: unless (grep(/^cr$/,@{$rolecodes})) {
5676: push(@{$rolecodes},'cr');
5677: }
5678: } else {
5679: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5680: push(@{$rolecodes},$crsrole);
5681: }
5682: }
5683: my $rolekey = "$crsrole./$cdom/$cnum";
5684: if ($crssec ne '') {
5685: $rolekey .= "/$crssec";
5686: }
5687: $rolekey .= './';
5688: $groups_roles->{$rolekey} = $rolecodes;
5689: }
5690: }
5691: }
5692: }
5693: return;
5694: }
5695:
5696: sub delete_env_groupprivs {
5697: my ($where,$courseroles,$possroles) = @_;
5698: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5699: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5700: unless (ref($courseroles->{$udom}) eq 'HASH') {
5701: %{$courseroles->{$udom}} =
5702: &get_my_roles('','','userroles',['active'],
5703: $possroles,[$udom],1);
5704: }
5705: if (ref($courseroles->{$udom}) eq 'HASH') {
5706: foreach my $item (keys(%{$courseroles->{$udom}})) {
5707: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5708: my $area = '/'.$cdom.'/'.$cnum;
5709: my $privkey = "user.priv.$crsrole.$area";
5710: if ($crssec ne '') {
5711: $privkey .= '/'.$crssec;
5712: }
5713: $privkey .= ".$area/$group";
5714: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5715: }
5716: }
5717: return;
5718: }
5719:
1.994 raeburn 5720: sub check_adhoc_privs {
1.1104 raeburn 5721: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5722: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5723: my $setprivs;
1.994 raeburn 5724: if ($env{$cckey}) {
5725: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5726: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5727: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5728: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5729: $setprivs = 1;
1.994 raeburn 5730: }
5731: } else {
1.1088 raeburn 5732: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5733: $setprivs = 1;
1.994 raeburn 5734: }
1.1172.2.9 raeburn 5735: return $setprivs;
1.994 raeburn 5736: }
5737:
5738: sub set_adhoc_privileges {
1.1172.2.84! raeburn 5739: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1088 raeburn 5740: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5741: my $area = '/'.$dcdom.'/'.$pickedcourse;
5742: my $spec = $role.'.'.$area;
5743: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5744: $env{'user.name'},1);
1.1172.2.84! raeburn 5745: my %rolehash = ();
! 5746: if ($role =~ m{^cr/$dcdom/$dcdom\Q-domainconfig\E/}) {
! 5747: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
! 5748: } else {
! 5749: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
! 5750: }
! 5751: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 5752: &appenv(\%userroles,[$role,'cm']);
5753: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5754: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5755: &appenv( {'request.role' => $spec,
5756: 'request.role.domain' => $dcdom,
5757: 'request.course.sec' => ''
5758: }
5759: );
5760: my $tadv=0;
5761: if (&allowed('adv') eq 'F') { $tadv=1; }
5762: &appenv({'request.role.adv' => $tadv});
5763: }
1.994 raeburn 5764: }
5765:
1.12 www 5766: # --------------------------------------------------------------- get interface
5767:
5768: sub get {
1.131 albertel 5769: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5770: my $items='';
1.800 albertel 5771: foreach my $item (@$storearr) {
5772: $items.=&escape($item).'&';
1.191 harris41 5773: }
1.12 www 5774: $items=~s/\&$//;
1.620 albertel 5775: if (!$udomain) { $udomain=$env{'user.domain'}; }
5776: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5777: my $uhome=&homeserver($uname,$udomain);
5778:
1.133 albertel 5779: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5780: my @pairs=split(/\&/,$rep);
1.273 albertel 5781: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5782: return @pairs;
5783: }
1.15 www 5784: my %returnhash=();
1.42 www 5785: my $i=0;
1.800 albertel 5786: foreach my $item (@$storearr) {
5787: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5788: $i++;
1.191 harris41 5789: }
1.15 www 5790: return %returnhash;
1.27 www 5791: }
5792:
5793: # --------------------------------------------------------------- del interface
5794:
5795: sub del {
1.133 albertel 5796: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5797: my $items='';
1.800 albertel 5798: foreach my $item (@$storearr) {
5799: $items.=&escape($item).'&';
1.191 harris41 5800: }
1.984 neumanie 5801:
1.27 www 5802: $items=~s/\&$//;
1.620 albertel 5803: if (!$udomain) { $udomain=$env{'user.domain'}; }
5804: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5805: my $uhome=&homeserver($uname,$udomain);
5806: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5807: }
5808:
5809: # -------------------------------------------------------------- dump interface
5810:
1.1172.2.22 raeburn 5811: sub unserialize {
5812: my ($rep, $escapedkeys) = @_;
5813:
5814: return {} if $rep =~ /^error/;
5815:
5816: my %returnhash=();
5817: foreach my $item (split(/\&/,$rep)) {
5818: my ($key, $value) = split(/=/, $item, 2);
5819: $key = unescape($key) unless $escapedkeys;
5820: next if $key =~ /^error: 2 /;
5821: $returnhash{$key} = &thaw_unescape($value);
5822: }
5823: return \%returnhash;
5824: }
5825:
5826: # see Lond::dump_with_regexp
5827: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5828: sub dump {
1.1172.2.22 raeburn 5829: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5830: if (!$udomain) { $udomain=$env{'user.domain'}; }
5831: if (!$uname) { $uname=$env{'user.name'}; }
5832: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5833:
1.1172.2.55 raeburn 5834: if ($regexp) {
5835: $regexp=&escape($regexp);
5836: } else {
5837: $regexp='.';
5838: }
1.1172.2.22 raeburn 5839: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5840: # user is hosted on this machine
1.1172.2.55 raeburn 5841: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5842: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5843: return %{&unserialize($reply, $escapedkeys)};
5844: }
1.1166 raeburn 5845: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5846: my @pairs=split(/\&/,$rep);
5847: my %returnhash=();
1.1098 foxr 5848: if (!($rep =~ /^error/ )) {
5849: foreach my $item (@pairs) {
5850: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5851: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5852: next if ($key =~ /^error: 2 /);
5853: $returnhash{$key}=&thaw_unescape($value);
5854: }
1.755 albertel 5855: }
5856: return %returnhash;
1.407 www 5857: }
5858:
1.1098 foxr 5859:
1.717 albertel 5860: # --------------------------------------------------------- dumpstore interface
5861:
5862: sub dumpstore {
5863: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5864: # same as dump but keys must be escaped. They may contain colon separated
5865: # lists of values that may themself contain colons (e.g. symbs).
5866: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5867: }
5868:
1.407 www 5869: # -------------------------------------------------------------- keys interface
5870:
5871: sub getkeys {
5872: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5873: if (!$udomain) { $udomain=$env{'user.domain'}; }
5874: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5875: my $uhome=&homeserver($uname,$udomain);
5876: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5877: my @keyarray=();
1.800 albertel 5878: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5879: next if ($key =~ /^error: 2 /);
1.800 albertel 5880: push(@keyarray,&unescape($key));
1.407 www 5881: }
5882: return @keyarray;
1.318 matthew 5883: }
5884:
1.319 matthew 5885: # --------------------------------------------------------------- currentdump
5886: sub currentdump {
1.328 matthew 5887: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5888: $courseid = $env{'request.course.id'} if (! defined($courseid));
5889: $sdom = $env{'user.domain'} if (! defined($sdom));
5890: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5891: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5892: my $rep;
5893:
5894: if (grep { $_ eq $uhome } current_machine_ids()) {
5895: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5896: $courseid)));
5897: } else {
5898: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5899: }
5900:
1.318 matthew 5901: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5902: #
1.318 matthew 5903: my %returnhash=();
1.319 matthew 5904: #
5905: if ($rep eq "unknown_cmd") {
5906: # an old lond will not know currentdump
5907: # Do a dump and make it look like a currentdump
1.822 albertel 5908: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5909: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5910: my %hash = @tmp;
5911: @tmp=();
1.424 matthew 5912: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5913: } else {
5914: my @pairs=split(/\&/,$rep);
1.800 albertel 5915: foreach my $pair (@pairs) {
5916: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5917: my ($symb,$param) = split(/:/,$key);
5918: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5919: &thaw_unescape($value);
1.319 matthew 5920: }
1.191 harris41 5921: }
1.12 www 5922: return %returnhash;
1.424 matthew 5923: }
5924:
5925: sub convert_dump_to_currentdump{
5926: my %hash = %{shift()};
5927: my %returnhash;
5928: # Code ripped from lond, essentially. The only difference
5929: # here is the unescaping done by lonnet::dump(). Conceivably
5930: # we might run in to problems with parameter names =~ /^v\./
5931: while (my ($key,$value) = each(%hash)) {
5932: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5933: $symb = &unescape($symb);
5934: $param = &unescape($param);
1.424 matthew 5935: next if ($v eq 'version' || $symb eq 'keys');
5936: next if (exists($returnhash{$symb}) &&
5937: exists($returnhash{$symb}->{$param}) &&
5938: $returnhash{$symb}->{'v.'.$param} > $v);
5939: $returnhash{$symb}->{$param}=$value;
5940: $returnhash{$symb}->{'v.'.$param}=$v;
5941: }
5942: #
5943: # Remove all of the keys in the hashes which keep track of
5944: # the version of the parameter.
5945: while (my ($symb,$param_hash) = each(%returnhash)) {
5946: # use a foreach because we are going to delete from the hash.
5947: foreach my $key (keys(%$param_hash)) {
5948: delete($param_hash->{$key}) if ($key =~ /^v\./);
5949: }
5950: }
5951: return \%returnhash;
1.12 www 5952: }
5953:
1.627 albertel 5954: # ------------------------------------------------------ critical inc interface
5955:
5956: sub cinc {
5957: return &inc(@_,'critical');
5958: }
5959:
1.449 matthew 5960: # --------------------------------------------------------------- inc interface
5961:
5962: sub inc {
1.627 albertel 5963: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5964: if (!$udomain) { $udomain=$env{'user.domain'}; }
5965: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5966: my $uhome=&homeserver($uname,$udomain);
5967: my $items='';
5968: if (! ref($store)) {
5969: # got a single value, so use that instead
5970: $items = &escape($store).'=&';
5971: } elsif (ref($store) eq 'SCALAR') {
5972: $items = &escape($$store).'=&';
5973: } elsif (ref($store) eq 'ARRAY') {
5974: $items = join('=&',map {&escape($_);} @{$store});
5975: } elsif (ref($store) eq 'HASH') {
5976: while (my($key,$value) = each(%{$store})) {
5977: $items.= &escape($key).'='.&escape($value).'&';
5978: }
5979: }
5980: $items=~s/\&$//;
1.627 albertel 5981: if ($critical) {
5982: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5983: } else {
5984: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5985: }
1.449 matthew 5986: }
5987:
1.12 www 5988: # --------------------------------------------------------------- put interface
5989:
5990: sub put {
1.134 albertel 5991: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5992: if (!$udomain) { $udomain=$env{'user.domain'}; }
5993: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5994: my $uhome=&homeserver($uname,$udomain);
1.12 www 5995: my $items='';
1.800 albertel 5996: foreach my $item (keys(%$storehash)) {
5997: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5998: }
1.12 www 5999: $items=~s/\&$//;
1.134 albertel 6000: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6001: }
6002:
1.631 albertel 6003: # ------------------------------------------------------------ newput interface
6004:
6005: sub newput {
6006: my ($namespace,$storehash,$udomain,$uname)=@_;
6007: if (!$udomain) { $udomain=$env{'user.domain'}; }
6008: if (!$uname) { $uname=$env{'user.name'}; }
6009: my $uhome=&homeserver($uname,$udomain);
6010: my $items='';
6011: foreach my $key (keys(%$storehash)) {
6012: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6013: }
6014: $items=~s/\&$//;
6015: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6016: }
6017:
6018: # --------------------------------------------------------- putstore interface
6019:
1.524 raeburn 6020: sub putstore {
1.1172.2.59 raeburn 6021: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6022: if (!$udomain) { $udomain=$env{'user.domain'}; }
6023: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6024: my $uhome=&homeserver($uname,$udomain);
6025: my $items='';
1.715 albertel 6026: foreach my $key (keys(%$storehash)) {
6027: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6028: }
1.715 albertel 6029: $items=~s/\&$//;
1.716 albertel 6030: my $esc_symb=&escape($symb);
6031: my $esc_v=&escape($version);
1.715 albertel 6032: my $reply =
1.716 albertel 6033: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6034: $uhome);
1.1172.2.59 raeburn 6035: if (($tolog) && ($reply eq 'ok')) {
6036: my $namevalue='';
6037: foreach my $key (keys(%{$storehash})) {
6038: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6039: }
6040: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6041: '&host='.&escape($perlvar{'lonHostID'}).
6042: '&version='.$esc_v.
6043: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6044: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6045: }
1.715 albertel 6046: if ($reply eq 'unknown_cmd') {
1.716 albertel 6047: # gfall back to way things use to be done
1.715 albertel 6048: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6049: $uname);
1.524 raeburn 6050: }
1.715 albertel 6051: return $reply;
6052: }
6053:
6054: sub old_putstore {
1.716 albertel 6055: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6056: if (!$udomain) { $udomain=$env{'user.domain'}; }
6057: if (!$uname) { $uname=$env{'user.name'}; }
6058: my $uhome=&homeserver($uname,$udomain);
6059: my %newstorehash;
1.800 albertel 6060: foreach my $item (keys(%$storehash)) {
6061: my $key = $version.':'.&escape($symb).':'.$item;
6062: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6063: }
6064: my $items='';
6065: my %allitems = ();
1.800 albertel 6066: foreach my $item (keys(%newstorehash)) {
6067: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6068: my $key = $1.':keys:'.$2;
6069: $allitems{$key} .= $3.':';
6070: }
1.800 albertel 6071: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6072: }
1.800 albertel 6073: foreach my $item (keys(%allitems)) {
6074: $allitems{$item} =~ s/\:$//;
6075: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6076: }
6077: $items=~s/\&$//;
6078: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6079: }
6080:
1.47 www 6081: # ------------------------------------------------------ critical put interface
6082:
6083: sub cput {
1.134 albertel 6084: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6085: if (!$udomain) { $udomain=$env{'user.domain'}; }
6086: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6087: my $uhome=&homeserver($uname,$udomain);
1.47 www 6088: my $items='';
1.800 albertel 6089: foreach my $item (keys(%$storehash)) {
6090: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6091: }
1.47 www 6092: $items=~s/\&$//;
1.134 albertel 6093: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6094: }
6095:
6096: # -------------------------------------------------------------- eget interface
6097:
6098: sub eget {
1.133 albertel 6099: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6100: my $items='';
1.800 albertel 6101: foreach my $item (@$storearr) {
6102: $items.=&escape($item).'&';
1.191 harris41 6103: }
1.12 www 6104: $items=~s/\&$//;
1.620 albertel 6105: if (!$udomain) { $udomain=$env{'user.domain'}; }
6106: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6107: my $uhome=&homeserver($uname,$udomain);
6108: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6109: my @pairs=split(/\&/,$rep);
6110: my %returnhash=();
1.42 www 6111: my $i=0;
1.800 albertel 6112: foreach my $item (@$storearr) {
6113: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6114: $i++;
1.191 harris41 6115: }
1.12 www 6116: return %returnhash;
6117: }
6118:
1.667 albertel 6119: # ------------------------------------------------------------ tmpput interface
6120: sub tmpput {
1.802 raeburn 6121: my ($storehash,$server,$context)=@_;
1.667 albertel 6122: my $items='';
1.800 albertel 6123: foreach my $item (keys(%$storehash)) {
6124: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6125: }
6126: $items=~s/\&$//;
1.802 raeburn 6127: if (defined($context)) {
6128: $items .= ':'.&escape($context);
6129: }
1.667 albertel 6130: return &reply("tmpput:$items",$server);
6131: }
6132:
6133: # ------------------------------------------------------------ tmpget interface
6134: sub tmpget {
1.688 albertel 6135: my ($token,$server)=@_;
6136: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6137: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6138: my %returnhash;
6139: foreach my $item (split(/\&/,$rep)) {
6140: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6141: next if ($key =~ /^error: 2 /);
1.667 albertel 6142: $returnhash{&unescape($key)}=&thaw_unescape($value);
6143: }
6144: return %returnhash;
6145: }
6146:
1.1113 raeburn 6147: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6148: sub tmpdel {
6149: my ($token,$server)=@_;
6150: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6151: return &reply("tmpdel:$token",$server);
6152: }
6153:
1.1172.2.13 raeburn 6154: # ------------------------------------------------------------ get_timebased_id
6155:
6156: sub get_timebased_id {
6157: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6158: $maxtries) = @_;
6159: my ($newid,$error,$dellock);
6160: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6161: return ('','ok','invalid call to get suffix');
6162: }
6163:
6164: # set defaults for any optional args for which values were not supplied
6165: if ($who eq '') {
6166: $who = $env{'user.name'}.':'.$env{'user.domain'};
6167: }
6168: if (!$locktries) {
6169: $locktries = 3;
6170: }
6171: if (!$maxtries) {
6172: $maxtries = 10;
6173: }
6174:
6175: if (($cdom eq '') || ($cnum eq '')) {
6176: if ($env{'request.course.id'}) {
6177: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6178: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6179: }
6180: if (($cdom eq '') || ($cnum eq '')) {
6181: return ('','ok','call to get suffix not in course context');
6182: }
6183: }
6184:
6185: # construct locking item
6186: my $lockhash = {
6187: $prefix."\0".'locked_'.$keyid => $who,
6188: };
6189: my $tries = 0;
6190:
6191: # attempt to get lock on nohist_$namespace file
6192: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6193: while (($gotlock ne 'ok') && $tries <$locktries) {
6194: $tries ++;
6195: sleep 1;
6196: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6197: }
6198:
6199: # attempt to get unique identifier, based on current timestamp
6200: if ($gotlock eq 'ok') {
6201: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6202: my $id = time;
6203: $newid = $id;
1.1172.2.56 raeburn 6204: if ($idtype eq 'addcode') {
6205: $newid .= &sixnum_code();
6206: }
1.1172.2.13 raeburn 6207: my $idtries = 0;
6208: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6209: if ($idtype eq 'concat') {
6210: $newid = $id.$idtries;
1.1172.2.56 raeburn 6211: } elsif ($idtype eq 'addcode') {
6212: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6213: } else {
6214: $newid ++;
6215: }
6216: $idtries ++;
6217: }
6218: if (!exists($inuse{$prefix."\0".$newid})) {
6219: my %new_item = (
6220: $prefix."\0".$newid => $who,
6221: );
6222: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6223: $cdom,$cnum);
6224: if ($putresult ne 'ok') {
6225: undef($newid);
6226: $error = 'error saving new item: '.$putresult;
6227: }
6228: } else {
1.1172.2.56 raeburn 6229: undef($newid);
1.1172.2.13 raeburn 6230: $error = ('error: no unique suffix available for the new item ');
6231: }
6232: # remove lock
6233: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6234: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6235: } else {
6236: $error = "error: could not obtain lockfile\n";
6237: $dellock = 'ok';
1.1172.2.58 raeburn 6238: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6239: $dellock = 'nolock';
6240: }
1.1172.2.13 raeburn 6241: }
6242: return ($newid,$dellock,$error);
6243: }
6244:
1.1172.2.56 raeburn 6245: sub sixnum_code {
6246: my $code;
6247: for (0..6) {
6248: $code .= int( rand(9) );
6249: }
6250: return $code;
6251: }
6252:
1.765 albertel 6253: # -------------------------------------------------- portfolio access checking
6254:
6255: sub portfolio_access {
1.1172.2.77 raeburn 6256: my ($requrl,$clientip) = @_;
1.765 albertel 6257: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6258: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6259: if ($result) {
6260: my %setters;
6261: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6262: my ($startblock,$endblock) =
6263: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6264: if ($startblock && $endblock) {
6265: return 'B';
6266: }
6267: } else {
6268: my ($startblock,$endblock) =
6269: &Apache::loncommon::blockcheck(\%setters,'port');
6270: if ($startblock && $endblock) {
6271: return 'B';
6272: }
6273: }
6274: }
1.765 albertel 6275: if ($result eq 'ok') {
1.766 albertel 6276: return 'F';
1.765 albertel 6277: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6278: return 'A';
1.765 albertel 6279: }
1.766 albertel 6280: return '';
1.765 albertel 6281: }
6282:
6283: sub get_portfolio_access {
1.1172.2.77 raeburn 6284: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6285:
6286: if (!ref($access_hash)) {
6287: my $current_perms = &get_portfile_permissions($udom,$unum);
6288: my %access_controls = &get_access_controls($current_perms,$group,
6289: $file_name);
6290: $access_hash = $access_controls{$file_name};
6291: }
6292:
1.1172.2.77 raeburn 6293: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6294: my $now = time;
6295: if (ref($access_hash) eq 'HASH') {
6296: foreach my $key (keys(%{$access_hash})) {
6297: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6298: if ($start > $now) {
6299: next;
6300: }
6301: if ($end && $end<$now) {
6302: next;
6303: }
6304: if ($scope eq 'public') {
6305: $public = $key;
6306: last;
6307: } elsif ($scope eq 'guest') {
6308: $guest = $key;
6309: } elsif ($scope eq 'domains') {
6310: push(@domains,$key);
6311: } elsif ($scope eq 'users') {
6312: push(@users,$key);
6313: } elsif ($scope eq 'course') {
6314: push(@courses,$key);
6315: } elsif ($scope eq 'group') {
6316: push(@groups,$key);
1.1172.2.77 raeburn 6317: } elsif ($scope eq 'ip') {
6318: push(@ips,$key);
1.765 albertel 6319: }
6320: }
6321: if ($public) {
6322: return 'ok';
1.1172.2.77 raeburn 6323: } elsif (@ips > 0) {
6324: my $allowed;
6325: foreach my $ipkey (@ips) {
6326: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6327: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6328: $allowed = 1;
6329: last;
6330: }
6331: }
6332: }
6333: if ($allowed) {
6334: return 'ok';
6335: }
1.765 albertel 6336: }
6337: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6338: if ($guest) {
6339: return $guest;
6340: }
6341: } else {
6342: if (@domains > 0) {
6343: foreach my $domkey (@domains) {
6344: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6345: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6346: return 'ok';
6347: }
6348: }
6349: }
6350: }
6351: if (@users > 0) {
6352: foreach my $userkey (@users) {
1.865 raeburn 6353: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6354: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6355: if (ref($item) eq 'HASH') {
6356: if (($item->{'uname'} eq $env{'user.name'}) &&
6357: ($item->{'udom'} eq $env{'user.domain'})) {
6358: return 'ok';
6359: }
6360: }
6361: }
6362: }
1.765 albertel 6363: }
6364: }
6365: my %roleshash;
6366: my @courses_and_groups = @courses;
6367: push(@courses_and_groups,@groups);
6368: if (@courses_and_groups > 0) {
6369: my (%allgroups,%allroles);
6370: my ($start,$end,$role,$sec,$group);
6371: foreach my $envkey (%env) {
1.1060 raeburn 6372: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6373: my $cid = $2.'_'.$3;
6374: if ($1 eq 'gr') {
6375: $group = $4;
6376: $allgroups{$cid}{$group} = $env{$envkey};
6377: } else {
6378: if ($4 eq '') {
6379: $sec = 'none';
6380: } else {
6381: $sec = $4;
6382: }
6383: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6384: }
1.811 albertel 6385: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6386: my $cid = $2.'_'.$3;
6387: if ($4 eq '') {
6388: $sec = 'none';
6389: } else {
6390: $sec = $4;
6391: }
6392: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6393: }
6394: }
6395: if (keys(%allroles) == 0) {
6396: return;
6397: }
6398: foreach my $key (@courses_and_groups) {
6399: my %content = %{$$access_hash{$key}};
6400: my $cnum = $content{'number'};
6401: my $cdom = $content{'domain'};
6402: my $cid = $cdom.'_'.$cnum;
6403: if (!exists($allroles{$cid})) {
6404: next;
6405: }
6406: foreach my $role_id (keys(%{$content{'roles'}})) {
6407: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6408: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6409: my @status = @{$content{'roles'}{$role_id}{'access'}};
6410: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6411: foreach my $role (keys(%{$allroles{$cid}})) {
6412: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6413: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6414: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6415: if (grep/^all$/,@sections) {
6416: return 'ok';
6417: } else {
6418: if (grep/^$sec$/,@sections) {
6419: return 'ok';
6420: }
6421: }
6422: }
6423: }
6424: if (keys(%{$allgroups{$cid}}) == 0) {
6425: if (grep/^none$/,@groups) {
6426: return 'ok';
6427: }
6428: } else {
6429: if (grep/^all$/,@groups) {
6430: return 'ok';
6431: }
6432: foreach my $group (keys(%{$allgroups{$cid}})) {
6433: if (grep/^$group$/,@groups) {
6434: return 'ok';
6435: }
6436: }
6437: }
6438: }
6439: }
6440: }
6441: }
6442: }
6443: if ($guest) {
6444: return $guest;
6445: }
6446: }
6447: }
6448: return;
6449: }
6450:
6451: sub course_group_datechecker {
6452: my ($dates,$now,$status) = @_;
6453: my ($start,$end) = split(/\./,$dates);
6454: if (!$start && !$end) {
6455: return 'ok';
6456: }
6457: if (grep/^active$/,@{$status}) {
6458: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6459: return 'ok';
6460: }
6461: }
6462: if (grep/^previous$/,@{$status}) {
6463: if ($end > $now ) {
6464: return 'ok';
6465: }
6466: }
6467: if (grep/^future$/,@{$status}) {
6468: if ($start > $now) {
6469: return 'ok';
6470: }
6471: }
6472: return;
6473: }
6474:
6475: sub parse_portfolio_url {
6476: my ($url) = @_;
6477:
6478: my ($type,$udom,$unum,$group,$file_name);
6479:
1.823 albertel 6480: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6481: $type = 1;
6482: $udom = $1;
6483: $unum = $2;
6484: $file_name = $3;
1.823 albertel 6485: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6486: $type = 2;
6487: $udom = $1;
6488: $unum = $2;
6489: $group = $3;
6490: $file_name = $3.'/'.$4;
6491: }
6492: if (wantarray) {
6493: return ($type,$udom,$unum,$file_name,$group);
6494: }
6495: return $type;
6496: }
6497:
6498: sub is_portfolio_url {
6499: my ($url) = @_;
6500: return scalar(&parse_portfolio_url($url));
6501: }
6502:
1.798 raeburn 6503: sub is_portfolio_file {
6504: my ($file) = @_;
1.820 raeburn 6505: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6506: return 1;
6507: }
6508: return;
6509: }
6510:
1.976 raeburn 6511: sub usertools_access {
1.1084 raeburn 6512: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6513: my ($access,%tools);
6514: if ($context eq '') {
6515: $context = 'tools';
6516: }
6517: if ($context eq 'requestcourses') {
6518: %tools = (
6519: official => 1,
6520: unofficial => 1,
1.1006 raeburn 6521: community => 1,
1.1172.2.37 raeburn 6522: textbook => 1,
1.985 raeburn 6523: );
1.1172.2.9 raeburn 6524: } elsif ($context eq 'requestauthor') {
6525: %tools = (
6526: requestauthor => 1,
6527: );
1.985 raeburn 6528: } else {
6529: %tools = (
6530: aboutme => 1,
6531: blog => 1,
1.1172.2.6 raeburn 6532: webdav => 1,
1.985 raeburn 6533: portfolio => 1,
6534: );
6535: }
1.976 raeburn 6536: return if (!defined($tools{$tool}));
6537:
1.1172.2.35 raeburn 6538: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6539: $udom = $env{'user.domain'};
6540: $uname = $env{'user.name'};
6541: }
6542:
1.978 raeburn 6543: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6544: if ($action ne 'reload') {
1.985 raeburn 6545: if ($context eq 'requestcourses') {
6546: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6547: } elsif ($context eq 'requestauthor') {
6548: return $env{'environment.canrequest.author'};
1.985 raeburn 6549: } else {
6550: return $env{'environment.availabletools.'.$tool};
6551: }
6552: }
1.976 raeburn 6553: }
6554:
1.1172.2.9 raeburn 6555: my ($toolstatus,$inststatus,$envkey);
6556: if ($context eq 'requestauthor') {
6557: $envkey = $context;
6558: } else {
6559: $envkey = $context.'.'.$tool;
6560: }
1.976 raeburn 6561:
1.985 raeburn 6562: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6563: ($action ne 'reload')) {
1.1172.2.9 raeburn 6564: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6565: $inststatus = $env{'environment.inststatus'};
6566: } else {
1.1084 raeburn 6567: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6568: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6569: $inststatus = $userenvref->{'inststatus'};
6570: } else {
1.1172.2.9 raeburn 6571: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6572: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6573: $inststatus = $userenv{'inststatus'};
6574: }
1.976 raeburn 6575: }
6576:
6577: if ($toolstatus ne '') {
6578: if ($toolstatus) {
6579: $access = 1;
6580: } else {
6581: $access = 0;
6582: }
6583: return $access;
6584: }
6585:
1.1084 raeburn 6586: my ($is_adv,%domdef);
6587: if (ref($is_advref) eq 'HASH') {
6588: $is_adv = $is_advref->{'is_adv'};
6589: } else {
6590: $is_adv = &is_advanced_user($udom,$uname);
6591: }
6592: if (ref($domdefref) eq 'HASH') {
6593: %domdef = %{$domdefref};
6594: } else {
6595: %domdef = &get_domain_defaults($udom);
6596: }
1.976 raeburn 6597: if (ref($domdef{$tool}) eq 'HASH') {
6598: if ($is_adv) {
6599: if ($domdef{$tool}{'_LC_adv'} ne '') {
6600: if ($domdef{$tool}{'_LC_adv'}) {
6601: $access = 1;
6602: } else {
6603: $access = 0;
6604: }
6605: return $access;
6606: }
6607: }
6608: if ($inststatus ne '') {
6609: my ($hasaccess,$hasnoaccess);
6610: foreach my $affiliation (split(/:/,$inststatus)) {
6611: if ($domdef{$tool}{$affiliation} ne '') {
6612: if ($domdef{$tool}{$affiliation}) {
6613: $hasaccess = 1;
6614: } else {
6615: $hasnoaccess = 1;
6616: }
6617: }
6618: }
6619: if ($hasaccess || $hasnoaccess) {
6620: if ($hasaccess) {
6621: $access = 1;
6622: } elsif ($hasnoaccess) {
6623: $access = 0;
6624: }
6625: return $access;
6626: }
6627: } else {
6628: if ($domdef{$tool}{'default'} ne '') {
6629: if ($domdef{$tool}{'default'}) {
6630: $access = 1;
6631: } elsif ($domdef{$tool}{'default'} == 0) {
6632: $access = 0;
6633: }
6634: return $access;
6635: }
6636: }
6637: } else {
1.1172.2.6 raeburn 6638: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6639: $access = 1;
6640: } else {
6641: $access = 0;
6642: }
1.976 raeburn 6643: return $access;
6644: }
6645: }
6646:
1.1050 raeburn 6647: sub is_course_owner {
6648: my ($cdom,$cnum,$udom,$uname) = @_;
6649: if (($udom eq '') || ($uname eq '')) {
6650: $udom = $env{'user.domain'};
6651: $uname = $env{'user.name'};
6652: }
6653: unless (($udom eq '') || ($uname eq '')) {
6654: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6655: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6656: return 1;
6657: } else {
6658: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6659: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6660: return 1;
6661: }
6662: }
6663: }
6664: }
6665: return;
6666: }
6667:
1.976 raeburn 6668: sub is_advanced_user {
6669: my ($udom,$uname) = @_;
1.1085 raeburn 6670: if ($udom ne '' && $uname ne '') {
6671: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6672: if (wantarray) {
6673: return ($env{'user.adv'},$env{'user.author'});
6674: } else {
6675: return $env{'user.adv'};
6676: }
1.1085 raeburn 6677: }
6678: }
1.976 raeburn 6679: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6680: my %allroles;
1.1128 raeburn 6681: my ($is_adv,$is_author);
1.976 raeburn 6682: foreach my $role (keys(%roleshash)) {
6683: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6684: my $area = '/'.$tdomain.'/'.$trest;
6685: if ($sec ne '') {
6686: $area .= '/'.$sec;
6687: }
6688: if (($area ne '') && ($trole ne '')) {
6689: my $spec=$trole.'.'.$area;
6690: if ($trole =~ /^cr\//) {
6691: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6692: } elsif ($trole ne 'gr') {
6693: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6694: }
1.1128 raeburn 6695: if ($trole eq 'au') {
6696: $is_author = 1;
6697: }
1.976 raeburn 6698: }
6699: }
6700: foreach my $role (keys(%allroles)) {
6701: last if ($is_adv);
6702: foreach my $item (split(/:/,$allroles{$role})) {
6703: if ($item ne '') {
6704: my ($privilege,$restrictions)=split(/&/,$item);
6705: if ($privilege eq 'adv') {
6706: $is_adv = 1;
6707: last;
6708: }
6709: }
6710: }
6711: }
1.1128 raeburn 6712: if (wantarray) {
6713: return ($is_adv,$is_author);
6714: }
1.976 raeburn 6715: return $is_adv;
6716: }
1.798 raeburn 6717:
1.1035 raeburn 6718: sub check_can_request {
1.1036 raeburn 6719: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6720: my $canreq = 0;
6721: my ($types,$typename) = &Apache::loncommon::course_types();
6722: my @options = ('approval','validate','autolimit');
6723: my $optregex = join('|',@options);
6724: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6725: foreach my $type (@{$types}) {
6726: if (&usertools_access($env{'user.name'},
6727: $env{'user.domain'},
6728: $type,undef,'requestcourses')) {
6729: $canreq ++;
1.1036 raeburn 6730: if (ref($request_domains) eq 'HASH') {
6731: push(@{$request_domains->{$type}},$env{'user.domain'});
6732: }
1.1035 raeburn 6733: if ($dom eq $env{'user.domain'}) {
6734: $can_request->{$type} = 1;
6735: }
6736: }
6737: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6738: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6739: if (@curr > 0) {
1.1036 raeburn 6740: foreach my $item (@curr) {
6741: if (ref($request_domains) eq 'HASH') {
6742: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6743: if ($otherdom ne '') {
6744: if (ref($request_domains->{$type}) eq 'ARRAY') {
6745: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6746: push(@{$request_domains->{$type}},$otherdom);
6747: }
6748: } else {
6749: push(@{$request_domains->{$type}},$otherdom);
6750: }
6751: }
6752: }
6753: }
6754: unless($dom eq $env{'user.domain'}) {
6755: $canreq ++;
1.1035 raeburn 6756: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6757: $can_request->{$type} = 1;
6758: }
6759: }
6760: }
6761: }
6762: }
6763: }
6764: return $canreq;
6765: }
6766:
1.341 www 6767: # ---------------------------------------------- Custom access rule evaluation
6768:
6769: sub customaccess {
6770: my ($priv,$uri)=@_;
1.807 albertel 6771: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6772: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6773: $udom = &LONCAPA::clean_domain($udom);
6774: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6775: my $access=0;
1.800 albertel 6776: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6777: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6778: if ($type eq 'user') {
6779: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6780: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6781: if ($tdom) {
6782: if ($tdom ne $env{'user.domain'}) { next; }
6783: }
1.896 albertel 6784: if ($tuname) {
6785: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6786: }
6787: $access=($effect eq 'allow');
6788: last;
6789: }
6790: } else {
6791: if ($role) {
6792: if ($role ne $urole) { next; }
6793: }
6794: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6795: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6796: if ($tdom) {
6797: if ($tdom ne $udom) { next; }
6798: }
6799: if ($tcrs) {
6800: if ($tcrs ne $ucrs) { next; }
6801: }
6802: if ($tsec) {
6803: if ($tsec ne $usec) { next; }
6804: }
6805: $access=($effect eq 'allow');
6806: last;
6807: }
6808: if ($realm eq '' && $role eq '') {
6809: $access=($effect eq 'allow');
6810: }
1.402 bowersj2 6811: }
1.341 www 6812: }
6813: return $access;
6814: }
6815:
1.103 harris41 6816: # ------------------------------------------------- Check for a user privilege
1.12 www 6817:
6818: sub allowed {
1.1172.2.65 raeburn 6819: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6820: my $ver_orguri=$uri;
1.439 www 6821: $uri=&deversion($uri);
1.152 www 6822: my $orguri=$uri;
1.52 www 6823: $uri=&declutter($uri);
1.809 raeburn 6824:
1.810 raeburn 6825: if ($priv eq 'evb') {
6826: # Evade communication block restrictions for specified role in a course
6827: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6828: return $1;
6829: } else {
6830: return;
6831: }
6832: }
6833:
1.620 albertel 6834: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6835: # Free bre access to adm and meta resources
1.775 albertel 6836: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6837: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6838: && ($priv eq 'bre')) {
1.14 www 6839: return 'F';
1.159 www 6840: }
6841:
1.545 banghart 6842: # Free bre access to user's own portfolio contents
1.714 raeburn 6843: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6844: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6845: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6846: my %setters;
6847: my ($startblock,$endblock) =
6848: &Apache::loncommon::blockcheck(\%setters,'port');
6849: if ($startblock && $endblock) {
6850: return 'B';
6851: } else {
6852: return 'F';
6853: }
1.545 banghart 6854: }
6855:
1.762 raeburn 6856: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6857: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6858: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6859: if (exists($env{'request.course.id'})) {
6860: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6861: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6862: if (($domain eq $cdom) && ($name eq $cnum)) {
6863: my $courseprivid=$env{'request.course.id'};
6864: $courseprivid=~s/\_/\//;
6865: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6866: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6867: return $1;
1.762 raeburn 6868: } else {
6869: if ($env{'request.course.sec'}) {
6870: $courseprivid.='/'.$env{'request.course.sec'};
6871: }
6872: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6873: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6874: return $2;
6875: }
1.714 raeburn 6876: }
6877: }
6878: }
6879: }
6880:
1.159 www 6881: # Free bre to public access
6882:
6883: if ($priv eq 'bre') {
1.238 www 6884: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6885: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6886: return 'F';
6887: }
1.238 www 6888: if ($copyright eq 'priv') {
6889: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6890: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6891: return '';
6892: }
6893: }
6894: if ($copyright eq 'domain') {
6895: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6896: unless (($env{'user.domain'} eq $1) ||
6897: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6898: return '';
6899: }
1.262 matthew 6900: }
1.620 albertel 6901: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6902: # Library role, so allow browsing of resources in this domain.
6903: return 'F';
1.238 www 6904: }
1.341 www 6905: if ($copyright eq 'custom') {
6906: unless (&customaccess($priv,$uri)) { return ''; }
6907: }
1.14 www 6908: }
1.264 matthew 6909: # Domain coordinator is trying to create a course
1.620 albertel 6910: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6911: # uri is the requested domain in this case.
6912: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6913: # a role of dc for the domain in question.
1.620 albertel 6914: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6915: }
1.29 www 6916:
1.52 www 6917: my $thisallowed='';
6918: my $statecond=0;
6919: my $courseprivid='';
6920:
1.1039 raeburn 6921: my $ownaccess;
1.1043 raeburn 6922: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6923: if (($priv eq 'bro') && ($env{'user.author'})) {
6924: if ($uri eq '') {
6925: $ownaccess = 1;
6926: } else {
6927: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6928: my $udom = $env{'user.domain'};
6929: my $uname = $env{'user.name'};
6930: if ($uri =~ m{^\Q$udom\E/?$}) {
6931: $ownaccess = 1;
1.1040 raeburn 6932: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6933: unless ($uri =~ m{\.\./}) {
6934: $ownaccess = 1;
6935: }
6936: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6937: my $now = time;
6938: if ($uri =~ m{^([^/]+)/?$}) {
6939: my $adom = $1;
6940: foreach my $key (keys(%env)) {
1.1042 raeburn 6941: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6942: my ($start,$end) = split('.',$env{$key});
6943: if (($now >= $start) && (!$end || $end < $now)) {
6944: $ownaccess = 1;
6945: last;
6946: }
6947: }
6948: }
6949: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6950: my $adom = $1;
6951: my $aname = $2;
1.1042 raeburn 6952: foreach my $role ('ca','aa') {
6953: if ($env{"user.role.$role./$adom/$aname"}) {
6954: my ($start,$end) =
6955: split('.',$env{"user.role.$role./$adom/$aname"});
6956: if (($now >= $start) && (!$end || $end < $now)) {
6957: $ownaccess = 1;
6958: last;
6959: }
1.1039 raeburn 6960: }
6961: }
6962: }
6963: }
6964: }
6965: }
6966: }
6967:
1.52 www 6968: # Course
6969:
1.620 albertel 6970: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6971: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6972: $thisallowed.=$1;
6973: }
1.52 www 6974: }
1.29 www 6975:
1.52 www 6976: # Domain
6977:
1.620 albertel 6978: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6979: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6980: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6981: $thisallowed.=$1;
6982: }
1.12 www 6983: }
1.52 www 6984:
1.1141 raeburn 6985: # User who is not author or co-author might still be able to edit
6986: # resource of an author in the domain (e.g., if Domain Coordinator).
6987: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6988: (&allowed('mdc',$env{'request.course.id'}))) {
6989: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6990: $thisallowed.=$1;
6991: }
6992: }
6993:
1.52 www 6994: # Course: uri itself is a course
1.66 www 6995: my $courseuri=$uri;
6996: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6997: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6998:
1.620 albertel 6999: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7000: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7001: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7002: $thisallowed.=$1;
7003: }
1.12 www 7004: }
1.29 www 7005:
1.665 albertel 7006: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7007: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7008: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7009: $thisallowed='';
1.671 raeburn 7010: my ($match)=&is_on_map($uri);
7011: if ($match) {
7012: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7013: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7014: my $value = $1;
7015: if ($noblockcheck) {
7016: $thisallowed.=$value;
1.1162 raeburn 7017: } else {
1.1172.2.65 raeburn 7018: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7019: if (@blockers > 0) {
7020: $thisallowed = 'B';
7021: } else {
7022: $thisallowed.=$value;
7023: }
1.1162 raeburn 7024: }
1.671 raeburn 7025: }
7026: } else {
1.705 albertel 7027: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7028: if ($refuri) {
7029: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7030: $thisallowed='F';
1.671 raeburn 7031: } else {
7032: $refuri=&declutter($refuri);
7033: my ($match) = &is_on_map($refuri);
7034: if ($match) {
1.1172.2.65 raeburn 7035: if ($noblockcheck) {
1.1162 raeburn 7036: $thisallowed='F';
1.1172.2.65 raeburn 7037: } else {
7038: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7039: if (@blockers > 0) {
7040: $thisallowed = 'B';
7041: } else {
7042: $thisallowed='F';
7043: }
1.1162 raeburn 7044: }
1.671 raeburn 7045: }
1.669 raeburn 7046: }
1.671 raeburn 7047: }
7048: }
1.314 www 7049: }
1.492 albertel 7050:
1.766 albertel 7051: if ($priv eq 'bre'
7052: && $thisallowed ne 'F'
7053: && $thisallowed ne '2'
7054: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7055: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7056: }
7057:
1.52 www 7058: # Full access at system, domain or course-wide level? Exit.
1.29 www 7059: if ($thisallowed=~/F/) {
7060: return 'F';
7061: }
7062:
1.52 www 7063: # If this is generating or modifying users, exit with special codes
1.29 www 7064:
1.643 www 7065: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7066: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7067: my ($audom,$auname)=split('/',$uri);
1.643 www 7068: # no author name given, so this just checks on the general right to make a co-author in this domain
7069: unless ($auname) { return $thisallowed; }
7070: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7071: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7072: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7073: ($audom ne $env{'request.role.domain'}))) { return ''; }
7074: }
1.52 www 7075: return $thisallowed;
7076: }
7077: #
1.103 harris41 7078: # Gathered so far: system, domain and course wide privileges
1.52 www 7079: #
7080: # Course: See if uri or referer is an individual resource that is part of
7081: # the course
7082:
1.620 albertel 7083: if ($env{'request.course.id'}) {
1.232 www 7084:
1.620 albertel 7085: $courseprivid=$env{'request.course.id'};
7086: if ($env{'request.course.sec'}) {
7087: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7088: }
7089: $courseprivid=~s/\_/\//;
7090: my $checkreferer=1;
1.232 www 7091: my ($match,$cond)=&is_on_map($uri);
7092: if ($match) {
7093: $statecond=$cond;
1.620 albertel 7094: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7095: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7096: my $value = $1;
7097: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7098: if ($noblockcheck) {
1.1162 raeburn 7099: $thisallowed.=$value;
1.1172.2.65 raeburn 7100: } else {
7101: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7102: if (@blockers > 0) {
7103: $thisallowed = 'B';
7104: } else {
7105: $thisallowed.=$value;
7106: }
1.1162 raeburn 7107: }
7108: } else {
7109: $thisallowed.=$value;
7110: }
1.52 www 7111: $checkreferer=0;
7112: }
1.29 www 7113: }
1.83 www 7114:
1.148 www 7115: if ($checkreferer) {
1.620 albertel 7116: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7117: unless ($refuri) {
1.800 albertel 7118: foreach my $key (keys(%env)) {
7119: if ($key=~/^httpref\..*\*/) {
7120: my $pattern=$key;
1.156 www 7121: $pattern=~s/^httpref\.\/res\///;
1.148 www 7122: $pattern=~s/\*/\[\^\/\]\+/g;
7123: $pattern=~s/\//\\\//g;
1.152 www 7124: if ($orguri=~/$pattern/) {
1.800 albertel 7125: $refuri=$env{$key};
1.148 www 7126: }
7127: }
1.191 harris41 7128: }
1.148 www 7129: }
1.232 www 7130:
1.148 www 7131: if ($refuri) {
1.152 www 7132: $refuri=&declutter($refuri);
1.232 www 7133: my ($match,$cond)=&is_on_map($refuri);
7134: if ($match) {
7135: my $refstatecond=$cond;
1.620 albertel 7136: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7137: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7138: my $value = $1;
7139: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7140: if ($noblockcheck) {
1.1162 raeburn 7141: $thisallowed.=$value;
1.1172.2.65 raeburn 7142: } else {
7143: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7144: if (@blockers > 0) {
7145: $thisallowed = 'B';
7146: } else {
7147: $thisallowed.=$value;
7148: }
1.1162 raeburn 7149: }
7150: } else {
7151: $thisallowed.=$value;
7152: }
1.53 www 7153: $uri=$refuri;
7154: $statecond=$refstatecond;
1.52 www 7155: }
7156: }
1.148 www 7157: }
1.29 www 7158: }
1.52 www 7159: }
1.29 www 7160:
1.52 www 7161: #
1.103 harris41 7162: # Gathered now: all privileges that could apply, and condition number
1.52 www 7163: #
7164: #
7165: # Full or no access?
7166: #
1.29 www 7167:
1.52 www 7168: if ($thisallowed=~/F/) {
7169: return 'F';
7170: }
1.29 www 7171:
1.52 www 7172: unless ($thisallowed) {
7173: return '';
7174: }
1.29 www 7175:
1.52 www 7176: # Restrictions exist, deal with them
7177: #
7178: # C:according to course preferences
7179: # R:according to resource settings
7180: # L:unless locked
7181: # X:according to user session state
7182: #
7183:
7184: # Possibly locked functionality, check all courses
1.54 www 7185: # Locks might take effect only after 10 minutes cache expiration for other
7186: # courses, and 2 minutes for current course
1.52 www 7187:
7188: my $envkey;
7189: if ($thisallowed=~/L/) {
1.1000 raeburn 7190: foreach $envkey (keys(%env)) {
1.54 www 7191: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7192: my $courseid=$2;
7193: my $roleid=$1.'.'.$2;
1.92 www 7194: $courseid=~s/^\///;
1.54 www 7195: my $expiretime=600;
1.620 albertel 7196: if ($env{'request.role'} eq $roleid) {
1.54 www 7197: $expiretime=120;
7198: }
7199: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7200: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7201: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7202: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7203: }
1.620 albertel 7204: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7205: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7206: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7207: &log($env{'user.domain'},$env{'user.name'},
7208: $env{'user.home'},
1.57 www 7209: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7210: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7211: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7212: return '';
7213: }
7214: }
1.620 albertel 7215: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7216: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7217: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7218: &log($env{'user.domain'},$env{'user.name'},
7219: $env{'user.home'},
1.57 www 7220: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7221: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7222: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7223: return '';
7224: }
7225: }
7226: }
1.29 www 7227: }
1.52 www 7228: }
7229:
7230: #
7231: # Rest of the restrictions depend on selected course
7232: #
7233:
1.620 albertel 7234: unless ($env{'request.course.id'}) {
1.766 albertel 7235: if ($thisallowed eq 'A') {
7236: return 'A';
1.814 raeburn 7237: } elsif ($thisallowed eq 'B') {
7238: return 'B';
1.766 albertel 7239: } else {
7240: return '1';
7241: }
1.52 www 7242: }
1.29 www 7243:
1.52 www 7244: #
7245: # Now user is definitely in a course
7246: #
1.53 www 7247:
7248:
7249: # Course preferences
7250:
7251: if ($thisallowed=~/C/) {
1.620 albertel 7252: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7253: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7254: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7255: =~/\Q$rolecode\E/) {
1.1103 raeburn 7256: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7257: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7258: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7259: $env{'request.course.id'});
7260: }
1.237 www 7261: return '';
7262: }
7263:
1.620 albertel 7264: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7265: =~/\Q$unamedom\E/) {
1.1103 raeburn 7266: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7267: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7268: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7269: $env{'request.course.id'});
7270: }
1.54 www 7271: return '';
7272: }
1.53 www 7273: }
7274:
7275: # Resource preferences
7276:
7277: if ($thisallowed=~/R/) {
1.620 albertel 7278: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7279: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7280: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7281: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7282: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7283: }
7284: return '';
1.54 www 7285: }
1.53 www 7286: }
1.30 www 7287:
1.246 www 7288: # Restricted by state or randomout?
1.30 www 7289:
1.52 www 7290: if ($thisallowed=~/X/) {
1.620 albertel 7291: if ($env{'acc.randomout'}) {
1.579 albertel 7292: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7293: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7294: return '';
7295: }
1.247 www 7296: }
7297: if (&condval($statecond)) {
1.52 www 7298: return '2';
7299: } else {
7300: return '';
7301: }
7302: }
1.30 www 7303:
1.766 albertel 7304: if ($thisallowed eq 'A') {
7305: return 'A';
1.814 raeburn 7306: } elsif ($thisallowed eq 'B') {
7307: return 'B';
1.766 albertel 7308: }
1.52 www 7309: return 'F';
1.232 www 7310: }
1.1162 raeburn 7311:
1.1172.2.13 raeburn 7312: # ------------------------------------------- Check construction space access
7313:
7314: sub constructaccess {
7315: my ($url,$setpriv)=@_;
7316:
7317: # We do not allow editing of previous versions of files
7318: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7319:
7320: # Get username and domain from URL
7321: my ($ownername,$ownerdomain,$ownerhome);
7322:
7323: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7324: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7325:
7326: # The URL does not really point to any authorspace, forget it
7327: unless (($ownername) && ($ownerdomain)) { return ''; }
7328:
7329: # Now we need to see if the user has access to the authorspace of
7330: # $ownername at $ownerdomain
7331:
7332: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7333: # Real author for this?
7334: $ownerhome = $env{'user.home'};
7335: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7336: return ($ownername,$ownerdomain,$ownerhome);
7337: }
7338: } else {
7339: # Co-author for this?
7340: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7341: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7342: $ownerhome = &homeserver($ownername,$ownerdomain);
7343: return ($ownername,$ownerdomain,$ownerhome);
7344: }
7345: }
7346:
7347: # We don't have any access right now. If we are not possibly going to do anything about this,
7348: # we might as well leave
7349: unless ($setpriv) { return ''; }
7350:
7351: # Backdoor access?
7352: my $allowed=&allowed('eco',$ownerdomain);
7353: # Nope
7354: unless ($allowed) { return ''; }
7355: # Looks like we may have access, but could be locked by the owner of the construction space
7356: if ($allowed eq 'U') {
7357: my %blocked=&get('environment',['domcoord.author'],
7358: $ownerdomain,$ownername);
7359: # Is blocked by owner
7360: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7361: }
7362: if (($allowed eq 'F') || ($allowed eq 'U')) {
7363: # Grant temporary access
7364: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7365: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7366: if (!$update) { $update = $then; }
7367: my $refresh=$env{'user.refresh.time'};
7368: if (!$refresh) { $refresh = $update; }
7369: my $now = time;
7370: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7371: $now,'ca','constructaccess');
7372: $ownerhome = &homeserver($ownername,$ownerdomain);
7373: return($ownername,$ownerdomain,$ownerhome);
7374: }
7375: # No business here
7376: return '';
7377: }
7378:
1.1172.2.66 raeburn 7379: # ----------------------------------------------------------- Content Blocking
7380:
7381: {
7382: # Caches for faster Course Contents display where content blocking
7383: # is in operation (i.e., interval param set) for timed quiz.
7384: #
7385: # User for whom data are being temporarily cached.
7386: my $cacheduser='';
7387: # Cached blockers for this user (a hash of blocking items).
7388: my %cachedblockers=();
7389: # When the data were last cached.
7390: my $cachedlast='';
7391:
7392: sub load_all_blockers {
7393: my ($uname,$udom,$blocks)=@_;
7394: if (($uname ne '') && ($udom ne '')) {
7395: if (($cacheduser eq $uname.':'.$udom) &&
7396: (abs($cachedlast-time)<5)) {
7397: return;
7398: }
7399: }
7400: $cachedlast=time;
7401: $cacheduser=$uname.':'.$udom;
7402: %cachedblockers = &get_commblock_resources($blocks);
7403: }
7404:
1.1162 raeburn 7405: sub get_comm_blocks {
7406: my ($cdom,$cnum) = @_;
7407: if ($cdom eq '' || $cnum eq '') {
7408: return unless ($env{'request.course.id'});
7409: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7410: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7411: }
7412: my %commblocks;
7413: my $hashid=$cdom.'_'.$cnum;
7414: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7415: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7416: %commblocks = %{$blocksref};
7417: } else {
7418: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7419: my $cachetime = 600;
7420: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7421: }
7422: return %commblocks;
7423: }
7424:
1.1172.2.66 raeburn 7425: sub get_commblock_resources {
7426: my ($blocks) = @_;
7427: my %blockers = ();
7428: return %blockers unless ($env{'request.course.id'});
7429: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7430: my %commblocks;
7431: if (ref($blocks) eq 'HASH') {
7432: %commblocks = %{$blocks};
7433: } else {
7434: %commblocks = &get_comm_blocks();
7435: }
1.1172.2.66 raeburn 7436: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7437: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7438: return %blockers unless (ref($navmap));
7439: my $now = time;
1.1162 raeburn 7440: foreach my $block (keys(%commblocks)) {
7441: if ($block =~ /^(\d+)____(\d+)$/) {
7442: my ($start,$end) = ($1,$2);
7443: if ($start <= $now && $end >= $now) {
7444: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7445: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7446: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7447: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7448: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7449: }
7450: }
7451: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7452: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7453: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7454: }
7455: }
7456: }
7457: }
7458: }
7459: } elsif ($block =~ /^firstaccess____(.+)$/) {
7460: my $item = $1;
1.1163 raeburn 7461: my @to_test;
1.1162 raeburn 7462: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7463: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7464: my @interval;
7465: my $type = 'map';
7466: if ($item eq 'course') {
7467: $type = 'course';
7468: @interval=&EXT("resource.0.interval");
7469: } else {
7470: if ($item =~ /___\d+___/) {
7471: $type = 'resource';
7472: @interval=&EXT("resource.0.interval",$item);
7473: if (ref($navmap)) {
7474: my $res = $navmap->getBySymb($item);
7475: push(@to_test,$res);
7476: }
1.1162 raeburn 7477: } else {
1.1172.2.66 raeburn 7478: my $mapsymb = &symbread($item,1);
7479: if ($mapsymb) {
7480: if (ref($navmap)) {
7481: my $mapres = $navmap->getBySymb($mapsymb);
7482: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7483: foreach my $res (@to_test) {
7484: my $symb = $res->symb();
7485: next if ($symb eq $mapsymb);
7486: if ($symb ne '') {
7487: @interval=&EXT("resource.0.interval",$symb);
7488: if ($interval[1] eq 'map') {
7489: last;
1.1162 raeburn 7490: }
7491: }
7492: }
7493: }
7494: }
7495: }
1.1172.2.66 raeburn 7496: }
7497: if ($interval[0] =~ /^\d+$/) {
7498: my $first_access;
7499: if ($type eq 'resource') {
7500: $first_access=&get_first_access($interval[1],$item);
7501: } elsif ($type eq 'map') {
7502: $first_access=&get_first_access($interval[1],undef,$item);
7503: } else {
7504: $first_access=&get_first_access($interval[1]);
7505: }
7506: if ($first_access) {
7507: my $timesup = $first_access+$interval[0];
7508: if ($timesup > $now) {
7509: my $activeblock;
7510: foreach my $res (@to_test) {
7511: if ($res->answerable()) {
7512: $activeblock = 1;
7513: last;
7514: }
7515: }
7516: if ($activeblock) {
7517: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7518: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7519: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7520: }
7521: }
7522: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7523: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7524: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7525: }
1.1162 raeburn 7526: }
7527: }
7528: }
7529: }
7530: }
7531: }
7532: }
7533: }
7534: }
1.1172.2.66 raeburn 7535: return %blockers;
1.1162 raeburn 7536: }
7537:
1.1172.2.66 raeburn 7538: sub has_comm_blocking {
7539: my ($priv,$symb,$uri,$blocks) = @_;
7540: my @blockers;
7541: return unless ($env{'request.course.id'});
7542: return unless ($priv eq 'bre');
7543: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7544: return if ($env{'request.state'} eq 'construct');
7545: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7546: return unless (keys(%cachedblockers) > 0);
7547: my (%possibles,@symbs);
7548: if (!$symb) {
7549: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7550: }
1.1172.2.66 raeburn 7551: if ($symb) {
7552: @symbs = ($symb);
7553: } elsif (keys(%possibles)) {
7554: @symbs = keys(%possibles);
7555: }
7556: my $noblock;
7557: foreach my $symb (@symbs) {
7558: last if ($noblock);
7559: my ($map,$resid,$resurl)=&decode_symb($symb);
7560: foreach my $block (keys(%cachedblockers)) {
7561: if ($block =~ /^firstaccess____(.+)$/) {
7562: my $item = $1;
7563: if (($item eq $map) || ($item eq $symb)) {
7564: $noblock = 1;
7565: last;
7566: }
1.1162 raeburn 7567: }
1.1172.2.66 raeburn 7568: if (ref($cachedblockers{$block}) eq 'HASH') {
7569: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7570: if ($cachedblockers{$block}{'resources'}{$symb}) {
7571: unless (grep(/^\Q$block\E$/,@blockers)) {
7572: push(@blockers,$block);
7573: }
7574: }
7575: }
7576: }
7577: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7578: if ($cachedblockers{$block}{'maps'}{$map}) {
7579: unless (grep(/^\Q$block\E$/,@blockers)) {
7580: push(@blockers,$block);
7581: }
7582: }
1.1162 raeburn 7583: }
7584: }
7585: }
1.1172.2.66 raeburn 7586: return if ($noblock);
7587: return @blockers;
7588: }
1.1162 raeburn 7589: }
7590:
1.1172.2.66 raeburn 7591: # -------------------------------- Deversion and split uri into path an filename
7592:
1.1133 foxr 7593: #
1.1172.2.66 raeburn 7594: # Removes the version from a URI and
1.1133 foxr 7595: # splits it in to its filename and path to the filename.
7596: # Seems like File::Basename could have done this more clearly.
7597: # Parameters:
7598: # $uri - input URI
7599: # Returns:
7600: # Two element list consisting of
7601: # $pathname - the URI up to and excluding the trailing /
7602: # $filename - The part of the URI following the last /
7603: # NOTE:
7604: # Another realization of this is simply:
7605: # use File::Basename;
7606: # ...
7607: # $uri = shift;
7608: # $filename = basename($uri);
7609: # $path = dirname($uri);
7610: # return ($filename, $path);
7611: #
7612: # The implementation below is probably faster however.
7613: #
1.710 albertel 7614: sub split_uri_for_cond {
7615: my $uri=&deversion(&declutter(shift));
7616: my @uriparts=split(/\//,$uri);
7617: my $filename=pop(@uriparts);
7618: my $pathname=join('/',@uriparts);
7619: return ($pathname,$filename);
7620: }
1.232 www 7621: # --------------------------------------------------- Is a resource on the map?
7622:
7623: sub is_on_map {
1.710 albertel 7624: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7625: #Trying to find the conditional for the file
1.620 albertel 7626: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7627: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7628: if ($match) {
1.289 bowersj2 7629: return (1,$1);
7630: } else {
1.434 www 7631: return (0,0);
1.289 bowersj2 7632: }
1.12 www 7633: }
7634:
1.427 www 7635: # --------------------------------------------------------- Get symb from alias
7636:
7637: sub get_symb_from_alias {
7638: my $symb=shift;
7639: my ($map,$resid,$url)=&decode_symb($symb);
7640: # Already is a symb
7641: if ($url) { return $symb; }
7642: # Must be an alias
7643: my $aliassymb='';
7644: my %bighash;
1.620 albertel 7645: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7646: &GDBM_READER(),0640)) {
7647: my $rid=$bighash{'mapalias_'.$symb};
7648: if ($rid) {
7649: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7650: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7651: $resid,$bighash{'src_'.$rid});
1.427 www 7652: }
7653: untie %bighash;
7654: }
7655: return $aliassymb;
7656: }
7657:
1.12 www 7658: # ----------------------------------------------------------------- Define Role
7659:
7660: sub definerole {
7661: if (allowed('mcr','/')) {
1.1172.2.84! raeburn 7662: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7663: foreach my $role (split(':',$sysrole)) {
7664: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7665: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7666: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7667: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7668: return "refused:s:$crole&$cqual";
7669: }
7670: }
1.191 harris41 7671: }
1.800 albertel 7672: foreach my $role (split(':',$domrole)) {
7673: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7674: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7675: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7676: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7677: return "refused:d:$crole&$cqual";
7678: }
7679: }
1.191 harris41 7680: }
1.800 albertel 7681: foreach my $role (split(':',$courole)) {
7682: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7683: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7684: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7685: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7686: return "refused:c:$crole&$cqual";
7687: }
7688: }
1.191 harris41 7689: }
1.1172.2.84! raeburn 7690: my $uhome;
! 7691: if (($uname ne '') && ($udom ne '')) {
! 7692: $uhome = &homeserver($uname,$udom);
! 7693: return $uhome if ($uhome eq 'no_host');
! 7694: } else {
! 7695: $uname = $env{'user.name'};
! 7696: $udom = $env{'user.domain'};
! 7697: $uhome = $env{'user.home'};
! 7698: }
1.620 albertel 7699: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84! raeburn 7700: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7701: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84! raeburn 7702: return reply($command,$uhome);
1.12 www 7703: } else {
7704: return 'refused';
7705: }
1.105 harris41 7706: }
7707:
7708: # ---------------- Make a metadata query against the network of library servers
7709:
7710: sub metadata_query {
1.1172.2.33 raeburn 7711: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7712: my %rhash;
1.845 albertel 7713: my %libserv = &all_library();
1.244 matthew 7714: my @server_list = (defined($server_array) ? @$server_array
7715: : keys(%libserv) );
7716: for my $server (@server_list) {
1.1172.2.33 raeburn 7717: my $domains = '';
7718: if (ref($domains_hash) eq 'HASH') {
7719: $domains = $domains_hash->{$server};
7720: }
1.118 harris41 7721: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7722: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7723: $rhash{$server}=$reply;
7724: }
7725: else {
7726: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7727: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7728: $server);
7729: $rhash{$server}=$reply;
7730: }
1.112 harris41 7731: }
1.118 harris41 7732: return \%rhash;
1.240 www 7733: }
7734:
7735: # ----------------------------------------- Send log queries and wait for reply
7736:
7737: sub log_query {
7738: my ($uname,$udom,$query,%filters)=@_;
7739: my $uhome=&homeserver($uname,$udom);
7740: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7741: my $uhost=&hostname($uhome);
1.800 albertel 7742: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7743: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7744: $uhome);
1.479 albertel 7745: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7746: return get_query_reply($queryid);
7747: }
7748:
1.818 raeburn 7749: # -------------------------- Update MySQL table for portfolio file
7750:
7751: sub update_portfolio_table {
1.821 raeburn 7752: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7753: if ($group ne '') {
7754: $file_name =~s /^\Q$group\E//;
7755: }
1.818 raeburn 7756: my $homeserver = &homeserver($uname,$udom);
7757: my $queryid=
1.821 raeburn 7758: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7759: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7760: my $reply = &get_query_reply($queryid);
7761: return $reply;
7762: }
7763:
1.899 raeburn 7764: # -------------------------- Update MySQL allusers table
7765:
7766: sub update_allusers_table {
7767: my ($uname,$udom,$names) = @_;
7768: my $homeserver = &homeserver($uname,$udom);
7769: my $queryid=
7770: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7771: 'lastname='.&escape($names->{'lastname'}).'%%'.
7772: 'firstname='.&escape($names->{'firstname'}).'%%'.
7773: 'middlename='.&escape($names->{'middlename'}).'%%'.
7774: 'generation='.&escape($names->{'generation'}).'%%'.
7775: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7776: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7777: return;
1.899 raeburn 7778: }
7779:
1.508 raeburn 7780: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7781:
7782: sub fetch_enrollment_query {
1.511 raeburn 7783: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 7784: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7785: my $maxtries = 1;
1.508 raeburn 7786: if ($context eq 'automated') {
7787: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 7788: $sleep = 2;
7789: $loopmax = 100;
1.547 raeburn 7790: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7791: } else {
7792: $homeserver = &homeserver($cnum,$dom);
7793: }
1.838 albertel 7794: my $host=&hostname($homeserver);
1.506 raeburn 7795: my $cmd = '';
1.1000 raeburn 7796: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7797: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7798: }
7799: $cmd =~ s/%%$//;
7800: $cmd = &escape($cmd);
7801: my $query = 'fetchenrollment';
1.620 albertel 7802: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7803: unless ($queryid=~/^\Q$host\E\_/) {
7804: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7805: return 'error: '.$queryid;
7806: }
1.1172.2.79 raeburn 7807: my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547 raeburn 7808: my $tries = 1;
7809: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 7810: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7811: $tries ++;
7812: }
1.526 raeburn 7813: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7814: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7815: } else {
1.901 albertel 7816: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 7817: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 7818: foreach my $line (@responses) {
7819: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7820: $$replyref{$key} = $value;
7821: }
7822: } else {
1.1117 foxr 7823: my $pathname = LONCAPA::tempdir();
1.800 albertel 7824: foreach my $line (@responses) {
7825: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7826: $$replyref{$key} = $value;
7827: if ($value > 0) {
1.800 albertel 7828: foreach my $item (@{$$affiliatesref{$key}}) {
7829: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7830: my $destname = $pathname.'/'.$filename;
7831: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7832: if ($xml_classlist =~ /^error/) {
7833: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7834: } else {
1.506 raeburn 7835: if ( open(FILE,">$destname") ) {
7836: print FILE &unescape($xml_classlist);
7837: close(FILE);
1.526 raeburn 7838: } else {
7839: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7840: }
7841: }
7842: }
7843: }
7844: }
7845: }
7846: return 'ok';
7847: }
7848: return 'error';
7849: }
7850:
1.242 www 7851: sub get_query_reply {
1.1172.2.79 raeburn 7852: my ($queryid,$sleep,$loopmax) = @_;
7853: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
7854: $sleep = 0.2;
7855: }
7856: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
7857: $loopmax = 100;
7858: }
1.1117 foxr 7859: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7860: my $reply='';
1.1172.2.79 raeburn 7861: for (1..$loopmax) {
7862: sleep($sleep);
1.240 www 7863: if (-e $replyfile.'.end') {
1.448 albertel 7864: if (open(my $fh,$replyfile)) {
1.904 albertel 7865: $reply = join('',<$fh>);
7866: close($fh);
1.240 www 7867: } else { return 'error: reply_file_error'; }
1.242 www 7868: return &unescape($reply);
7869: }
1.240 www 7870: }
1.242 www 7871: return 'timeout:'.$queryid;
1.240 www 7872: }
7873:
7874: sub courselog_query {
1.241 www 7875: #
7876: # possible filters:
7877: # url: url or symb
7878: # username
7879: # domain
7880: # action: view, submit, grade
7881: # start: timestamp
7882: # end: timestamp
7883: #
1.240 www 7884: my (%filters)=@_;
1.620 albertel 7885: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7886: if ($filters{'url'}) {
7887: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7888: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7889: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7890: }
1.620 albertel 7891: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7892: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7893: return &log_query($cname,$cdom,'courselog',%filters);
7894: }
7895:
7896: sub userlog_query {
1.858 raeburn 7897: #
7898: # possible filters:
7899: # action: log check role
7900: # start: timestamp
7901: # end: timestamp
7902: #
1.240 www 7903: my ($uname,$udom,%filters)=@_;
7904: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7905: }
7906:
1.506 raeburn 7907: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7908:
7909: sub auto_run {
1.508 raeburn 7910: my ($cnum,$cdom) = @_;
1.876 raeburn 7911: my $response = 0;
7912: my $settings;
7913: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7914: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7915: $settings = $domconfig{'autoenroll'};
7916: if ($settings->{'run'} eq '1') {
7917: $response = 1;
7918: }
7919: } else {
1.934 raeburn 7920: my $homeserver;
7921: if (&is_course($cdom,$cnum)) {
7922: $homeserver = &homeserver($cnum,$cdom);
7923: } else {
7924: $homeserver = &domain($cdom,'primary');
7925: }
7926: if ($homeserver ne 'no_host') {
7927: $response = &reply('autorun:'.$cdom,$homeserver);
7928: }
1.876 raeburn 7929: }
1.506 raeburn 7930: return $response;
7931: }
1.776 albertel 7932:
1.506 raeburn 7933: sub auto_get_sections {
1.508 raeburn 7934: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7935: my $homeserver;
7936: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7937: $homeserver = &homeserver($cnum,$cdom);
7938: }
7939: if (!defined($homeserver)) {
7940: if ($cdom =~ /^$match_domain$/) {
7941: $homeserver = &domain($cdom,'primary');
7942: }
7943: }
7944: my @secs;
7945: if (defined($homeserver)) {
7946: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7947: unless ($response eq 'refused') {
7948: @secs = split(/:/,$response);
7949: }
1.506 raeburn 7950: }
7951: return @secs;
7952: }
1.776 albertel 7953:
1.506 raeburn 7954: sub auto_new_course {
1.1099 raeburn 7955: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7956: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7957: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7958: return $response;
7959: }
1.776 albertel 7960:
1.506 raeburn 7961: sub auto_validate_courseID {
1.508 raeburn 7962: my ($cnum,$cdom,$inst_course_id) = @_;
7963: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7964: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7965: return $response;
7966: }
1.776 albertel 7967:
1.1007 raeburn 7968: sub auto_validate_instcode {
1.1020 raeburn 7969: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7970: my ($homeserver,$response);
7971: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7972: $homeserver = &homeserver($cnum,$cdom);
7973: }
7974: if (!defined($homeserver)) {
7975: if ($cdom =~ /^$match_domain$/) {
7976: $homeserver = &domain($cdom,'primary');
7977: }
7978: }
1.1065 raeburn 7979: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7980: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7981: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7982: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7983: }
7984:
1.506 raeburn 7985: sub auto_create_password {
1.873 raeburn 7986: my ($cnum,$cdom,$authparam,$udom) = @_;
7987: my ($homeserver,$response);
1.506 raeburn 7988: my $create_passwd = 0;
7989: my $authchk = '';
1.873 raeburn 7990: if ($udom =~ /^$match_domain$/) {
7991: $homeserver = &domain($udom,'primary');
7992: }
7993: if ($homeserver eq '') {
7994: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7995: $homeserver = &homeserver($cnum,$cdom);
7996: }
7997: }
7998: if ($homeserver eq '') {
7999: $authchk = 'nodomain';
1.506 raeburn 8000: } else {
1.873 raeburn 8001: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8002: if ($response eq 'refused') {
8003: $authchk = 'refused';
8004: } else {
1.901 albertel 8005: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8006: }
1.506 raeburn 8007: }
8008: return ($authparam,$create_passwd,$authchk);
8009: }
8010:
1.706 raeburn 8011: sub auto_photo_permission {
8012: my ($cnum,$cdom,$students) = @_;
8013: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8014: my ($outcome,$perm_reqd,$conditions) =
8015: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8016: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8017: return (undef,undef);
8018: }
1.706 raeburn 8019: return ($outcome,$perm_reqd,$conditions);
8020: }
8021:
8022: sub auto_checkphotos {
8023: my ($uname,$udom,$pid) = @_;
8024: my $homeserver = &homeserver($uname,$udom);
8025: my ($result,$resulttype);
8026: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8027: &escape($uname).':'.&escape($pid),
8028: $homeserver));
1.709 albertel 8029: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8030: return (undef,undef);
8031: }
1.706 raeburn 8032: if ($outcome) {
8033: ($result,$resulttype) = split(/:/,$outcome);
8034: }
8035: return ($result,$resulttype);
8036: }
8037:
8038: sub auto_photochoice {
8039: my ($cnum,$cdom) = @_;
8040: my $homeserver = &homeserver($cnum,$cdom);
8041: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8042: &escape($cdom),
8043: $homeserver)));
1.709 albertel 8044: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8045: return (undef,undef);
8046: }
1.706 raeburn 8047: return ($update,$comment);
8048: }
8049:
8050: sub auto_photoupdate {
8051: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8052: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8053: my $host=&hostname($homeserver);
1.706 raeburn 8054: my $cmd = '';
8055: my $maxtries = 1;
1.800 albertel 8056: foreach my $affiliate (keys(%{$affiliatesref})) {
8057: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8058: }
8059: $cmd =~ s/%%$//;
8060: $cmd = &escape($cmd);
8061: my $query = 'institutionalphotos';
8062: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8063: unless ($queryid=~/^\Q$host\E\_/) {
8064: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8065: return 'error: '.$queryid;
8066: }
8067: my $reply = &get_query_reply($queryid);
8068: my $tries = 1;
8069: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8070: $reply = &get_query_reply($queryid);
8071: $tries ++;
8072: }
8073: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8074: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8075: } else {
8076: my @responses = split(/:/,$reply);
8077: my $outcome = shift(@responses);
8078: foreach my $item (@responses) {
8079: my ($key,$value) = split(/=/,$item);
8080: $$photo{$key} = $value;
8081: }
8082: return $outcome;
8083: }
8084: return 'error';
8085: }
8086:
1.521 raeburn 8087: sub auto_instcode_format {
1.793 albertel 8088: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8089: $cat_order) = @_;
1.521 raeburn 8090: my $courses = '';
1.772 raeburn 8091: my @homeservers;
1.521 raeburn 8092: if ($caller eq 'global') {
1.841 albertel 8093: my %servers = &get_servers($codedom,'library');
8094: foreach my $tryserver (keys(%servers)) {
8095: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8096: push(@homeservers,$tryserver);
8097: }
1.584 raeburn 8098: }
1.1022 raeburn 8099: } elsif ($caller eq 'requests') {
8100: if ($codedom =~ /^$match_domain$/) {
8101: my $chome = &domain($codedom,'primary');
8102: unless ($chome eq 'no_host') {
8103: push(@homeservers,$chome);
8104: }
8105: }
1.521 raeburn 8106: } else {
1.772 raeburn 8107: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8108: }
1.793 albertel 8109: foreach my $code (keys(%{$instcodes})) {
8110: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8111: }
8112: chop($courses);
1.772 raeburn 8113: my $ok_response = 0;
8114: my $response;
8115: while (@homeservers > 0 && $ok_response == 0) {
8116: my $server = shift(@homeservers);
8117: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8118: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8119: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8120: split(/:/,$response);
1.772 raeburn 8121: %{$codes} = (%{$codes},&str2hash($codes_str));
8122: push(@{$codetitles},&str2array($codetitles_str));
8123: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8124: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8125: $ok_response = 1;
8126: }
8127: }
8128: if ($ok_response) {
1.521 raeburn 8129: return 'ok';
1.772 raeburn 8130: } else {
8131: return $response;
1.521 raeburn 8132: }
8133: }
8134:
1.792 raeburn 8135: sub auto_instcode_defaults {
8136: my ($domain,$returnhash,$code_order) = @_;
8137: my @homeservers;
1.841 albertel 8138:
8139: my %servers = &get_servers($domain,'library');
8140: foreach my $tryserver (keys(%servers)) {
8141: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8142: push(@homeservers,$tryserver);
8143: }
1.792 raeburn 8144: }
1.841 albertel 8145:
1.792 raeburn 8146: my $response;
1.841 albertel 8147: foreach my $server (@homeservers) {
1.792 raeburn 8148: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8149: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8150:
8151: foreach my $pair (split(/\&/,$response)) {
8152: my ($name,$value)=split(/\=/,$pair);
8153: if ($name eq 'code_order') {
8154: @{$code_order} = split(/\&/,&unescape($value));
8155: } else {
8156: $returnhash->{&unescape($name)}=&unescape($value);
8157: }
8158: }
8159: return 'ok';
1.792 raeburn 8160: }
1.841 albertel 8161:
8162: return $response;
1.1003 raeburn 8163: }
8164:
8165: sub auto_possible_instcodes {
1.1007 raeburn 8166: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8167: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8168: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8169: return;
8170: }
1.1003 raeburn 8171: my (@homeservers,$uhome);
8172: if (defined(&domain($domain,'primary'))) {
8173: $uhome=&domain($domain,'primary');
8174: push(@homeservers,&domain($domain,'primary'));
8175: } else {
8176: my %servers = &get_servers($domain,'library');
8177: foreach my $tryserver (keys(%servers)) {
8178: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8179: push(@homeservers,$tryserver);
8180: }
8181: }
8182: }
8183: my $response;
8184: foreach my $server (@homeservers) {
8185: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8186: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8187: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8188: split(':',$response);
8189: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8190: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8191: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8192: my ($name,$value)=split('=',$item);
8193: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8194: }
8195: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8196: my ($name,$value)=split('=',$item);
8197: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8198: }
8199: return 'ok';
8200: }
8201: return $response;
8202: }
1.792 raeburn 8203:
1.1010 raeburn 8204: sub auto_courserequest_checks {
8205: my ($dom) = @_;
1.1020 raeburn 8206: my ($homeserver,%validations);
8207: if ($dom =~ /^$match_domain$/) {
8208: $homeserver = &domain($dom,'primary');
8209: }
8210: unless ($homeserver eq 'no_host') {
8211: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8212: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8213: my @items = split(/&/,$response);
8214: foreach my $item (@items) {
8215: my ($key,$value) = split('=',$item);
8216: $validations{&unescape($key)} = &thaw_unescape($value);
8217: }
8218: }
8219: }
1.1010 raeburn 8220: return %validations;
8221: }
8222:
1.1020 raeburn 8223: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8224: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8225: my ($homeserver,$response);
8226: if ($dom =~ /^$match_domain$/) {
8227: $homeserver = &domain($dom,'primary');
8228: }
1.1172.2.43 raeburn 8229: unless ($homeserver eq 'no_host') {
8230: my $customdata;
8231: if (ref($custominfo) eq 'HASH') {
8232: $customdata = &freeze_escape($custominfo);
8233: }
1.1020 raeburn 8234: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8235: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8236: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8237: $customdata,$homeserver));
1.1020 raeburn 8238: }
8239: return $response;
8240: }
8241:
1.777 albertel 8242: sub auto_validate_class_sec {
1.918 raeburn 8243: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8244: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8245: my $ownerlist;
8246: if (ref($owners) eq 'ARRAY') {
8247: $ownerlist = join(',',@{$owners});
8248: } else {
8249: $ownerlist = $owners;
8250: }
1.773 raeburn 8251: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8252: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8253: return $response;
8254: }
8255:
1.1172.2.38 raeburn 8256: sub auto_crsreq_update {
8257: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8258: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8259: my ($homeserver,%crsreqresponse);
8260: if ($cdom =~ /^$match_domain$/) {
8261: $homeserver = &domain($cdom,'primary');
8262: }
8263: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8264: my $info;
8265: if (ref($inbound) eq 'HASH') {
8266: $info = &freeze_escape($inbound);
8267: }
8268: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8269: ':'.&escape($action).':'.&escape($ownername).':'.
8270: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8271: &escape($title).':'.&escape($code).':'.
8272: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8273: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8274: my @items = split(/&/,$response);
8275: foreach my $item (@items) {
8276: my ($key,$value) = split('=',$item);
8277: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8278: }
8279: }
8280: }
8281: return \%crsreqresponse;
8282: }
8283:
1.1172.2.78 raeburn 8284: sub auto_export_grades {
8285: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8286: my ($homeserver,%exportresponse);
8287: if ($cdom =~ /^$match_domain$/) {
8288: $homeserver = &domain($cdom,'primary');
8289: }
8290: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8291: my $info;
8292: if (ref($inforef) eq 'HASH') {
8293: $info = &freeze_escape($inforef);
8294: }
8295: if (ref($gradesref) eq 'HASH') {
8296: my $grades = &freeze_escape($gradesref);
8297: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8298: $info.':'.$grades,$homeserver);
8299: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8300: my @items = split(/&/,$response);
8301: foreach my $item (@items) {
8302: my ($key,$value) = split('=',$item);
8303: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8304: }
8305: }
8306: }
8307: }
8308: return \%exportresponse;
8309: }
8310:
1.1172.2.68 raeburn 8311: sub check_instcode_cloning {
8312: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8313: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8314: return;
8315: }
8316: my $canclone;
8317: if (@{$code_order} > 0) {
8318: my $instcoderegexp ='^';
8319: my @clonecodes = split(/\&/,$cloner);
8320: foreach my $item (@{$code_order}) {
8321: if (grep(/^\Q$item\E=/,@clonecodes)) {
8322: foreach my $pair (@clonecodes) {
8323: my ($key,$val) = split(/\=/,$pair,2);
8324: $val = &unescape($val);
8325: if ($key eq $item) {
8326: $instcoderegexp .= '('.$val.')';
8327: last;
8328: }
8329: }
8330: } else {
8331: $instcoderegexp .= $codedefaults->{$item};
8332: }
8333: }
8334: $instcoderegexp .= '$';
8335: my (@from,@to);
8336: eval {
8337: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8338: (@to) = ($clonetocode =~ /$instcoderegexp/);
8339: };
8340: if ((@from > 0) && (@to > 0)) {
8341: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8342: if (!@diffs) {
8343: $canclone = 1;
8344: }
8345: }
8346: }
8347: return $canclone;
8348: }
8349:
8350: sub default_instcode_cloning {
8351: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8352: my (%codedefaults,@code_order,$canclone);
8353: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8354: %codedefaults = %{$codedefaultsref};
8355: @code_order = @{$codeorderref};
8356: } elsif ($clonedom) {
8357: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8358: }
8359: if (($domdefclone) && (@code_order)) {
8360: my @clonecodes = split(/\+/,$domdefclone);
8361: my $instcoderegexp ='^';
8362: foreach my $item (@code_order) {
8363: if (grep(/^\Q$item\E$/,@clonecodes)) {
8364: $instcoderegexp .= '('.$codedefaults{$item}.')';
8365: } else {
8366: $instcoderegexp .= $codedefaults{$item};
8367: }
8368: }
8369: $instcoderegexp .= '$';
8370: my (@from,@to);
8371: eval {
8372: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8373: (@to) = ($clonetocode =~ /$instcoderegexp/);
8374: };
8375: if ((@from > 0) && (@to > 0)) {
8376: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8377: if (!@diffs) {
8378: $canclone = 1;
8379: }
8380: }
8381: }
8382: return $canclone;
8383: }
8384:
1.679 raeburn 8385: # ------------------------------------------------------- Course Group routines
8386:
8387: sub get_coursegroups {
1.809 raeburn 8388: my ($cdom,$cnum,$group,$namespace) = @_;
8389: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8390: }
8391:
1.679 raeburn 8392: sub modify_coursegroup {
8393: my ($cdom,$cnum,$groupsettings) = @_;
8394: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8395: }
8396:
1.809 raeburn 8397: sub toggle_coursegroup_status {
8398: my ($cdom,$cnum,$group,$action) = @_;
8399: my ($from_namespace,$to_namespace);
8400: if ($action eq 'delete') {
8401: $from_namespace = 'coursegroups';
8402: $to_namespace = 'deleted_groups';
8403: } else {
8404: $from_namespace = 'deleted_groups';
8405: $to_namespace = 'coursegroups';
8406: }
8407: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8408: if (my $tmp = &error(%curr_group)) {
8409: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8410: return ('read error',$tmp);
8411: } else {
8412: my %savedsettings = %curr_group;
1.809 raeburn 8413: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8414: my $deloutcome;
8415: if ($result eq 'ok') {
1.809 raeburn 8416: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8417: } else {
8418: return ('write error',$result);
8419: }
8420: if ($deloutcome eq 'ok') {
8421: return 'ok';
8422: } else {
8423: return ('delete error',$deloutcome);
8424: }
8425: }
8426: }
8427:
1.679 raeburn 8428: sub modify_group_roles {
1.957 raeburn 8429: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8430: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8431: my $role = 'gr/'.&escape($userprivs);
8432: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8433: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8434: if ($result eq 'ok') {
8435: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8436: }
1.679 raeburn 8437: return $result;
8438: }
8439:
8440: sub modify_coursegroup_membership {
8441: my ($cdom,$cnum,$membership) = @_;
8442: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8443: return $result;
8444: }
8445:
1.682 raeburn 8446: sub get_active_groups {
8447: my ($udom,$uname,$cdom,$cnum) = @_;
8448: my $now = time;
8449: my %groups = ();
8450: foreach my $key (keys(%env)) {
1.811 albertel 8451: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8452: my ($start,$end) = split(/\./,$env{$key});
8453: if (($end!=0) && ($end<$now)) { next; }
8454: if (($start!=0) && ($start>$now)) { next; }
8455: if ($1 eq $cdom && $2 eq $cnum) {
8456: $groups{$3} = $env{$key} ;
8457: }
8458: }
8459: }
8460: return %groups;
8461: }
8462:
1.683 raeburn 8463: sub get_group_membership {
8464: my ($cdom,$cnum,$group) = @_;
8465: return(&dump('groupmembership',$cdom,$cnum,$group));
8466: }
8467:
8468: sub get_users_groups {
8469: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8470: my @usersgroups;
1.683 raeburn 8471: my $cachetime=1800;
8472:
8473: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8474: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8475: if (defined($cached)) {
1.734 albertel 8476: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8477: } else {
8478: $grouplist = '';
1.816 raeburn 8479: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8480: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8481: my $access_end = $env{'course.'.$courseid.
8482: '.default_enrollment_end_date'};
8483: my $now = time;
8484: foreach my $key (keys(%roleshash)) {
8485: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8486: my $group = $1;
8487: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8488: my $start = $2;
8489: my $end = $1;
8490: if ($start == -1) { next; } # deleted from group
8491: if (($start!=0) && ($start>$now)) { next; }
8492: if (($end!=0) && ($end<$now)) {
8493: if ($access_end && $access_end < $now) {
8494: if ($access_end - $end < 86400) {
8495: push(@usersgroups,$group);
1.733 raeburn 8496: }
8497: }
1.817 raeburn 8498: next;
1.733 raeburn 8499: }
1.817 raeburn 8500: push(@usersgroups,$group);
1.683 raeburn 8501: }
8502: }
8503: }
1.817 raeburn 8504: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8505: $grouplist = join(':',@usersgroups);
8506: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8507: }
1.733 raeburn 8508: return @usersgroups;
1.683 raeburn 8509: }
8510:
8511: sub devalidate_getgroups_cache {
8512: my ($udom,$uname,$cdom,$cnum)=@_;
8513: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8514:
1.683 raeburn 8515: my $hashid="$udom:$uname:$courseid";
8516: &devalidate_cache_new('getgroups',$hashid);
8517: }
8518:
1.12 www 8519: # ------------------------------------------------------------------ Plain Text
8520:
8521: sub plaintext {
1.988 raeburn 8522: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8523: if ($short =~ m{^cr/}) {
1.758 albertel 8524: return (split('/',$short))[-1];
8525: }
1.742 raeburn 8526: if (!defined($cid)) {
8527: $cid = $env{'request.course.id'};
8528: }
8529: my %rolenames = (
1.1008 raeburn 8530: Course => 'std',
8531: Community => 'alt1',
1.742 raeburn 8532: );
1.1037 raeburn 8533: if ($cid ne '') {
8534: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8535: unless ($forcedefault) {
8536: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8537: &Apache::lonlocal::mt_escape(\$roletext);
8538: return &Apache::lonlocal::mt($roletext);
8539: }
8540: }
8541: }
8542: if ((defined($type)) && (defined($rolenames{$type})) &&
8543: (defined($rolenames{$type})) &&
8544: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8545: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8546: } elsif ($cid ne '') {
8547: my $crstype = $env{'course.'.$cid.'.type'};
8548: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8549: (defined($prp{$short}{$rolenames{$crstype}}))) {
8550: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8551: }
1.742 raeburn 8552: }
1.1037 raeburn 8553: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8554: }
8555:
8556: # ----------------------------------------------------------------- Assign Role
8557:
8558: sub assignrole {
1.957 raeburn 8559: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8560: $context)=@_;
1.21 www 8561: my $mrole;
8562: if ($role =~ /^cr\//) {
1.393 www 8563: my $cwosec=$url;
1.811 albertel 8564: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8565: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8566: my $refused = 1;
8567: if ($context eq 'requestcourses') {
8568: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8569: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8570: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8571: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8572: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8573: if ($crsenv{'internal.courseowner'} eq
8574: $env{'user.name'}.':'.$env{'user.domain'}) {
8575: $refused = '';
8576: }
8577: }
8578: }
8579: }
8580: }
8581: if ($refused) {
8582: &logthis('Refused custom assignrole: '.
8583: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8584: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8585: return 'refused';
8586: }
1.104 www 8587: }
1.21 www 8588: $mrole='cr';
1.678 raeburn 8589: } elsif ($role =~ /^gr\//) {
8590: my $cwogrp=$url;
1.811 albertel 8591: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8592: unless (&allowed('mdg',$cwogrp)) {
8593: &logthis('Refused group assignrole: '.
8594: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8595: $env{'user.name'}.' at '.$env{'user.domain'});
8596: return 'refused';
8597: }
8598: $mrole='gr';
1.21 www 8599: } else {
1.82 www 8600: my $cwosec=$url;
1.811 albertel 8601: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8602: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8603: my $refused;
8604: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8605: if (!(&allowed('c'.$role,$url))) {
8606: $refused = 1;
8607: }
8608: } else {
8609: $refused = 1;
8610: }
1.947 raeburn 8611: if ($refused) {
1.1045 raeburn 8612: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8613: if (!$selfenroll && $context eq 'course') {
8614: my %crsenv;
8615: if ($role eq 'cc' || $role eq 'co') {
8616: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8617: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8618: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8619: if ($crsenv{'internal.courseowner'} eq
8620: $env{'user.name'}.':'.$env{'user.domain'}) {
8621: $refused = '';
8622: }
8623: }
8624: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8625: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8626: if ($crsenv{'internal.courseowner'} eq
8627: $env{'user.name'}.':'.$env{'user.domain'}) {
8628: $refused = '';
8629: }
8630: }
8631: }
8632: }
8633: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8634: $refused = '';
1.1017 raeburn 8635: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8636: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8637: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8638: my $wrongcc;
8639: if ($cnum =~ /^$match_community$/) {
8640: $wrongcc = 1 if ($role eq 'cc');
8641: } else {
8642: $wrongcc = 1 if ($role eq 'co');
8643: }
8644: unless ($wrongcc) {
8645: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8646: if ($crsenv{'internal.courseowner'} eq
8647: $env{'user.name'}.':'.$env{'user.domain'}) {
8648: $refused = '';
8649: }
1.1017 raeburn 8650: }
8651: }
1.1172.2.9 raeburn 8652: } elsif ($context eq 'requestauthor') {
8653: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8654: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8655: if ($env{'environment.requestauthor'} eq 'automatic') {
8656: $refused = '';
8657: } else {
8658: my %domdefaults = &get_domain_defaults($udom);
8659: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8660: my $checkbystatus;
8661: if ($env{'user.adv'}) {
8662: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8663: if ($disposition eq 'automatic') {
8664: $refused = '';
8665: } elsif ($disposition eq '') {
8666: $checkbystatus = 1;
8667: }
8668: } else {
8669: $checkbystatus = 1;
8670: }
8671: if ($checkbystatus) {
8672: if ($env{'environment.inststatus'}) {
8673: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8674: foreach my $type (@inststatuses) {
8675: if (($type ne '') &&
8676: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8677: $refused = '';
8678: }
8679: }
8680: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8681: $refused = '';
8682: }
8683: }
8684: }
8685: }
8686: }
1.1017 raeburn 8687: }
8688: if ($refused) {
1.947 raeburn 8689: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8690: ' '.$role.' '.$end.' '.$start.' by '.
8691: $env{'user.name'}.' at '.$env{'user.domain'});
8692: return 'refused';
8693: }
1.932 raeburn 8694: }
1.1131 raeburn 8695: } elsif ($role eq 'au') {
8696: if ($url ne '/'.$udom.'/') {
8697: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8698: ' to assign author role for '.$uname.':'.$udom.
8699: ' in domain: '.$url.' refused (wrong domain).');
8700: return 'refused';
8701: }
1.104 www 8702: }
1.21 www 8703: $mrole=$role;
8704: }
1.620 albertel 8705: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8706: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8707: if ($end) { $command.='_'.$end; }
1.21 www 8708: if ($start) {
8709: if ($end) {
1.81 www 8710: $command.='_'.$start;
1.21 www 8711: } else {
1.81 www 8712: $command.='_0_'.$start;
1.21 www 8713: }
8714: }
1.739 raeburn 8715: my $origstart = $start;
8716: my $origend = $end;
1.957 raeburn 8717: my $delflag;
1.357 www 8718: # actually delete
8719: if ($deleteflag) {
1.373 www 8720: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8721: # modify command to delete the role
1.620 albertel 8722: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8723: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8724: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8725: # set start and finish to negative values for userrolelog
8726: $start=-1;
8727: $end=-1;
1.957 raeburn 8728: $delflag = 1;
1.357 www 8729: }
8730: }
8731: # send command
1.349 www 8732: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8733: # log new user role if status is ok
1.349 www 8734: if ($answer eq 'ok') {
1.663 raeburn 8735: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8736: if (($role eq 'cc') || ($role eq 'in') ||
8737: ($role eq 'ep') || ($role eq 'ad') ||
8738: ($role eq 'ta') || ($role eq 'st') ||
8739: ($role=~/^cr/) || ($role eq 'gr') ||
8740: ($role eq 'co')) {
1.1172.2.13 raeburn 8741: # for course roles, perform group memberships changes triggered by role change.
8742: unless ($role =~ /^gr/) {
8743: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8744: $origstart,$selfenroll,$context);
8745: }
1.1172.2.9 raeburn 8746: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8747: $selfenroll,$context);
8748: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.84! raeburn 8749: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1172.2.9 raeburn 8750: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8751: $context);
8752: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8753: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8754: $context);
8755: }
1.1053 raeburn 8756: if ($role eq 'cc') {
8757: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8758: }
1.349 www 8759: }
8760: return $answer;
1.169 harris41 8761: }
8762:
1.1053 raeburn 8763: sub autoupdate_coowners {
8764: my ($url,$end,$start,$uname,$udom) = @_;
8765: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8766: if (($cdom ne '') && ($cnum ne '')) {
8767: my $now = time;
8768: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8769: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8770: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8771: my $instcode = $coursehash{'internal.coursecode'};
8772: if ($instcode ne '') {
1.1056 raeburn 8773: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8774: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8775: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8776: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8777: if ($result eq 'valid') {
8778: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8779: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8780: push(@newcoowners,$coowner);
8781: }
8782: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8783: push(@newcoowners,$uname.':'.$udom);
8784: }
8785: @newcoowners = sort(@newcoowners);
8786: } else {
8787: push(@newcoowners,$uname.':'.$udom);
8788: }
8789: } else {
8790: if ($coursehash{'internal.co-owners'}) {
8791: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8792: unless ($coowner eq $uname.':'.$udom) {
8793: push(@newcoowners,$coowner);
8794: }
8795: }
8796: unless (@newcoowners > 0) {
8797: $delcoowners = 1;
8798: $coowners = '';
8799: }
8800: }
8801: }
8802: if (@newcoowners || $delcoowners) {
8803: &store_coowners($cdom,$cnum,$coursehash{'home'},
8804: $delcoowners,@newcoowners);
8805: }
8806: }
8807: }
8808: }
8809: }
8810: }
8811: }
8812:
8813: sub store_coowners {
8814: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8815: my $cid = $cdom.'_'.$cnum;
8816: my ($coowners,$delresult,$putresult);
8817: if (@newcoowners) {
8818: $coowners = join(',',@newcoowners);
8819: my %coownershash = (
8820: 'internal.co-owners' => $coowners,
8821: );
8822: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8823: if ($putresult eq 'ok') {
8824: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8825: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8826: }
8827: }
8828: }
8829: if ($delcoowners) {
8830: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8831: if ($delresult eq 'ok') {
8832: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8833: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8834: }
8835: }
8836: }
8837: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8838: my %crsinfo =
8839: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8840: if (ref($crsinfo{$cid}) eq 'HASH') {
8841: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8842: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8843: }
8844: }
8845: }
8846:
1.169 harris41 8847: # -------------------------------------------------- Modify user authentication
1.197 www 8848: # Overrides without validation
8849:
1.169 harris41 8850: sub modifyuserauth {
8851: my ($udom,$uname,$umode,$upass)=@_;
8852: my $uhome=&homeserver($uname,$udom);
1.197 www 8853: unless (&allowed('mau',$udom)) { return 'refused'; }
8854: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8855: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8856: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8857: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8858: &escape($upass),$uhome);
1.620 albertel 8859: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8860: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8861: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8862: &log($udom,,$uname,$uhome,
1.620 albertel 8863: 'Authentication changed by '.$env{'user.domain'}.', '.
8864: $env{'user.name'}.', '.$umode.
1.197 www 8865: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8866: unless ($reply eq 'ok') {
1.197 www 8867: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8868: return 'error: '.$reply;
8869: }
1.170 harris41 8870: return 'ok';
1.80 www 8871: }
8872:
1.81 www 8873: # --------------------------------------------------------------- Modify a user
1.80 www 8874:
1.81 www 8875: sub modifyuser {
1.206 matthew 8876: my ($udom, $uname, $uid,
8877: $umode, $upass, $first,
8878: $middle, $last, $gene,
1.1058 raeburn 8879: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8880: $udom= &LONCAPA::clean_domain($udom);
8881: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8882: my $showcandelete = 'none';
8883: if (ref($candelete) eq 'ARRAY') {
8884: if (@{$candelete} > 0) {
8885: $showcandelete = join(', ',@{$candelete});
8886: }
8887: }
1.81 www 8888: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8889: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8890: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8891: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8892: ' desiredhome not specified').
1.620 albertel 8893: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8894: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8895: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8896: my $newuser;
8897: if ($uhome eq 'no_host') {
8898: $newuser = 1;
8899: }
1.80 www 8900: # ----------------------------------------------------------------- Create User
1.406 albertel 8901: if (($uhome eq 'no_host') &&
8902: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8903: my $unhome='';
1.844 albertel 8904: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8905: $unhome = $desiredhome;
1.620 albertel 8906: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8907: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8908: } else { # load balancing routine for determining $unhome
1.81 www 8909: my $loadm=10000000;
1.841 albertel 8910: my %servers = &get_servers($udom,'library');
8911: foreach my $tryserver (keys(%servers)) {
8912: my $answer=reply('load',$tryserver);
8913: if (($answer=~/\d+/) && ($answer<$loadm)) {
8914: $loadm=$answer;
8915: $unhome=$tryserver;
8916: }
1.80 www 8917: }
8918: }
8919: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8920: return 'error: unable to find a home server for '.$uname.
8921: ' in domain '.$udom;
1.80 www 8922: }
8923: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8924: &escape($upass),$unhome);
8925: unless ($reply eq 'ok') {
8926: return 'error: '.$reply;
8927: }
1.230 stredwic 8928: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8929: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8930: return 'error: unable verify users home machine.';
1.80 www 8931: }
1.209 matthew 8932: } # End of creation of new user
1.80 www 8933: # ---------------------------------------------------------------------- Add ID
8934: if ($uid) {
8935: $uid=~tr/A-Z/a-z/;
8936: my %uidhash=&idrget($udom,$uname);
1.196 www 8937: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8938: && (!$forceid)) {
1.80 www 8939: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8940: return 'error: user id "'.$uid.'" does not match '.
8941: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8942: }
8943: } else {
8944: &idput($udom,($uname => $uid));
8945: }
8946: }
8947: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8948: my @tmp=&get('environment',
1.899 raeburn 8949: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8950: 'permanentemail','inststatus'],
1.134 albertel 8951: $udom,$uname);
1.1075 raeburn 8952: my (%names,%oldnames);
1.313 matthew 8953: if ($tmp[0] =~ m/^error:.*/) {
8954: %names=();
8955: } else {
8956: %names = @tmp;
1.1075 raeburn 8957: %oldnames = %names;
1.313 matthew 8958: }
1.388 www 8959: #
1.1058 raeburn 8960: # If name, email and/or uid are blank (e.g., because an uploaded file
8961: # of users did not contain them), do not overwrite existing values
8962: # unless field is in $candelete array ref.
8963: #
8964:
8965: my @fields = ('firstname','middlename','lastname','generation',
8966: 'permanentemail','id');
8967: my %newvalues;
8968: if (ref($candelete) eq 'ARRAY') {
8969: foreach my $field (@fields) {
8970: if (grep(/^\Q$field\E$/,@{$candelete})) {
8971: if ($field eq 'firstname') {
8972: $names{$field} = $first;
8973: } elsif ($field eq 'middlename') {
8974: $names{$field} = $middle;
8975: } elsif ($field eq 'lastname') {
8976: $names{$field} = $last;
8977: } elsif ($field eq 'generation') {
8978: $names{$field} = $gene;
8979: } elsif ($field eq 'permanentemail') {
8980: $names{$field} = $email;
8981: } elsif ($field eq 'id') {
8982: $names{$field} = $uid;
8983: }
8984: }
8985: }
8986: }
1.388 www 8987: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8988: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8989: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8990: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8991: if ($email) {
8992: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8993: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8994: }
1.899 raeburn 8995: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8996: if (defined($inststatus)) {
8997: $names{'inststatus'} = '';
8998: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8999: if (ref($usertypes) eq 'HASH') {
9000: my @okstatuses;
9001: foreach my $item (split(/:/,$inststatus)) {
9002: if (defined($usertypes->{$item})) {
9003: push(@okstatuses,$item);
9004: }
9005: }
9006: if (@okstatuses) {
9007: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9008: }
9009: }
9010: }
1.1075 raeburn 9011: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9012: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9013: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9014: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9015: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9016: } else {
9017: $logmsg .= ' during self creation';
9018: }
1.1075 raeburn 9019: my $changed;
9020: if ($newuser) {
9021: $changed = 1;
9022: } else {
9023: foreach my $field (@fields) {
9024: if ($names{$field} ne $oldnames{$field}) {
9025: $changed = 1;
9026: last;
9027: }
9028: }
9029: }
9030: unless ($changed) {
9031: $logmsg = 'No changes in user information needed for: '.$logmsg;
9032: &logthis($logmsg);
9033: return 'ok';
9034: }
9035: my $reply = &put('environment', \%names, $udom,$uname);
9036: if ($reply ne 'ok') {
9037: return 'error: '.$reply;
9038: }
1.1087 raeburn 9039: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9040: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9041: }
1.1075 raeburn 9042: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9043: &devalidate_cache_new('namescache',$uname.':'.$udom);
9044: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9045: &logthis($logmsg);
1.134 albertel 9046: return 'ok';
1.80 www 9047: }
9048:
1.81 www 9049: # -------------------------------------------------------------- Modify student
1.80 www 9050:
1.81 www 9051: sub modifystudent {
9052: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9053: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9054: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9055: if (!$cid) {
1.620 albertel 9056: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9057: return 'not_in_class';
9058: }
1.80 www 9059: }
9060: # --------------------------------------------------------------- Make the user
1.81 www 9061: my $reply=&modifyuser
1.209 matthew 9062: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9063: $desiredhome,$email,$inststatus);
1.80 www 9064: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9065: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9066: # student's environment
1.297 matthew 9067: $uid = undef if (!$forceid);
1.455 albertel 9068: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9069: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9070: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9071: return $reply;
9072: }
9073:
9074: sub modify_student_enrollment {
1.1172.2.23 raeburn 9075: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9076: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9077: my ($cdom,$cnum,$chome);
9078: if (!$cid) {
1.620 albertel 9079: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9080: return 'not_in_class';
9081: }
1.620 albertel 9082: $cdom=$env{'course.'.$cid.'.domain'};
9083: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9084: } else {
9085: ($cdom,$cnum)=split(/_/,$cid);
9086: }
1.620 albertel 9087: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9088: if (!$chome) {
1.457 raeburn 9089: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9090: }
1.455 albertel 9091: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9092: # Make sure the user exists
1.81 www 9093: my $uhome=&homeserver($uname,$udom);
9094: if (($uhome eq '') || ($uhome eq 'no_host')) {
9095: return 'error: no such user';
9096: }
1.297 matthew 9097: # Get student data if we were not given enough information
9098: if (!defined($first) || $first eq '' ||
9099: !defined($last) || $last eq '' ||
9100: !defined($uid) || $uid eq '' ||
9101: !defined($middle) || $middle eq '' ||
9102: !defined($gene) || $gene eq '') {
1.294 matthew 9103: # They did not supply us with enough data to enroll the student, so
9104: # we need to pick up more information.
1.297 matthew 9105: my %tmp = &get('environment',
1.294 matthew 9106: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9107: ,$udom,$uname);
9108:
1.800 albertel 9109: #foreach my $key (keys(%tmp)) {
9110: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9111: #}
1.294 matthew 9112: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9113: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9114: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9115: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9116: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9117: }
1.556 albertel 9118: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9119: my $user = "$uname:$udom";
9120: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9121: my $reply=cput('classlist',
1.1148 raeburn 9122: {$user =>
1.1172.2.76 raeburn 9123: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9124: $cdom,$cnum);
1.1148 raeburn 9125: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9126: &devalidate_getsection_cache($udom,$uname,$cid);
9127: } else {
1.81 www 9128: return 'error: '.$reply;
9129: }
1.297 matthew 9130: # Add student role to user
1.83 www 9131: my $uurl='/'.$cid;
1.81 www 9132: $uurl=~s/\_/\//g;
9133: if ($usec) {
9134: $uurl.='/'.$usec;
9135: }
1.1148 raeburn 9136: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9137: $selfenroll,$context);
9138: if ($result ne 'ok') {
9139: if ($old_entry{$user} ne '') {
9140: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9141: } else {
9142: $reply = &del('classlist',[$user],$cdom,$cnum);
9143: }
9144: }
9145: return $result;
1.21 www 9146: }
9147:
1.556 albertel 9148: sub format_name {
9149: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9150: my $name;
9151: if ($first ne 'lastname') {
9152: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9153: } else {
9154: if ($lastname=~/\S/) {
9155: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9156: $name=~s/\s+,/,/;
9157: } else {
9158: $name.= $firstname.' '.$middlename.' '.$generation;
9159: }
9160: }
9161: $name=~s/^\s+//;
9162: $name=~s/\s+$//;
9163: $name=~s/\s+/ /g;
9164: return $name;
9165: }
9166:
1.84 www 9167: # ------------------------------------------------- Write to course preferences
9168:
9169: sub writecoursepref {
9170: my ($courseid,%prefs)=@_;
9171: $courseid=~s/^\///;
9172: $courseid=~s/\_/\//g;
9173: my ($cdomain,$cnum)=split(/\//,$courseid);
9174: my $chome=homeserver($cnum,$cdomain);
9175: if (($chome eq '') || ($chome eq 'no_host')) {
9176: return 'error: no such course';
9177: }
9178: my $cstring='';
1.800 albertel 9179: foreach my $pref (keys(%prefs)) {
9180: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9181: }
1.84 www 9182: $cstring=~s/\&$//;
9183: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9184: }
9185:
9186: # ---------------------------------------------------------- Make/modify course
9187:
9188: sub createcourse {
1.741 raeburn 9189: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9190: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9191: $url=&declutter($url);
9192: my $cid='';
1.1028 raeburn 9193: if ($context eq 'requestcourses') {
9194: my $can_create = 0;
9195: my ($ownername,$ownerdom) = split(':',$course_owner);
9196: if ($udom eq $ownerdom) {
9197: if (&usertools_access($ownername,$ownerdom,$category,undef,
9198: $context)) {
9199: $can_create = 1;
9200: }
9201: } else {
9202: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9203: $category);
9204: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9205: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9206: if (@curr > 0) {
9207: my @options = qw(approval validate autolimit);
9208: my $optregex = join('|',@options);
9209: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9210: $can_create = 1;
9211: }
9212: }
9213: }
9214: }
9215: if ($can_create) {
9216: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9217: unless (&allowed('ccc',$udom)) {
9218: return 'refused';
9219: }
1.1017 raeburn 9220: }
9221: } else {
9222: return 'refused';
9223: }
1.1028 raeburn 9224: } elsif (!&allowed('ccc',$udom)) {
9225: return 'refused';
1.84 www 9226: }
1.1011 raeburn 9227: # --------------------------------------------------------------- Get Unique ID
9228: my $uname;
9229: if ($cnum =~ /^$match_courseid$/) {
9230: my $chome=&homeserver($cnum,$udom,'true');
9231: if (($chome eq '') || ($chome eq 'no_host')) {
9232: $uname = $cnum;
9233: } else {
1.1038 raeburn 9234: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9235: }
9236: } else {
1.1038 raeburn 9237: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9238: }
9239: return $uname if ($uname =~ /^error/);
9240: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9241: if (!defined($course_server)) {
9242: if (defined(&domain($udom,'primary'))) {
9243: $course_server = &domain($udom,'primary');
9244: } else {
9245: $course_server = $env{'user.home'};
9246: }
9247: }
9248: my %host_servers =
9249: &Apache::lonnet::get_servers($udom,'library');
9250: unless ($host_servers{$course_server}) {
9251: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9252: }
1.84 www 9253: # ------------------------------------------------------------- Make the course
9254: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9255: $course_server);
1.84 www 9256: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9257: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9258: if (($uhome eq '') || ($uhome eq 'no_host')) {
9259: return 'error: no such course';
9260: }
1.271 www 9261: # ----------------------------------------------------------------- Course made
1.516 raeburn 9262: # log existence
1.1029 raeburn 9263: my $now = time;
1.918 raeburn 9264: my $newcourse = {
9265: $udom.'_'.$uname => {
1.921 raeburn 9266: description => $description,
9267: inst_code => $inst_code,
9268: owner => $course_owner,
9269: type => $crstype,
1.1029 raeburn 9270: creator => $env{'user.name'}.':'.
9271: $env{'user.domain'},
9272: created => $now,
9273: context => $context,
1.918 raeburn 9274: },
9275: };
1.921 raeburn 9276: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9277: # set toplevel url
1.271 www 9278: my $topurl=$url;
9279: unless ($nonstandard) {
9280: # ------------------------------------------ For standard courses, make top url
9281: my $mapurl=&clutter($url);
1.278 www 9282: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9283: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9284: <map>
9285: <resource id="1" type="start"></resource>
9286: <resource id="2" src="$mapurl"></resource>
9287: <resource id="3" type="finish"></resource>
9288: <link index="1" from="1" to="2"></link>
9289: <link index="2" from="2" to="3"></link>
9290: </map>
9291: ENDINITMAP
9292: $topurl=&declutter(
1.638 albertel 9293: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9294: );
9295: }
9296: # ----------------------------------------------------------- Write preferences
1.84 www 9297: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9298: ('description' => $description,
9299: 'url' => $topurl,
9300: 'internal.creator' => $env{'user.name'}.':'.
9301: $env{'user.domain'},
9302: 'internal.created' => $now,
9303: 'internal.creationcontext' => $context)
9304: );
1.84 www 9305: return '/'.$udom.'/'.$uname;
9306: }
9307:
1.1011 raeburn 9308: # ------------------------------------------------------------------- Create ID
9309: sub generate_coursenum {
1.1038 raeburn 9310: my ($udom,$crstype) = @_;
1.1011 raeburn 9311: my $domdesc = &domain($udom);
9312: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9313: my $first;
9314: if ($crstype eq 'Community') {
9315: $first = '0';
9316: } else {
9317: $first = int(1+rand(9));
9318: }
9319: my $uname=$first.
1.1011 raeburn 9320: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9321: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9322: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9323: # ----------------------------------------------- Make sure that does not exist
9324: my $uhome=&homeserver($uname,$udom,'true');
9325: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9326: if ($crstype eq 'Community') {
9327: $first = '0';
9328: } else {
9329: $first = int(1+rand(9));
9330: }
9331: $uname=$first.
1.1011 raeburn 9332: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9333: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9334: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9335: $uhome=&homeserver($uname,$udom,'true');
9336: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9337: return 'error: unable to generate unique course-ID';
9338: }
9339: }
9340: return $uname;
9341: }
9342:
1.813 albertel 9343: sub is_course {
1.1167 droeschl 9344: my ($cdom, $cnum) = scalar(@_) == 1 ?
9345: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9346:
9347: return unless $cdom and $cnum;
9348:
9349: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9350: '.');
9351:
1.1172.2.23 raeburn 9352: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9353: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9354: }
9355:
1.1015 raeburn 9356: sub store_userdata {
9357: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9358: my $result;
1.1016 raeburn 9359: if ($datakey ne '') {
1.1013 raeburn 9360: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9361: if ($udom eq '' || $uname eq '') {
9362: $udom = $env{'user.domain'};
9363: $uname = $env{'user.name'};
9364: }
9365: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9366: if (($uhome eq '') || ($uhome eq 'no_host')) {
9367: $result = 'error: no_host';
9368: } else {
9369: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9370: $storehash->{'host'} = $perlvar{'lonHostID'};
9371:
9372: my $namevalue='';
9373: foreach my $key (keys(%{$storehash})) {
9374: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9375: }
9376: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9377: unless ($namespace eq 'courserequests') {
9378: $datakey = &escape($datakey);
9379: }
1.1105 raeburn 9380: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9381: $namevalue,$uhome);
1.1013 raeburn 9382: }
9383: } else {
9384: $result = 'error: data to store was not a hash reference';
9385: }
9386: } else {
9387: $result= 'error: invalid requestkey';
9388: }
9389: return $result;
9390: }
9391:
1.21 www 9392: # ---------------------------------------------------------- Assign Custom Role
9393:
9394: sub assigncustomrole {
1.957 raeburn 9395: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9396: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9397: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9398: }
9399:
9400: # ----------------------------------------------------------------- Revoke Role
9401:
9402: sub revokerole {
1.957 raeburn 9403: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9404: my $now=time;
1.965 raeburn 9405: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9406: }
9407:
9408: # ---------------------------------------------------------- Revoke Custom Role
9409:
9410: sub revokecustomrole {
1.957 raeburn 9411: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9412: my $now=time;
1.357 www 9413: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9414: $deleteflag,$selfenroll,$context);
1.17 www 9415: }
9416:
1.533 banghart 9417: # ------------------------------------------------------------ Disk usage
1.535 albertel 9418: sub diskusage {
1.955 raeburn 9419: my ($udom,$uname,$directorypath,$getpropath)=@_;
9420: $directorypath =~ s/\/$//;
9421: my $listing=&reply('du2:'.&escape($directorypath).':'
9422: .&escape($getpropath).':'.&escape($uname).':'
9423: .&escape($udom),homeserver($uname,$udom));
9424: if ($listing eq 'unknown_cmd') {
9425: if ($getpropath) {
9426: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9427: }
9428: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9429: }
1.514 albertel 9430: return $listing;
1.512 banghart 9431: }
9432:
1.566 banghart 9433: sub is_locked {
1.1096 raeburn 9434: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9435: my @check;
9436: my $is_locked;
1.1093 raeburn 9437: push (@check,$file_name);
1.613 albertel 9438: my %locked = &get('file_permissions',\@check,
1.620 albertel 9439: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9440: my ($tmp)=keys(%locked);
9441: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9442:
1.566 banghart 9443: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9444: $is_locked = 'false';
9445: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9446: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9447: $is_locked = 'true';
1.1096 raeburn 9448: if (ref($which) eq 'ARRAY') {
9449: push(@{$which},$entry);
9450: } else {
9451: last;
9452: }
1.745 raeburn 9453: }
9454: }
1.566 banghart 9455: } else {
9456: $is_locked = 'false';
9457: }
1.1093 raeburn 9458: return $is_locked;
1.566 banghart 9459: }
9460:
1.759 albertel 9461: sub declutter_portfile {
9462: my ($file) = @_;
1.833 albertel 9463: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9464: return $file;
9465: }
9466:
1.559 banghart 9467: # ------------------------------------------------------------- Mark as Read Only
9468:
9469: sub mark_as_readonly {
9470: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9471: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9472: my ($tmp)=keys(%current_permissions);
9473: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9474: foreach my $file (@{$files}) {
1.759 albertel 9475: $file = &declutter_portfile($file);
1.561 banghart 9476: push(@{$current_permissions{$file}},$what);
1.559 banghart 9477: }
1.613 albertel 9478: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9479: return;
9480: }
9481:
1.572 banghart 9482: # ------------------------------------------------------------Save Selected Files
9483:
9484: sub save_selected_files {
9485: my ($user, $path, @files) = @_;
9486: my $filename = $user."savedfiles";
1.573 banghart 9487: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9488: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9489: foreach my $file (@files) {
1.620 albertel 9490: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9491: }
9492: foreach my $file (@other_files) {
1.574 banghart 9493: print (OUT $file."\n");
1.572 banghart 9494: }
1.574 banghart 9495: close (OUT);
1.572 banghart 9496: return 'ok';
9497: }
9498:
1.574 banghart 9499: sub clear_selected_files {
9500: my ($user) = @_;
9501: my $filename = $user."savedfiles";
1.1117 foxr 9502: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9503: print (OUT undef);
9504: close (OUT);
9505: return ("ok");
9506: }
9507:
1.572 banghart 9508: sub files_in_path {
9509: my ($user, $path) = @_;
9510: my $filename = $user."savedfiles";
9511: my %return_files;
1.1117 foxr 9512: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9513: while (my $line_in = <IN>) {
1.574 banghart 9514: chomp ($line_in);
9515: my @paths_and_file = split (m!/!, $line_in);
9516: my $file_part = pop (@paths_and_file);
9517: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9518: $path_part.='/';
9519: my $path_and_file = $path_part.$file_part;
9520: if ($path_part eq $path) {
9521: $return_files{$file_part}= 'selected';
9522: }
9523: }
1.574 banghart 9524: close (IN);
9525: return (\%return_files);
1.572 banghart 9526: }
9527:
9528: # called in portfolio select mode, to show files selected NOT in current directory
9529: sub files_not_in_path {
9530: my ($user, $path) = @_;
9531: my $filename = $user."savedfiles";
9532: my @return_files;
9533: my $path_part;
1.1117 foxr 9534: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9535: while (my $line = <IN>) {
1.572 banghart 9536: #ok, I know it's clunky, but I want it to work
1.800 albertel 9537: my @paths_and_file = split(m|/|, $line);
9538: my $file_part = pop(@paths_and_file);
9539: chomp($file_part);
9540: my $path_part = join('/', @paths_and_file);
1.572 banghart 9541: $path_part .= '/';
9542: my $path_and_file = $path_part.$file_part;
9543: if ($path_part ne $path) {
1.800 albertel 9544: push(@return_files, ($path_and_file));
1.572 banghart 9545: }
9546: }
1.800 albertel 9547: close(OUT);
1.574 banghart 9548: return (@return_files);
1.572 banghart 9549: }
9550:
1.745 raeburn 9551: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9552:
1.745 raeburn 9553: sub get_portfile_permissions {
9554: my ($domain,$user) = @_;
1.613 albertel 9555: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9556: my ($tmp)=keys(%current_permissions);
9557: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9558: return \%current_permissions;
9559: }
9560:
9561: #---------------------------------------------Get portfolio file access controls
9562:
1.749 raeburn 9563: sub get_access_controls {
1.745 raeburn 9564: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9565: my %access;
9566: my $real_file = $file;
9567: $file =~ s/\.meta$//;
1.745 raeburn 9568: if (defined($file)) {
1.749 raeburn 9569: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9570: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9571: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9572: }
9573: }
1.745 raeburn 9574: } else {
1.749 raeburn 9575: foreach my $key (keys(%{$current_permissions})) {
9576: if ($key =~ /\0accesscontrol$/) {
9577: if (defined($group)) {
9578: if ($key !~ m-^\Q$group\E/-) {
9579: next;
9580: }
9581: }
9582: my ($fullpath) = split(/\0/,$key);
9583: if (ref($$current_permissions{$key}) eq 'HASH') {
9584: foreach my $control (keys(%{$$current_permissions{$key}})) {
9585: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9586: }
9587: }
9588: }
9589: }
9590: }
9591: return %access;
9592: }
9593:
9594: sub modify_access_controls {
9595: my ($file_name,$changes,$domain,$user)=@_;
9596: my ($outcome,$deloutcome);
9597: my %store_permissions;
9598: my %new_values;
9599: my %new_control;
9600: my %translation;
9601: my @deletions = ();
9602: my $now = time;
9603: if (exists($$changes{'activate'})) {
9604: if (ref($$changes{'activate'}) eq 'HASH') {
9605: my @newitems = sort(keys(%{$$changes{'activate'}}));
9606: my $numnew = scalar(@newitems);
9607: for (my $i=0; $i<$numnew; $i++) {
9608: my $newkey = $newitems[$i];
9609: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9610: if ($newkey =~ /^\d+:/) {
9611: $newkey =~ s/^(\d+)/$newid/;
9612: $translation{$1} = $newid;
9613: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9614: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9615: $translation{$1} = $newid;
9616: }
1.749 raeburn 9617: $new_values{$file_name."\0".$newkey} =
9618: $$changes{'activate'}{$newitems[$i]};
9619: $new_control{$newkey} = $now;
9620: }
9621: }
9622: }
9623: my %todelete;
9624: my %changed_items;
9625: foreach my $action ('delete','update') {
9626: if (exists($$changes{$action})) {
9627: if (ref($$changes{$action}) eq 'HASH') {
9628: foreach my $key (keys(%{$$changes{$action}})) {
9629: my ($itemnum) = ($key =~ /^([^:]+):/);
9630: if ($action eq 'delete') {
9631: $todelete{$itemnum} = 1;
9632: } else {
9633: $changed_items{$itemnum} = $key;
9634: }
9635: }
1.745 raeburn 9636: }
9637: }
1.749 raeburn 9638: }
9639: # get lock on access controls for file.
9640: my $lockhash = {
9641: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9642: ':'.$env{'user.domain'},
9643: };
9644: my $tries = 0;
9645: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9646:
1.1172.2.79 raeburn 9647: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9648: $tries ++;
1.1172.2.79 raeburn 9649: sleep(0.1);
1.749 raeburn 9650: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9651: }
9652: if ($gotlock eq 'ok') {
9653: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9654: my ($tmp)=keys(%curr_permissions);
9655: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9656: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9657: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9658: if (ref($curr_controls) eq 'HASH') {
9659: foreach my $control_item (keys(%{$curr_controls})) {
9660: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9661: if (defined($todelete{$itemnum})) {
9662: push(@deletions,$file_name."\0".$control_item);
9663: } else {
9664: if (defined($changed_items{$itemnum})) {
9665: $new_control{$changed_items{$itemnum}} = $now;
9666: push(@deletions,$file_name."\0".$control_item);
9667: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9668: } else {
9669: $new_control{$control_item} = $$curr_controls{$control_item};
9670: }
9671: }
1.745 raeburn 9672: }
9673: }
9674: }
1.970 raeburn 9675: my ($group);
9676: if (&is_course($domain,$user)) {
9677: ($group,my $file) = split(/\//,$file_name,2);
9678: }
1.749 raeburn 9679: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9680: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9681: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9682: # remove lock
9683: my @del_lock = ($file_name."\0".'locked_access_records');
9684: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9685: my $sqlresult =
1.970 raeburn 9686: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9687: $group);
1.749 raeburn 9688: } else {
9689: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9690: }
1.749 raeburn 9691: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9692: }
9693:
1.827 raeburn 9694: sub make_public_indefinitely {
9695: my ($requrl) = @_;
9696: my $now = time;
9697: my $action = 'activate';
9698: my $aclnum = 0;
9699: if (&is_portfolio_url($requrl)) {
9700: my (undef,$udom,$unum,$file_name,$group) =
9701: &parse_portfolio_url($requrl);
9702: my $current_perms = &get_portfile_permissions($udom,$unum);
9703: my %access_controls = &get_access_controls($current_perms,
9704: $group,$file_name);
9705: foreach my $key (keys(%{$access_controls{$file_name}})) {
9706: my ($num,$scope,$end,$start) =
9707: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9708: if ($scope eq 'public') {
9709: if ($start <= $now && $end == 0) {
9710: $action = 'none';
9711: } else {
9712: $action = 'update';
9713: $aclnum = $num;
9714: }
9715: last;
9716: }
9717: }
9718: if ($action eq 'none') {
9719: return 'ok';
9720: } else {
9721: my %changes;
9722: my $newend = 0;
9723: my $newstart = $now;
9724: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9725: $changes{$action}{$newkey} = {
9726: type => 'public',
9727: time => {
9728: start => $newstart,
9729: end => $newend,
9730: },
9731: };
9732: my ($outcome,$deloutcome,$new_values,$translation) =
9733: &modify_access_controls($file_name,\%changes,$udom,$unum);
9734: return $outcome;
9735: }
9736: } else {
9737: return 'invalid';
9738: }
9739: }
9740:
1.745 raeburn 9741: #------------------------------------------------------Get Marked as Read Only
9742:
9743: sub get_marked_as_readonly {
9744: my ($domain,$user,$what,$group) = @_;
9745: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9746: my @readonly_files;
1.629 banghart 9747: my $cmp1=$what;
9748: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9749: while (my ($file_name,$value) = each(%{$current_permissions})) {
9750: if (defined($group)) {
9751: if ($file_name !~ m-^\Q$group\E/-) {
9752: next;
9753: }
9754: }
1.561 banghart 9755: if (ref($value) eq "ARRAY"){
9756: foreach my $stored_what (@{$value}) {
1.629 banghart 9757: my $cmp2=$stored_what;
1.759 albertel 9758: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9759: $cmp2=join('',@{$stored_what});
1.745 raeburn 9760: }
1.629 banghart 9761: if ($cmp1 eq $cmp2) {
1.561 banghart 9762: push(@readonly_files, $file_name);
1.745 raeburn 9763: last;
1.563 banghart 9764: } elsif (!defined($what)) {
9765: push(@readonly_files, $file_name);
1.745 raeburn 9766: last;
1.561 banghart 9767: }
9768: }
1.745 raeburn 9769: }
1.561 banghart 9770: }
9771: return @readonly_files;
9772: }
1.577 banghart 9773: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9774:
1.577 banghart 9775: sub get_marked_as_readonly_hash {
1.745 raeburn 9776: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9777: my %readonly_files;
1.745 raeburn 9778: while (my ($file_name,$value) = each(%{$current_permissions})) {
9779: if (defined($group)) {
9780: if ($file_name !~ m-^\Q$group\E/-) {
9781: next;
9782: }
9783: }
1.577 banghart 9784: if (ref($value) eq "ARRAY"){
9785: foreach my $stored_what (@{$value}) {
1.745 raeburn 9786: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9787: foreach my $lock_descriptor(@{$stored_what}) {
9788: if ($lock_descriptor eq 'graded') {
9789: $readonly_files{$file_name} = 'graded';
9790: } elsif ($lock_descriptor eq 'handback') {
9791: $readonly_files{$file_name} = 'handback';
9792: } else {
9793: if (!exists($readonly_files{$file_name})) {
9794: $readonly_files{$file_name} = 'locked';
9795: }
9796: }
1.745 raeburn 9797: }
1.750 banghart 9798: }
1.577 banghart 9799: }
9800: }
9801: }
9802: return %readonly_files;
9803: }
1.559 banghart 9804: # ------------------------------------------------------------ Unmark as Read Only
9805:
9806: sub unmark_as_readonly {
1.629 banghart 9807: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9808: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9809: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9810: $file_name = &declutter_portfile($file_name);
1.634 albertel 9811: my $symb_crs = $what;
9812: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9813: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9814: my ($tmp)=keys(%current_permissions);
9815: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9816: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9817: foreach my $file (@readonly_files) {
1.759 albertel 9818: my $clean_file = &declutter_portfile($file);
9819: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9820: my $current_locks = $current_permissions{$file};
1.563 banghart 9821: my @new_locks;
9822: my @del_keys;
9823: if (ref($current_locks) eq "ARRAY"){
9824: foreach my $locker (@{$current_locks}) {
1.632 albertel 9825: my $compare=$locker;
1.749 raeburn 9826: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9827: $compare=join('',@{$locker});
1.746 raeburn 9828: if ($compare ne $symb_crs) {
9829: push(@new_locks, $locker);
9830: }
1.563 banghart 9831: }
9832: }
1.650 albertel 9833: if (scalar(@new_locks) > 0) {
1.563 banghart 9834: $current_permissions{$file} = \@new_locks;
9835: } else {
9836: push(@del_keys, $file);
1.613 albertel 9837: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9838: delete($current_permissions{$file});
1.563 banghart 9839: }
9840: }
1.561 banghart 9841: }
1.613 albertel 9842: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9843: return;
9844: }
1.512 banghart 9845:
1.17 www 9846: # ------------------------------------------------------------ Directory lister
9847:
9848: sub dirlist {
1.955 raeburn 9849: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9850: $uri=~s/^\///;
9851: $uri=~s/\/$//;
1.253 stredwic 9852: my ($udom, $uname);
1.955 raeburn 9853: if ($getuserdir) {
1.253 stredwic 9854: $udom = $userdomain;
9855: $uname = $username;
1.955 raeburn 9856: } else {
9857: (undef,$udom,$uname)=split(/\//,$uri);
9858: if(defined($userdomain)) {
9859: $udom = $userdomain;
9860: }
9861: if(defined($username)) {
9862: $uname = $username;
9863: }
1.253 stredwic 9864: }
1.955 raeburn 9865: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9866:
1.955 raeburn 9867: $dirRoot = $perlvar{'lonDocRoot'};
9868: if (defined($getpropath)) {
9869: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9870: $dirRoot =~ s/\/$//;
1.955 raeburn 9871: } elsif (defined($getuserdir)) {
9872: my $subdir=$uname.'__';
9873: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9874: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9875: ."/$udom/$subdir/$uname";
9876: } elsif (defined($alternateRoot)) {
9877: $dirRoot = $alternateRoot;
1.751 banghart 9878: }
1.253 stredwic 9879:
9880: if($udom) {
9881: if($uname) {
1.1135 raeburn 9882: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9883: if ($uhome eq 'no_host') {
9884: return ([],'no_host');
9885: }
1.955 raeburn 9886: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9887: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9888: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9889: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9890: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9891: } else {
9892: @listing_results = map { &unescape($_); } split(/:/,$listing);
9893: }
1.605 matthew 9894: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9895: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9896: @listing_results = split(/:/,$listing);
9897: } else {
9898: @listing_results = map { &unescape($_); } split(/:/,$listing);
9899: }
1.1135 raeburn 9900: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9901: ($listing eq 'rejected') || ($listing eq 'refused') ||
9902: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9903: return ([],$listing);
9904: } else {
9905: return (\@listing_results);
1.1135 raeburn 9906: }
1.955 raeburn 9907: } elsif(!$alternateRoot) {
1.1136 raeburn 9908: my (%allusers,%listerror);
1.841 albertel 9909: my %servers = &get_servers($udom,'library');
1.955 raeburn 9910: foreach my $tryserver (keys(%servers)) {
9911: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9912: &escape($udom),$tryserver);
9913: if ($listing eq 'unknown_cmd') {
9914: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9915: $udom, $tryserver);
9916: } else {
9917: @listing_results = map { &unescape($_); } split(/:/,$listing);
9918: }
1.841 albertel 9919: if ($listing eq 'unknown_cmd') {
9920: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9921: $udom, $tryserver);
9922: @listing_results = split(/:/,$listing);
9923: } else {
9924: @listing_results =
9925: map { &unescape($_); } split(/:/,$listing);
9926: }
1.1136 raeburn 9927: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9928: ($listing eq 'rejected') || ($listing eq 'refused') ||
9929: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9930: $listerror{$tryserver} = $listing;
9931: } else {
1.841 albertel 9932: foreach my $line (@listing_results) {
9933: my ($entry) = split(/&/,$line,2);
9934: $allusers{$entry} = 1;
9935: }
9936: }
1.253 stredwic 9937: }
1.1136 raeburn 9938: my @alluserslist=();
1.800 albertel 9939: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9940: push(@alluserslist,$user.'&user');
1.253 stredwic 9941: }
1.1172.2.80 raeburn 9942: if (!%listerror) {
9943: # no errors
9944: return (\@alluserslist);
9945: } elsif (scalar(keys(%servers)) == 1) {
9946: # one library server, one error
9947: my ($key) = keys(%listerror);
9948: return (\@alluserslist, $listerror{$key});
9949: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
9950: # con_lost indicates that we might miss data from at least one
9951: # library server
9952: return (\@alluserslist, 'con_lost');
9953: } else {
9954: # multiple library servers and no con_lost -> data should be
9955: # complete.
9956: return (\@alluserslist);
9957: }
9958:
1.253 stredwic 9959: } else {
1.1136 raeburn 9960: return ([],'missing username');
1.253 stredwic 9961: }
1.955 raeburn 9962: } elsif(!defined($getpropath)) {
1.1136 raeburn 9963: my $path = $perlvar{'lonDocRoot'}.'/res/';
9964: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9965: return (\@all_domains);
1.955 raeburn 9966: } else {
1.1136 raeburn 9967: return ([],'missing domain');
1.275 stredwic 9968: }
9969: }
9970:
9971: # --------------------------------------------- GetFileTimestamp
9972: # This function utilizes dirlist and returns the date stamp for
9973: # when it was last modified. It will also return an error of -1
9974: # if an error occurs
9975:
9976: sub GetFileTimestamp {
1.955 raeburn 9977: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9978: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9979: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9980: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9981: undef,$getuserdir);
9982: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9983: return -1;
9984: }
9985: if (ref($fileref) eq 'ARRAY') {
9986: my @stats = split('&',$fileref->[0]);
1.375 matthew 9987: # @stats contains first the filename, then the stat output
9988: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9989: } else {
9990: return -1;
1.253 stredwic 9991: }
1.26 www 9992: }
9993:
1.712 albertel 9994: sub stat_file {
9995: my ($uri) = @_;
1.787 albertel 9996: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9997:
1.955 raeburn 9998: my ($udom,$uname,$file);
1.712 albertel 9999: if ($uri =~ m-^/(uploaded|editupload)/-) {
10000: ($udom,$uname,$file) =
1.811 albertel 10001: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10002: $file = 'userfiles/'.$file;
10003: }
10004: if ($uri =~ m-^/res/-) {
10005: ($udom,$uname) =
1.807 albertel 10006: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10007: $file = $uri;
10008: }
10009:
10010: if (!$udom || !$uname || !$file) {
10011: # unable to handle the uri
10012: return ();
10013: }
1.956 raeburn 10014: my $getpropath;
10015: if ($file =~ /^userfiles\//) {
10016: $getpropath = 1;
10017: }
1.1136 raeburn 10018: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10019: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10020: return ();
10021: } else {
10022: if (ref($listref) eq 'ARRAY') {
10023: my @stats = split('&',$listref->[0]);
10024: shift(@stats); #filename is first
10025: return @stats;
10026: }
1.712 albertel 10027: }
10028: return ();
10029: }
10030:
1.26 www 10031: # -------------------------------------------------------- Value of a Condition
10032:
1.713 albertel 10033: # gets the value of a specific preevaluated condition
10034: # stored in the string $env{user.state.<cid>}
10035: # or looks up a condition reference in the bighash and if if hasn't
10036: # already been evaluated recurses into docondval to get the value of
10037: # the condition, then memoizing it to
10038: # $env{user.state.<cid>.<condition>}
1.40 www 10039: sub directcondval {
10040: my $number=shift;
1.620 albertel 10041: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10042: &Apache::lonuserstate::evalstate();
10043: }
1.713 albertel 10044: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10045: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10046: } elsif ($number =~ /^_/) {
10047: my $sub_condition;
10048: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10049: &GDBM_READER(),0640)) {
10050: $sub_condition=$bighash{'conditions'.$number};
10051: untie(%bighash);
10052: }
10053: my $value = &docondval($sub_condition);
1.949 raeburn 10054: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10055: return $value;
10056: }
1.620 albertel 10057: if ($env{'user.state.'.$env{'request.course.id'}}) {
10058: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10059: } else {
10060: return 2;
10061: }
10062: }
10063:
1.713 albertel 10064: # get the collection of conditions for this resource
1.26 www 10065: sub condval {
10066: my $condidx=shift;
1.54 www 10067: my $allpathcond='';
1.713 albertel 10068: foreach my $cond (split(/\|/,$condidx)) {
10069: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10070: $allpathcond.=
10071: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10072: }
1.191 harris41 10073: }
1.54 www 10074: $allpathcond=~s/\|$//;
1.713 albertel 10075: return &docondval($allpathcond);
10076: }
10077:
10078: #evaluates an expression of conditions
10079: sub docondval {
10080: my ($allpathcond) = @_;
10081: my $result=0;
10082: if ($env{'request.course.id'}
10083: && defined($allpathcond)) {
10084: my $operand='|';
10085: my @stack;
10086: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10087: if ($chunk eq '(') {
10088: push @stack,($operand,$result);
10089: } elsif ($chunk eq ')') {
10090: my $before=pop @stack;
10091: if (pop @stack eq '&') {
10092: $result=$result>$before?$before:$result;
10093: } else {
10094: $result=$result>$before?$result:$before;
10095: }
10096: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10097: $operand=$chunk;
10098: } else {
10099: my $new=directcondval($chunk);
10100: if ($operand eq '&') {
10101: $result=$result>$new?$new:$result;
10102: } else {
10103: $result=$result>$new?$result:$new;
10104: }
10105: }
10106: }
1.26 www 10107: }
10108: return $result;
1.421 albertel 10109: }
10110:
10111: # ---------------------------------------------------- Devalidate courseresdata
10112:
10113: sub devalidatecourseresdata {
10114: my ($coursenum,$coursedomain)=@_;
10115: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10116: &devalidate_cache_new('courseres',$hashid);
1.28 www 10117: }
10118:
1.763 www 10119:
1.200 www 10120: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10121: #
10122: # Parameters:
10123: # $coursenum - Number of the course.
10124: # $coursedomain - Domain at which the course was created.
10125: # Returns:
10126: # A hash of the course parameters along (I think) with timestamps
10127: # and version info.
1.877 foxr 10128:
1.624 albertel 10129: sub get_courseresdata {
10130: my ($coursenum,$coursedomain)=@_;
1.200 www 10131: my $coursehom=&homeserver($coursenum,$coursedomain);
10132: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10133: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10134: my %dumpreply;
1.417 albertel 10135: unless (defined($cached)) {
1.624 albertel 10136: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10137: $result=\%dumpreply;
1.251 albertel 10138: my ($tmp) = keys(%dumpreply);
10139: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10140: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10141: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10142: return $tmp;
1.416 albertel 10143: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10144: $result=undef;
1.599 albertel 10145: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10146: }
10147: }
1.624 albertel 10148: return $result;
10149: }
10150:
1.633 albertel 10151: sub devalidateuserresdata {
10152: my ($uname,$udom)=@_;
10153: my $hashid="$udom:$uname";
10154: &devalidate_cache_new('userres',$hashid);
10155: }
10156:
1.624 albertel 10157: sub get_userresdata {
10158: my ($uname,$udom)=@_;
10159: #most student don\'t have any data set, check if there is some data
10160: if (&EXT_cache_status($udom,$uname)) { return undef; }
10161:
10162: my $hashid="$udom:$uname";
10163: my ($result,$cached)=&is_cached_new('userres',$hashid);
10164: if (!defined($cached)) {
10165: my %resourcedata=&dump('resourcedata',$udom,$uname);
10166: $result=\%resourcedata;
10167: &do_cache_new('userres',$hashid,$result,600);
10168: }
10169: my ($tmp)=keys(%$result);
10170: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10171: return $result;
10172: }
10173: #error 2 occurs when the .db doesn't exist
10174: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10175: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10176: &logthis("<font color=\"blue\">WARNING:".
10177: " Trying to get resource data for ".
10178: $uname." at ".$udom.": ".
10179: $tmp."</font>");
10180: }
1.624 albertel 10181: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10182: #&EXT_cache_set($udom,$uname);
10183: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10184: undef($tmp); # not really an error so don't send it back
1.624 albertel 10185: }
10186: return $tmp;
10187: }
1.879 foxr 10188: #----------------------------------------------- resdata - return resource data
10189: # Purpose:
10190: # Return resource data for either users or for a course.
10191: # Parameters:
10192: # $name - Course/user name.
10193: # $domain - Name of the domain the user/course is registered on.
10194: # $type - Type of thing $name is (must be 'course' or 'user'
10195: # @which - Array of names of resources desired.
10196: # Returns:
10197: # The value of the first reasource in @which that is found in the
10198: # resource hash.
10199: # Exceptional Conditions:
10200: # If the $type passed in is not valid (not the string 'course' or
10201: # 'user', an undefined reference is returned.
10202: # If none of the resources are found, an undef is returned
1.624 albertel 10203: sub resdata {
10204: my ($name,$domain,$type,@which)=@_;
10205: my $result;
10206: if ($type eq 'course') {
10207: $result=&get_courseresdata($name,$domain);
10208: } elsif ($type eq 'user') {
10209: $result=&get_userresdata($name,$domain);
10210: }
10211: if (!ref($result)) { return $result; }
1.251 albertel 10212: foreach my $item (@which) {
1.927 albertel 10213: if (defined($result->{$item->[0]})) {
10214: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10215: }
1.250 albertel 10216: }
1.291 albertel 10217: return undef;
1.200 www 10218: }
10219:
1.1172.2.31 raeburn 10220: sub get_numsuppfiles {
10221: my ($cnum,$cdom,$ignorecache)=@_;
10222: my $hashid=$cnum.':'.$cdom;
10223: my ($suppcount,$cached);
10224: unless ($ignorecache) {
10225: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10226: }
10227: unless (defined($cached)) {
10228: my $chome=&homeserver($cnum,$cdom);
10229: unless ($chome eq 'no_host') {
10230: ($suppcount,my $errors) = (0,0);
10231: my $suppmap = 'supplemental.sequence';
10232: ($suppcount,$errors) =
10233: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10234: }
10235: &do_cache_new('suppcount',$hashid,$suppcount,600);
10236: }
10237: return $suppcount;
10238: }
10239:
1.379 matthew 10240: #
10241: # EXT resource caching routines
10242: #
10243:
10244: sub clear_EXT_cache_status {
1.383 albertel 10245: &delenv('cache.EXT.');
1.379 matthew 10246: }
10247:
10248: sub EXT_cache_status {
10249: my ($target_domain,$target_user) = @_;
1.383 albertel 10250: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10251: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10252: # We know already the user has no data
10253: return 1;
10254: } else {
10255: return 0;
10256: }
10257: }
10258:
10259: sub EXT_cache_set {
10260: my ($target_domain,$target_user) = @_;
1.383 albertel 10261: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10262: #&appenv({$cachename => time});
1.379 matthew 10263: }
10264:
1.28 www 10265: # --------------------------------------------------------- Value of a Variable
1.58 www 10266: sub EXT {
1.715 albertel 10267:
1.1172.2.28 raeburn 10268: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10269: unless ($varname) { return ''; }
1.218 albertel 10270: #get real user name/domain, courseid and symb
10271: my $courseid;
1.359 albertel 10272: my $publicuser;
1.427 www 10273: if ($symbparm) {
10274: $symbparm=&get_symb_from_alias($symbparm);
10275: }
1.218 albertel 10276: if (!($uname && $udom)) {
1.790 albertel 10277: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10278: if (!$symbparm) { $symbparm=$cursymb; }
10279: } else {
1.620 albertel 10280: $courseid=$env{'request.course.id'};
1.218 albertel 10281: }
1.48 www 10282: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10283: my $rest;
1.320 albertel 10284: if (defined($therest[0])) {
1.48 www 10285: $rest=join('.',@therest);
10286: } else {
10287: $rest='';
10288: }
1.320 albertel 10289:
1.57 www 10290: my $qualifierrest=$qualifier;
10291: if ($rest) { $qualifierrest.='.'.$rest; }
10292: my $spacequalifierrest=$space;
10293: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10294: if ($realm eq 'user') {
1.48 www 10295: # --------------------------------------------------------------- user.resource
10296: if ($space eq 'resource') {
1.651 albertel 10297: if ( (defined($Apache::lonhomework::parsing_a_problem)
10298: || defined($Apache::lonhomework::parsing_a_task))
10299: &&
1.744 albertel 10300: ($symbparm eq &symbread()) ) {
10301: # if we are in the middle of processing the resource the
10302: # get the value we are planning on committing
10303: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10304: return $Apache::lonhomework::results{$qualifierrest};
10305: } else {
10306: return $Apache::lonhomework::history{$qualifierrest};
10307: }
1.335 albertel 10308: } else {
1.359 albertel 10309: my %restored;
1.620 albertel 10310: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10311: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10312: } else {
10313: %restored=&restore($symbparm,$courseid,$udom,$uname);
10314: }
1.335 albertel 10315: return $restored{$qualifierrest};
10316: }
1.48 www 10317: # ----------------------------------------------------------------- user.access
10318: } elsif ($space eq 'access') {
1.218 albertel 10319: # FIXME - not supporting calls for a specific user
1.48 www 10320: return &allowed($qualifier,$rest);
10321: # ------------------------------------------ user.preferences, user.environment
10322: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10323: if (($uname eq $env{'user.name'}) &&
10324: ($udom eq $env{'user.domain'})) {
10325: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10326: } else {
1.359 albertel 10327: my %returnhash;
10328: if (!$publicuser) {
10329: %returnhash=&userenvironment($udom,$uname,
10330: $qualifierrest);
10331: }
1.218 albertel 10332: return $returnhash{$qualifierrest};
10333: }
1.48 www 10334: # ----------------------------------------------------------------- user.course
10335: } elsif ($space eq 'course') {
1.218 albertel 10336: # FIXME - not supporting calls for a specific user
1.620 albertel 10337: return $env{join('.',('request.course',$qualifier))};
1.48 www 10338: # ------------------------------------------------------------------- user.role
10339: } elsif ($space eq 'role') {
1.218 albertel 10340: # FIXME - not supporting calls for a specific user
1.620 albertel 10341: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10342: if ($qualifier eq 'value') {
10343: return $role;
10344: } elsif ($qualifier eq 'extent') {
10345: return $where;
10346: }
10347: # ----------------------------------------------------------------- user.domain
10348: } elsif ($space eq 'domain') {
1.218 albertel 10349: return $udom;
1.48 www 10350: # ------------------------------------------------------------------- user.name
10351: } elsif ($space eq 'name') {
1.218 albertel 10352: return $uname;
1.48 www 10353: # ---------------------------------------------------- Any other user namespace
1.29 www 10354: } else {
1.359 albertel 10355: my %reply;
10356: if (!$publicuser) {
10357: %reply=&get($space,[$qualifierrest],$udom,$uname);
10358: }
10359: return $reply{$qualifierrest};
1.48 www 10360: }
1.236 www 10361: } elsif ($realm eq 'query') {
10362: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10363: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10364: [$spacequalifierrest]);
1.620 albertel 10365: return $env{'form.'.$spacequalifierrest};
1.236 www 10366: } elsif ($realm eq 'request') {
1.48 www 10367: # ------------------------------------------------------------- request.browser
10368: if ($space eq 'browser') {
1.1145 bisitz 10369: return $env{'browser.'.$qualifier};
1.57 www 10370: # ------------------------------------------------------------ request.filename
10371: } else {
1.620 albertel 10372: return $env{'request.'.$spacequalifierrest};
1.29 www 10373: }
1.28 www 10374: } elsif ($realm eq 'course') {
1.48 www 10375: # ---------------------------------------------------------- course.description
1.620 albertel 10376: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10377: } elsif ($realm eq 'resource') {
1.165 www 10378:
1.620 albertel 10379: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10380: if (!$symbparm) { $symbparm=&symbread(); }
10381: }
1.693 albertel 10382:
1.1172.2.30 raeburn 10383: if ($qualifier eq '') {
10384: if ($space eq 'title') {
10385: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10386: return &gettitle($symbparm);
10387: }
1.693 albertel 10388:
1.1172.2.30 raeburn 10389: if ($space eq 'map') {
10390: my ($map) = &decode_symb($symbparm);
10391: return &symbread($map);
10392: }
10393: if ($space eq 'maptitle') {
10394: my ($map) = &decode_symb($symbparm);
10395: return &gettitle($map);
10396: }
10397: if ($space eq 'filename') {
10398: if ($symbparm) {
10399: return &clutter((&decode_symb($symbparm))[2]);
10400: }
10401: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10402: }
1.1172.2.30 raeburn 10403:
10404: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10405: if ($space eq 'visibleparts') {
10406: my $navmap = Apache::lonnavmaps::navmap->new();
10407: my $item;
10408: if (ref($navmap)) {
10409: my $res = $navmap->getBySymb($symbparm);
10410: my $parts = $res->parts();
10411: if (ref($parts) eq 'ARRAY') {
10412: $item = join(',',@{$parts});
10413: }
10414: undef($navmap);
10415: }
10416: return $item;
10417: }
10418: }
10419: }
1.693 albertel 10420:
10421: my ($section, $group, @groups);
1.593 albertel 10422: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10423: if (($courseid eq '') && ($cid)) {
10424: $courseid = $cid;
10425: }
10426: if (($symbparm && $courseid) &&
10427: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10428:
1.218 albertel 10429: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10430:
1.60 www 10431: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10432: my $symbp=$symbparm;
1.735 albertel 10433: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10434:
10435: my $symbparm=$symbp.'.'.$spacequalifierrest;
10436: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10437:
1.620 albertel 10438: if (($env{'user.name'} eq $uname) &&
10439: ($env{'user.domain'} eq $udom)) {
10440: $section=$env{'request.course.sec'};
1.733 raeburn 10441: @groups = split(/:/,$env{'request.course.groups'});
10442: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10443: } else {
1.539 albertel 10444: if (! defined($usection)) {
1.551 albertel 10445: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10446: } else {
10447: $section = $usection;
10448: }
1.733 raeburn 10449: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10450: }
10451:
10452: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10453: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10454: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10455:
1.593 albertel 10456: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10457: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10458: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10459:
1.60 www 10460: # ----------------------------------------------------------- first, check user
1.624 albertel 10461:
10462: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10463: ([$courselevelr,'resource'],
10464: [$courselevelm,'map' ],
10465: [$courselevel, 'course' ]));
1.931 albertel 10466: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10467:
1.594 albertel 10468: # ------------------------------------------------ second, check some of course
1.684 raeburn 10469: my $coursereply;
1.691 raeburn 10470: if (@groups > 0) {
10471: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10472: $mapparm,$spacequalifierrest);
1.927 albertel 10473: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10474: }
1.96 www 10475:
1.684 raeburn 10476: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10477: $env{'course.'.$courseid.'.domain'},
10478: 'course',
10479: ([$seclevelr, 'resource'],
10480: [$seclevelm, 'map' ],
10481: [$seclevel, 'course' ],
10482: [$courselevelr,'resource']));
10483: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10484:
1.60 www 10485: # ------------------------------------------------------ third, check map parms
1.218 albertel 10486: my %parmhash=();
10487: my $thisparm='';
10488: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10489: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10490: &GDBM_READER(),0640)) {
1.218 albertel 10491: $thisparm=$parmhash{$symbparm};
10492: untie(%parmhash);
10493: }
1.927 albertel 10494: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10495: }
1.594 albertel 10496: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10497:
1.218 albertel 10498: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10499: my $filename;
10500: if (!$symbparm) { $symbparm=&symbread(); }
10501: if ($symbparm) {
1.409 www 10502: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10503: } else {
1.620 albertel 10504: $filename=$env{'request.filename'};
1.282 albertel 10505: }
10506: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10507: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10508: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10509: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10510:
1.927 albertel 10511: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10512: if ($symbparm && defined($courseid) &&
1.620 albertel 10513: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10514: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10515: $env{'course.'.$courseid.'.domain'},
10516: 'course',
1.927 albertel 10517: ([$courselevelm,'map' ],
10518: [$courselevel, 'course']));
10519: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10520: }
1.145 www 10521: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10522: unless ($space eq '0') {
1.336 albertel 10523: my @parts=split(/_/,$space);
10524: my $id=pop(@parts);
10525: my $part=join('_',@parts);
10526: if ($part eq '') { $part='0'; }
1.927 albertel 10527: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10528: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10529: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10530: }
1.395 albertel 10531: if ($recurse) { return undef; }
10532: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10533: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10534: # ---------------------------------------------------- Any other user namespace
10535: } elsif ($realm eq 'environment') {
10536: # ----------------------------------------------------------------- environment
1.620 albertel 10537: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10538: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10539: } else {
1.770 albertel 10540: if ($uname eq 'anonymous' && $udom eq '') {
10541: return '';
10542: }
1.219 albertel 10543: my %returnhash=&userenvironment($udom,$uname,
10544: $spacequalifierrest);
10545: return $returnhash{$spacequalifierrest};
10546: }
1.28 www 10547: } elsif ($realm eq 'system') {
1.48 www 10548: # ----------------------------------------------------------------- system.time
10549: if ($space eq 'time') {
10550: return time;
10551: }
1.696 albertel 10552: } elsif ($realm eq 'server') {
10553: # ----------------------------------------------------------------- system.time
10554: if ($space eq 'name') {
10555: return $ENV{'SERVER_NAME'};
10556: }
1.28 www 10557: }
1.48 www 10558: return '';
1.61 www 10559: }
10560:
1.927 albertel 10561: sub get_reply {
10562: my ($reply_value) = @_;
1.940 raeburn 10563: if (ref($reply_value) eq 'ARRAY') {
10564: if (wantarray) {
10565: return @$reply_value;
10566: }
10567: return $reply_value->[0];
10568: } else {
10569: return $reply_value;
1.927 albertel 10570: }
10571: }
10572:
1.691 raeburn 10573: sub check_group_parms {
10574: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10575: my @groupitems = ();
10576: my $resultitem;
1.927 albertel 10577: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10578: foreach my $group (@{$groups}) {
10579: foreach my $level (@levels) {
1.927 albertel 10580: my $item = $courseid.'.['.$group.'].'.$level->[0];
10581: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10582: }
10583: }
10584: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10585: $env{'course.'.$courseid.'.domain'},
10586: 'course',@groupitems);
10587: return $coursereply;
10588: }
10589:
10590: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10591: my ($courseid,@groups) = @_;
10592: @groups = sort(@groups);
1.691 raeburn 10593: return @groups;
10594: }
10595:
1.395 albertel 10596: sub packages_tab_default {
10597: my ($uri,$varname)=@_;
10598: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10599:
10600: my (@extension,@specifics,$do_default);
10601: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10602: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10603: if ($pack_type eq 'default') {
10604: $do_default=1;
10605: } elsif ($pack_type eq 'extension') {
10606: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10607: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10608: # only look at packages defaults for packages that this id is
1.738 albertel 10609: push(@specifics,[$package,$pack_type,$pack_part]);
10610: }
10611: }
10612: # first look for a package that matches the requested part id
10613: foreach my $package (@specifics) {
10614: my (undef,$pack_type,$pack_part)=@{$package};
10615: next if ($pack_part ne $part);
10616: if (defined($packagetab{"$pack_type&$name&default"})) {
10617: return $packagetab{"$pack_type&$name&default"};
10618: }
10619: }
10620: # look for any possible matching non extension_ package
10621: foreach my $package (@specifics) {
10622: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10623: if (defined($packagetab{"$pack_type&$name&default"})) {
10624: return $packagetab{"$pack_type&$name&default"};
10625: }
1.585 albertel 10626: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10627: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10628: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10629: }
10630: }
1.738 albertel 10631: # look for any posible extension_ match
10632: foreach my $package (@extension) {
10633: my ($package,$pack_type)=@{$package};
10634: if (defined($packagetab{"$pack_type&$name&default"})) {
10635: return $packagetab{"$pack_type&$name&default"};
10636: }
10637: if (defined($packagetab{$package."&$name&default"})) {
10638: return $packagetab{$package."&$name&default"};
10639: }
10640: }
10641: # look for a global default setting
10642: if ($do_default && defined($packagetab{"default&$name&default"})) {
10643: return $packagetab{"default&$name&default"};
10644: }
1.395 albertel 10645: return undef;
10646: }
10647:
1.334 albertel 10648: sub add_prefix_and_part {
10649: my ($prefix,$part)=@_;
10650: my $keyroot;
10651: if (defined($prefix) && $prefix !~ /^__/) {
10652: # prefix that has a part already
10653: $keyroot=$prefix;
10654: } elsif (defined($prefix)) {
10655: # prefix that is missing a part
10656: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10657: } else {
10658: # no prefix at all
10659: if (defined($part)) { $keyroot='_'.$part; }
10660: }
10661: return $keyroot;
10662: }
10663:
1.71 www 10664: # ---------------------------------------------------------------- Get metadata
10665:
1.599 albertel 10666: my %metaentry;
1.1070 www 10667: my %importedpartids;
1.71 www 10668: sub metadata {
1.176 www 10669: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10670: $uri=&declutter($uri);
1.288 albertel 10671: # if it is a non metadata possible uri return quickly
1.529 albertel 10672: if (($uri eq '') ||
10673: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10674: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10675: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10676: return undef;
10677: }
1.1172.2.49 raeburn 10678: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10679: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10680: return undef;
1.288 albertel 10681: }
1.73 www 10682: my $filename=$uri;
10683: $uri=~s/\.meta$//;
1.172 www 10684: #
10685: # Is the metadata already cached?
1.177 www 10686: # Look at timestamp of caching
1.172 www 10687: # Everything is cached by the main uri, libraries are never directly cached
10688: #
1.428 albertel 10689: if (!defined($liburi)) {
1.599 albertel 10690: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10691: if (defined($cached)) { return $result->{':'.$what}; }
10692: }
10693: {
1.1069 www 10694: # Imported parts would go here
1.1070 www 10695: my %importedids=();
10696: my @origfileimportpartids=();
1.1069 www 10697: my $importedparts=0;
1.172 www 10698: #
10699: # Is this a recursive call for a library?
10700: #
1.599 albertel 10701: # if (! exists($metacache{$uri})) {
10702: # $metacache{$uri}={};
10703: # }
1.924 albertel 10704: my $cachetime = 60*60;
1.171 www 10705: if ($liburi) {
10706: $liburi=&declutter($liburi);
10707: $filename=$liburi;
1.401 bowersj2 10708: } else {
1.599 albertel 10709: &devalidate_cache_new('meta',$uri);
10710: undef(%metaentry);
1.401 bowersj2 10711: }
1.140 www 10712: my %metathesekeys=();
1.73 www 10713: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10714: my $metastring;
1.1140 www 10715: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10716: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10717: $metastring =
1.929 albertel 10718: &Apache::lonnet::ssi_body($which,
1.924 albertel 10719: ('grade_target' => 'meta'));
10720: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10721: } elsif (($uri !~ m -^(editupload)/-) &&
10722: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10723: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10724: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10725: $metastring=&getfile($file);
1.489 albertel 10726: }
1.208 albertel 10727: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10728: my $token;
1.140 www 10729: undef %metathesekeys;
1.71 www 10730: while ($token=$parser->get_token) {
1.339 albertel 10731: if ($token->[0] eq 'S') {
10732: if (defined($token->[2]->{'package'})) {
1.172 www 10733: #
10734: # This is a package - get package info
10735: #
1.339 albertel 10736: my $package=$token->[2]->{'package'};
10737: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10738: if (defined($token->[2]->{'id'})) {
10739: $keyroot.='_'.$token->[2]->{'id'};
10740: }
1.599 albertel 10741: if ($metaentry{':packages'}) {
10742: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10743: } else {
1.599 albertel 10744: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10745: }
1.736 albertel 10746: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10747: my $part=$keyroot;
10748: $part=~s/^\_//;
1.736 albertel 10749: if ($pack_entry=~/^\Q$package\E\&/ ||
10750: $pack_entry=~/^\Q$package\E_0\&/) {
10751: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10752: # ignore package.tab specified default values
10753: # here &package_tab_default() will fetch those
10754: if ($subp eq 'default') { next; }
1.736 albertel 10755: my $value=$packagetab{$pack_entry};
1.432 albertel 10756: my $unikey;
10757: if ($pack =~ /_0$/) {
10758: $unikey='parameter_0_'.$name;
10759: $part=0;
10760: } else {
10761: $unikey='parameter'.$keyroot.'_'.$name;
10762: }
1.339 albertel 10763: if ($subp eq 'display') {
10764: $value.=' [Part: '.$part.']';
10765: }
1.599 albertel 10766: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10767: $metathesekeys{$unikey}=1;
1.599 albertel 10768: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10769: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10770: }
1.599 albertel 10771: if (defined($metaentry{':'.$unikey.'.default'})) {
10772: $metaentry{':'.$unikey}=
10773: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10774: }
1.339 albertel 10775: }
10776: }
10777: } else {
1.172 www 10778: #
10779: # This is not a package - some other kind of start tag
1.339 albertel 10780: #
10781: my $entry=$token->[1];
1.1068 www 10782: my $unikey='';
1.175 www 10783:
1.339 albertel 10784: if ($entry eq 'import') {
1.175 www 10785: #
10786: # Importing a library here
1.339 albertel 10787: #
1.1067 www 10788: my $location=$parser->get_text('/import');
10789: my $dir=$filename;
10790: $dir=~s|[^/]*$||;
10791: $location=&filelocation($dir,$location);
1.1069 www 10792:
1.1068 www 10793: my $importmode=$token->[2]->{'importmode'};
10794: if ($importmode eq 'problem') {
1.1069 www 10795: # Import as problem/response
1.1068 www 10796: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10797: } elsif ($importmode eq 'part') {
10798: # Import as part(s)
1.1069 www 10799: $importedparts=1;
10800: # We need to get the original file and the imported file to get the part order correct
10801: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10802: # Load and inspect original file
1.1070 www 10803: if ($#origfileimportpartids<0) {
10804: undef(%importedpartids);
10805: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10806: my $origfile=&getfile($origfilelocation);
10807: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10808: }
10809:
1.1069 www 10810: # Load and inspect imported file
10811: my $impfile=&getfile($location);
10812: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10813: if ($#impfilepartids>=0) {
10814: # This problem had parts
1.1070 www 10815: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10816: } else {
10817: # Importing by turning a single problem into a problem part
10818: # It gets the import-tags ID as part-ID
10819: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10820: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10821: }
1.1068 www 10822: } else {
10823: # Normal import
10824: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10825: if (defined($token->[2]->{'id'})) {
10826: $unikey.='_'.$token->[2]->{'id'};
10827: }
1.1067 www 10828: }
10829:
1.339 albertel 10830: if ($depthcount<20) {
1.736 albertel 10831: my $metadata =
10832: &metadata($uri,'keys', $location,$unikey,
10833: $depthcount+1);
10834: foreach my $meta (split(',',$metadata)) {
10835: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10836: $metathesekeys{$meta}=1;
1.339 albertel 10837: }
1.1068 www 10838:
10839: }
1.1067 www 10840: } else {
10841: #
10842: # Not importing, some other kind of non-package, non-library start tag
10843: #
10844: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10845: if (defined($token->[2]->{'id'})) {
10846: $unikey.='_'.$token->[2]->{'id'};
10847: }
1.339 albertel 10848: if (defined($token->[2]->{'name'})) {
10849: $unikey.='_'.$token->[2]->{'name'};
10850: }
10851: $metathesekeys{$unikey}=1;
1.736 albertel 10852: foreach my $param (@{$token->[3]}) {
10853: $metaentry{':'.$unikey.'.'.$param} =
10854: $token->[2]->{$param};
1.339 albertel 10855: }
10856: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10857: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10858: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10859: # only ws inside the tag, and not in default, so use default
10860: # as value
1.599 albertel 10861: $metaentry{':'.$unikey}=$default;
1.908 albertel 10862: } elsif ( $internaltext =~ /\S/ ) {
10863: # something interesting inside the tag
10864: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10865: } else {
1.908 albertel 10866: # no interesting values, don't set a default
1.339 albertel 10867: }
1.172 www 10868: # end of not-a-package not-a-library import
1.339 albertel 10869: }
1.172 www 10870: # end of not-a-package start tag
1.339 albertel 10871: }
1.172 www 10872: # the next is the end of "start tag"
1.339 albertel 10873: }
10874: }
1.483 albertel 10875: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10876: $extension = lc($extension);
10877: if ($extension eq 'htm') { $extension='html'; }
10878:
1.737 albertel 10879: foreach my $key (keys(%packagetab)) {
1.483 albertel 10880: #no specific packages #how's our extension
10881: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10882: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10883: \%metathesekeys);
10884: }
1.883 albertel 10885:
10886: if (!exists($metaentry{':packages'})
10887: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10888: foreach my $key (keys(%packagetab)) {
1.483 albertel 10889: #no specific packages well let's get default then
10890: if ($key!~/^default&/) { next; }
1.488 albertel 10891: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10892: \%metathesekeys);
10893: }
10894: }
1.338 www 10895: # are there custom rights to evaluate
1.599 albertel 10896: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10897:
1.338 www 10898: #
10899: # Importing a rights file here
1.339 albertel 10900: #
10901: unless ($depthcount) {
1.599 albertel 10902: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10903: my $dir=$filename;
10904: $dir=~s|[^/]*$||;
10905: $location=&filelocation($dir,$location);
1.736 albertel 10906: my $rights_metadata =
10907: &metadata($uri,'keys',$location,'_rights',
10908: $depthcount+1);
10909: foreach my $rights (split(',',$rights_metadata)) {
10910: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10911: $metathesekeys{$rights}=1;
1.339 albertel 10912: }
10913: }
10914: }
1.737 albertel 10915: # uniqifiy package listing
10916: my %seen;
10917: my @uniq_packages =
10918: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10919: $metaentry{':packages'} = join(',',@uniq_packages);
10920:
1.1070 www 10921: if ($importedparts) {
10922: # We had imported parts and need to rebuild partorder
10923: $metaentry{':partorder'}='';
10924: $metathesekeys{'partorder'}=1;
10925: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10926: if ($origfileimportpartids[$index] eq 'part') {
10927: # original part, part of the problem
10928: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10929: } else {
10930: # we have imported parts at this position
10931: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10932: }
10933: }
10934: $metaentry{':partorder'}=~s/^\,//;
10935: }
10936:
1.737 albertel 10937: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10938: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10939: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10940: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10941: # this is the end of "was not already recently cached
1.71 www 10942: }
1.599 albertel 10943: return $metaentry{':'.$what};
1.261 albertel 10944: }
10945:
1.488 albertel 10946: sub metadata_create_package_def {
1.483 albertel 10947: my ($uri,$key,$package,$metathesekeys)=@_;
10948: my ($pack,$name,$subp)=split(/\&/,$key);
10949: if ($subp eq 'default') { next; }
10950:
1.599 albertel 10951: if (defined($metaentry{':packages'})) {
10952: $metaentry{':packages'}.=','.$package;
1.483 albertel 10953: } else {
1.599 albertel 10954: $metaentry{':packages'}=$package;
1.483 albertel 10955: }
10956: my $value=$packagetab{$key};
10957: my $unikey;
10958: $unikey='parameter_0_'.$name;
1.599 albertel 10959: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10960: $$metathesekeys{$unikey}=1;
1.599 albertel 10961: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10962: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10963: }
1.599 albertel 10964: if (defined($metaentry{':'.$unikey.'.default'})) {
10965: $metaentry{':'.$unikey}=
10966: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10967: }
10968: }
10969:
1.261 albertel 10970: sub metadata_generate_part0 {
10971: my ($metadata,$metacache,$uri) = @_;
10972: my %allnames;
1.737 albertel 10973: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10974: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10975: my $part=$$metacache{':'.$metakey.'.part'};
10976: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10977: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10978: $allnames{$name}=$part;
10979: }
10980: }
10981: }
10982: foreach my $name (keys(%allnames)) {
10983: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10984: my $key=":parameter_0_$name";
1.261 albertel 10985: $$metacache{"$key.part"}='0';
10986: $$metacache{"$key.name"}=$name;
1.428 albertel 10987: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10988: $allnames{$name}.'_'.$name.
10989: '.type'};
1.428 albertel 10990: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10991: '.display'};
1.644 www 10992: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10993: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10994: $$metacache{"$key.display"}=$olddis;
10995: }
1.71 www 10996: }
10997:
1.764 albertel 10998: # ------------------------------------------------------ Devalidate title cache
10999:
11000: sub devalidate_title_cache {
11001: my ($url)=@_;
11002: if (!$env{'request.course.id'}) { return; }
11003: my $symb=&symbread($url);
11004: if (!$symb) { return; }
11005: my $key=$env{'request.course.id'}."\0".$symb;
11006: &devalidate_cache_new('title',$key);
11007: }
11008:
1.1014 droeschl 11009: # ------------------------------------------------- Get the title of a course
11010:
11011: sub current_course_title {
11012: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11013: }
1.301 www 11014: # ------------------------------------------------- Get the title of a resource
11015:
11016: sub gettitle {
11017: my $urlsymb=shift;
11018: my $symb=&symbread($urlsymb);
1.534 albertel 11019: if ($symb) {
1.620 albertel 11020: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11021: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11022: if (defined($cached)) {
11023: return $result;
11024: }
1.534 albertel 11025: my ($map,$resid,$url)=&decode_symb($symb);
11026: my $title='';
1.907 albertel 11027: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11028: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11029: } else {
11030: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11031: &GDBM_READER(),0640)) {
11032: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11033: $title=$bighash{'title_'.$mapid.'.'.$resid};
11034: untie(%bighash);
11035: }
1.534 albertel 11036: }
11037: $title=~s/\&colon\;/\:/gs;
11038: if ($title) {
1.1159 www 11039: # Remember both $symb and $title for dynamic metadata
11040: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11041: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11042: # Cache this title and then return it
1.599 albertel 11043: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11044: }
11045: $urlsymb=$url;
11046: }
11047: my $title=&metadata($urlsymb,'title');
11048: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11049: return $title;
1.301 www 11050: }
1.613 albertel 11051:
1.614 albertel 11052: sub get_slot {
11053: my ($which,$cnum,$cdom)=@_;
11054: if (!$cnum || !$cdom) {
1.790 albertel 11055: (undef,my $courseid)=&whichuser();
1.620 albertel 11056: $cdom=$env{'course.'.$courseid.'.domain'};
11057: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11058: }
1.703 albertel 11059: my $key=join("\0",'slots',$cdom,$cnum,$which);
11060: my %slotinfo;
11061: if (exists($remembered{$key})) {
11062: $slotinfo{$which} = $remembered{$key};
11063: } else {
11064: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11065: &Apache::lonhomework::showhash(%slotinfo);
11066: my ($tmp)=keys(%slotinfo);
11067: if ($tmp=~/^error:/) { return (); }
11068: $remembered{$key} = $slotinfo{$which};
11069: }
1.616 albertel 11070: if (ref($slotinfo{$which}) eq 'HASH') {
11071: return %{$slotinfo{$which}};
11072: }
11073: return $slotinfo{$which};
1.614 albertel 11074: }
1.1150 raeburn 11075:
11076: sub get_reservable_slots {
11077: my ($cnum,$cdom,$uname,$udom) = @_;
11078: my $now = time;
11079: my $reservable_info;
11080: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11081: if (exists($remembered{$key})) {
11082: $reservable_info = $remembered{$key};
11083: } else {
11084: my %resv;
11085: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11086: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11087: $reservable_info = \%resv;
11088: $remembered{$key} = $reservable_info;
11089: }
11090: return $reservable_info;
11091: }
11092:
11093: sub get_course_slots {
11094: my ($cnum,$cdom) = @_;
11095: my $hashid=$cnum.':'.$cdom;
11096: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11097: if (defined($cached)) {
11098: if (ref($result) eq 'HASH') {
11099: return %{$result};
11100: }
11101: } else {
11102: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11103: my ($tmp) = keys(%slots);
11104: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11105: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11106: return %slots;
11107: }
11108: }
11109: return;
11110: }
11111:
11112: sub devalidate_slots_cache {
11113: my ($cnum,$cdom)=@_;
11114: my $hashid=$cnum.':'.$cdom;
11115: &devalidate_cache_new('allslots',$hashid);
11116: }
11117:
1.1172.2.8 raeburn 11118: sub get_coursechange {
11119: my ($cdom,$cnum) = @_;
11120: if ($cdom eq '' || $cnum eq '') {
11121: return unless ($env{'request.course.id'});
11122: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11123: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11124: }
11125: my $hashid=$cdom.'_'.$cnum;
11126: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11127: if ((defined($cached)) && ($change ne '')) {
11128: return $change;
11129: } else {
11130: my %crshash;
11131: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11132: if ($crshash{'internal.contentchange'} eq '') {
11133: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11134: if ($change eq '') {
11135: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11136: $change = $crshash{'internal.created'};
11137: }
11138: } else {
11139: $change = $crshash{'internal.contentchange'};
11140: }
11141: my $cachetime = 600;
11142: &do_cache_new('crschange',$hashid,$change,$cachetime);
11143: }
11144: return $change;
11145: }
11146:
11147: sub devalidate_coursechange_cache {
11148: my ($cnum,$cdom)=@_;
11149: my $hashid=$cnum.':'.$cdom;
11150: &devalidate_cache_new('crschange',$hashid);
11151: }
11152:
1.31 www 11153: # ------------------------------------------------- Update symbolic store links
11154:
11155: sub symblist {
11156: my ($mapname,%newhash)=@_;
1.438 www 11157: $mapname=&deversion(&declutter($mapname));
1.31 www 11158: my %hash;
1.620 albertel 11159: if (($env{'request.course.fn'}) && (%newhash)) {
11160: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11161: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11162: foreach my $url (keys(%newhash)) {
1.711 albertel 11163: next if ($url eq 'last_known'
11164: && $env{'form.no_update_last_known'});
11165: $hash{declutter($url)}=&encode_symb($mapname,
11166: $newhash{$url}->[1],
11167: $newhash{$url}->[0]);
1.191 harris41 11168: }
1.31 www 11169: if (untie(%hash)) {
11170: return 'ok';
11171: }
11172: }
11173: }
11174: return 'error';
1.212 www 11175: }
11176:
11177: # --------------------------------------------------------------- Verify a symb
11178:
11179: sub symbverify {
1.1172.2.11 raeburn 11180: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11181: my $thisfn=$thisurl;
1.439 www 11182: $thisfn=&declutter($thisfn);
1.215 www 11183: # direct jump to resource in page or to a sequence - will construct own symbs
11184: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11185: # check URL part
1.409 www 11186: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11187:
1.431 www 11188: unless ($url eq $thisfn) { return 0; }
1.213 www 11189:
1.216 www 11190: $symb=&symbclean($symb);
1.510 www 11191: $thisurl=&deversion($thisurl);
1.439 www 11192: $thisfn=&deversion($thisfn);
1.213 www 11193:
11194: my %bighash;
11195: my $okay=0;
1.431 www 11196:
1.620 albertel 11197: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11198: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11199: my $noclutter;
1.1032 raeburn 11200: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11201: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11202: if ($map =~ m{^uploaded/.+\.page$}) {
11203: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11204: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11205: $noclutter = 1;
11206: }
11207: }
11208: my $ids;
11209: if ($noclutter) {
11210: $ids=$bighash{'ids_'.$thisurl};
11211: } else {
11212: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11213: }
1.1102 raeburn 11214: unless ($ids) {
1.1172.2.13 raeburn 11215: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11216: $ids=$bighash{$idkey};
1.216 www 11217: }
11218: if ($ids) {
11219: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11220: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11221: $symb =~ s/\?.+$//;
11222: }
1.800 albertel 11223: foreach my $id (split(/\,/,$ids)) {
11224: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11225: if (
11226: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11227: eq $symb) {
1.1172.2.11 raeburn 11228: if (ref($encstate)) {
11229: $$encstate = $bighash{'encrypted_'.$id};
11230: }
1.1172.2.13 raeburn 11231: if (($env{'request.role.adv'}) ||
11232: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11233: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11234: $okay=1;
11235: last;
11236: }
11237: }
11238: }
1.216 www 11239: }
1.213 www 11240: untie(%bighash);
11241: }
11242: return $okay;
1.31 www 11243: }
11244:
1.210 www 11245: # --------------------------------------------------------------- Clean-up symb
11246:
11247: sub symbclean {
11248: my $symb=shift;
1.568 albertel 11249: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11250: # remove version from map
11251: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11252:
1.210 www 11253: # remove version from URL
11254: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11255:
1.507 www 11256: # remove wrapper
11257:
1.510 www 11258: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11259: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11260: return $symb;
1.409 www 11261: }
11262:
11263: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11264:
11265: sub encode_symb {
11266: my ($map,$resid,$url)=@_;
11267: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11268: }
1.409 www 11269:
11270: sub decode_symb {
1.568 albertel 11271: my $symb=shift;
11272: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11273: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11274: return (&fixversion($map),$resid,&fixversion($url));
11275: }
11276:
11277: sub fixversion {
11278: my $fn=shift;
1.609 banghart 11279: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11280: my %bighash;
11281: my $uri=&clutter($fn);
1.620 albertel 11282: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11283: # is this cached?
1.599 albertel 11284: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11285: if (defined($cached)) { return $result; }
11286: # unfortunately not cached, or expired
1.620 albertel 11287: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11288: &GDBM_READER(),0640)) {
11289: if ($bighash{'version_'.$uri}) {
11290: my $version=$bighash{'version_'.$uri};
1.444 www 11291: unless (($version eq 'mostrecent') ||
11292: ($version==&getversion($uri))) {
1.440 www 11293: $uri=~s/\.(\w+)$/\.$version\.$1/;
11294: }
11295: }
11296: untie %bighash;
1.413 www 11297: }
1.599 albertel 11298: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11299: }
11300:
11301: sub deversion {
11302: my $url=shift;
11303: $url=~s/\.\d+\.(\w+)$/\.$1/;
11304: return $url;
1.210 www 11305: }
11306:
1.31 www 11307: # ------------------------------------------------------ Return symb list entry
11308:
11309: sub symbread {
1.1172.2.66 raeburn 11310: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11311: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11312: if (defined($env{$cache_str})) {
11313: if ($ignorecachednull) {
11314: return $env{$cache_str} unless ($env{$cache_str} eq '');
11315: } else {
11316: return $env{$cache_str};
11317: }
11318: }
1.242 www 11319: # no filename provided? try from environment
1.1172.2.54 raeburn 11320: unless ($thisfn) {
1.620 albertel 11321: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11322: return $env{$cache_str}=&symbclean($env{'request.symb'});
11323: }
11324: $thisfn=$env{'request.filename'};
1.44 www 11325: }
1.569 albertel 11326: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11327: # is that filename actually a symb? Verify, clean, and return
11328: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11329: if (&symbverify($thisfn,$1)) {
1.620 albertel 11330: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11331: }
1.242 www 11332: }
1.44 www 11333: $thisfn=declutter($thisfn);
1.31 www 11334: my %hash;
1.37 www 11335: my %bighash;
11336: my $syval='';
1.620 albertel 11337: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11338: my $targetfn = $thisfn;
1.609 banghart 11339: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11340: $targetfn = 'adm/wrapper/'.$thisfn;
11341: }
1.687 albertel 11342: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11343: $targetfn=$1;
11344: }
1.620 albertel 11345: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11346: &GDBM_READER(),0640)) {
1.481 raeburn 11347: $syval=$hash{$targetfn};
1.37 www 11348: untie(%hash);
11349: }
11350: # ---------------------------------------------------------- There was an entry
11351: if ($syval) {
1.601 albertel 11352: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11353: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11354: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11355: #return $env{$cache_str}='';
1.601 albertel 11356: #}
11357: #$syval.=$1;
11358: #}
1.37 www 11359: } else {
11360: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11361: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11362: &GDBM_READER(),0640)) {
1.37 www 11363: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11364: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11365: unless ($ids) {
11366: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11367: }
11368: unless ($ids) {
11369: # alias?
11370: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11371: }
1.37 www 11372: if ($ids) {
11373: # ------------------------------------------------------------------- Has ID(s)
11374: my @possibilities=split(/\,/,$ids);
1.39 www 11375: if ($#possibilities==0) {
11376: # ----------------------------------------------- There is only one possibility
1.37 www 11377: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11378: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11379: $resid,$thisfn);
1.1172.2.66 raeburn 11380: if (ref($possibles) eq 'HASH') {
11381: $possibles->{$syval} = 1;
11382: }
11383: if ($checkforblock) {
11384: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11385: if (@blockers) {
11386: $syval = '';
11387: return;
11388: }
11389: }
11390: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11391: # ------------------------------------------ There is more than one possibility
11392: my $realpossible=0;
1.800 albertel 11393: foreach my $id (@possibilities) {
11394: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11395: my $canaccess;
11396: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11397: $canaccess = 1;
11398: } else {
11399: $canaccess = &allowed('bre',$file);
11400: }
11401: if ($canaccess) {
11402: my ($mapid,$resid)=split(/\./,$id);
11403: if ($bighash{'map_type_'.$mapid} ne 'page') {
11404: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11405: $resid,$thisfn);
11406: if (ref($possibles) eq 'HASH') {
11407: $possibles->{$syval} = 1;
11408: }
11409: if ($checkforblock) {
11410: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11411: unless (@blockers > 0) {
11412: $syval = $poss_syval;
11413: $realpossible++;
11414: }
11415: } else {
11416: $syval = $poss_syval;
11417: $realpossible++;
11418: }
11419: }
1.39 www 11420: }
1.191 harris41 11421: }
1.39 www 11422: if ($realpossible!=1) { $syval=''; }
1.249 www 11423: } else {
11424: $syval='';
1.37 www 11425: }
11426: }
1.1172.2.66 raeburn 11427: untie(%bighash);
1.481 raeburn 11428: }
1.31 www 11429: }
1.62 www 11430: if ($syval) {
1.620 albertel 11431: return $env{$cache_str}=$syval;
1.62 www 11432: }
1.31 www 11433: }
1.949 raeburn 11434: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11435: return $env{$cache_str}='';
1.31 www 11436: }
11437:
11438: # ---------------------------------------------------------- Return random seed
11439:
1.32 www 11440: sub numval {
11441: my $txt=shift;
11442: $txt=~tr/A-J/0-9/;
11443: $txt=~tr/a-j/0-9/;
11444: $txt=~tr/K-T/0-9/;
11445: $txt=~tr/k-t/0-9/;
11446: $txt=~tr/U-Z/0-5/;
11447: $txt=~tr/u-z/0-5/;
11448: $txt=~s/\D//g;
1.564 albertel 11449: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11450: return int($txt);
1.368 albertel 11451: }
11452:
1.484 albertel 11453: sub numval2 {
11454: my $txt=shift;
11455: $txt=~tr/A-J/0-9/;
11456: $txt=~tr/a-j/0-9/;
11457: $txt=~tr/K-T/0-9/;
11458: $txt=~tr/k-t/0-9/;
11459: $txt=~tr/U-Z/0-5/;
11460: $txt=~tr/u-z/0-5/;
11461: $txt=~s/\D//g;
11462: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11463: my $total;
11464: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11465: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11466: return int($total);
11467: }
11468:
1.575 albertel 11469: sub numval3 {
11470: use integer;
11471: my $txt=shift;
11472: $txt=~tr/A-J/0-9/;
11473: $txt=~tr/a-j/0-9/;
11474: $txt=~tr/K-T/0-9/;
11475: $txt=~tr/k-t/0-9/;
11476: $txt=~tr/U-Z/0-5/;
11477: $txt=~tr/u-z/0-5/;
11478: $txt=~s/\D//g;
11479: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11480: my $total;
11481: foreach my $val (@txts) { $total+=$val; }
11482: if ($_64bit) { $total=(($total<<32)>>32); }
11483: return $total;
11484: }
11485:
1.675 albertel 11486: sub digest {
11487: my ($data)=@_;
11488: my $digest=&Digest::MD5::md5($data);
11489: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11490: my ($e,$f);
11491: {
11492: use integer;
11493: $e=($a+$b);
11494: $f=($c+$d);
11495: if ($_64bit) {
11496: $e=(($e<<32)>>32);
11497: $f=(($f<<32)>>32);
11498: }
11499: }
11500: if (wantarray) {
11501: return ($e,$f);
11502: } else {
11503: my $g;
11504: {
11505: use integer;
11506: $g=($e+$f);
11507: if ($_64bit) {
11508: $g=(($g<<32)>>32);
11509: }
11510: }
11511: return $g;
11512: }
11513: }
11514:
1.368 albertel 11515: sub latest_rnd_algorithm_id {
1.675 albertel 11516: return '64bit5';
1.366 albertel 11517: }
1.32 www 11518:
1.503 albertel 11519: sub get_rand_alg {
11520: my ($courseid)=@_;
1.790 albertel 11521: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11522: if ($courseid) {
1.620 albertel 11523: return $env{"course.$courseid.rndseed"};
1.503 albertel 11524: }
11525: return &latest_rnd_algorithm_id();
11526: }
11527:
1.562 albertel 11528: sub validCODE {
11529: my ($CODE)=@_;
11530: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11531: return 0;
11532: }
11533:
1.491 albertel 11534: sub getCODE {
1.620 albertel 11535: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11536: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11537: defined($Apache::lonhomework::parsing_a_task) ) &&
11538: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11539: return $Apache::lonhomework::history{'resource.CODE'};
11540: }
11541: return undef;
11542: }
1.1133 foxr 11543: #
11544: # Determines the random seed for a specific context:
11545: #
11546: # parameters:
11547: # symb - in course context the symb for the seed.
11548: # course_id - The course id of the form domain_coursenum.
11549: # domain - Domain for the user.
11550: # course - Course for the user.
11551: # cenv - environment of the course.
11552: #
11553: # NOTE:
11554: # All parameters are picked out of the environment if missing
11555: # or not defined.
11556: # If a symb cannot be determined the current time is used instead.
11557: #
11558: # For a given well defined symb, courside, domain, username,
11559: # and course environment, the seed is reproducible.
11560: #
1.31 www 11561: sub rndseed {
1.1133 foxr 11562: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11563: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11564: if (!defined($symb)) {
1.366 albertel 11565: unless ($symb=$wsymb) { return time; }
11566: }
1.1146 foxr 11567: if (!defined $courseid) {
11568: $courseid=$wcourseid;
11569: }
11570: if (!defined $domain) { $domain=$wdomain; }
11571: if (!defined $username) { $username=$wusername }
1.1133 foxr 11572:
11573: my $which;
11574: if (defined($cenv->{'rndseed'})) {
11575: $which = $cenv->{'rndseed'};
11576: } else {
11577: $which =&get_rand_alg($courseid);
11578: }
1.491 albertel 11579: if (defined(&getCODE())) {
1.675 albertel 11580: if ($which eq '64bit5') {
11581: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11582: } elsif ($which eq '64bit4') {
1.575 albertel 11583: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11584: } else {
11585: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11586: }
1.675 albertel 11587: } elsif ($which eq '64bit5') {
11588: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11589: } elsif ($which eq '64bit4') {
11590: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11591: } elsif ($which eq '64bit3') {
11592: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11593: } elsif ($which eq '64bit2') {
11594: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11595: } elsif ($which eq '64bit') {
11596: return &rndseed_64bit($symb,$courseid,$domain,$username);
11597: }
11598: return &rndseed_32bit($symb,$courseid,$domain,$username);
11599: }
11600:
11601: sub rndseed_32bit {
11602: my ($symb,$courseid,$domain,$username)=@_;
11603: {
11604: use integer;
11605: my $symbchck=unpack("%32C*",$symb) << 27;
11606: my $symbseed=numval($symb) << 22;
11607: my $namechck=unpack("%32C*",$username) << 17;
11608: my $nameseed=numval($username) << 12;
11609: my $domainseed=unpack("%32C*",$domain) << 7;
11610: my $courseseed=unpack("%32C*",$courseid);
11611: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11612: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11613: #&logthis("rndseed :$num:$symb");
1.564 albertel 11614: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11615: return $num;
11616: }
11617: }
11618:
11619: sub rndseed_64bit {
11620: my ($symb,$courseid,$domain,$username)=@_;
11621: {
11622: use integer;
11623: my $symbchck=unpack("%32S*",$symb) << 21;
11624: my $symbseed=numval($symb) << 10;
11625: my $namechck=unpack("%32S*",$username);
11626:
11627: my $nameseed=numval($username) << 21;
11628: my $domainseed=unpack("%32S*",$domain) << 10;
11629: my $courseseed=unpack("%32S*",$courseid);
11630:
11631: my $num1=$symbchck+$symbseed+$namechck;
11632: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11633: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11634: #&logthis("rndseed :$num:$symb");
1.564 albertel 11635: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11636: return "$num1,$num2";
1.155 albertel 11637: }
1.366 albertel 11638: }
11639:
1.443 albertel 11640: sub rndseed_64bit2 {
11641: my ($symb,$courseid,$domain,$username)=@_;
11642: {
11643: use integer;
11644: # strings need to be an even # of cahracters long, it it is odd the
11645: # last characters gets thrown away
11646: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11647: my $symbseed=numval($symb) << 10;
11648: my $namechck=unpack("%32S*",$username.' ');
11649:
11650: my $nameseed=numval($username) << 21;
1.501 albertel 11651: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11652: my $courseseed=unpack("%32S*",$courseid.' ');
11653:
11654: my $num1=$symbchck+$symbseed+$namechck;
11655: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11656: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11657: #&logthis("rndseed :$num:$symb");
1.803 albertel 11658: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11659: return "$num1,$num2";
11660: }
11661: }
11662:
11663: sub rndseed_64bit3 {
11664: my ($symb,$courseid,$domain,$username)=@_;
11665: {
11666: use integer;
11667: # strings need to be an even # of cahracters long, it it is odd the
11668: # last characters gets thrown away
11669: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11670: my $symbseed=numval2($symb) << 10;
11671: my $namechck=unpack("%32S*",$username.' ');
11672:
11673: my $nameseed=numval2($username) << 21;
1.443 albertel 11674: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11675: my $courseseed=unpack("%32S*",$courseid.' ');
11676:
11677: my $num1=$symbchck+$symbseed+$namechck;
11678: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11679: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11680: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11681: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11682:
1.503 albertel 11683: return "$num1:$num2";
1.443 albertel 11684: }
11685: }
11686:
1.575 albertel 11687: sub rndseed_64bit4 {
11688: my ($symb,$courseid,$domain,$username)=@_;
11689: {
11690: use integer;
11691: # strings need to be an even # of cahracters long, it it is odd the
11692: # last characters gets thrown away
11693: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11694: my $symbseed=numval3($symb) << 10;
11695: my $namechck=unpack("%32S*",$username.' ');
11696:
11697: my $nameseed=numval3($username) << 21;
11698: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11699: my $courseseed=unpack("%32S*",$courseid.' ');
11700:
11701: my $num1=$symbchck+$symbseed+$namechck;
11702: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11703: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11704: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11705: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11706:
1.575 albertel 11707: return "$num1:$num2";
11708: }
11709: }
11710:
1.675 albertel 11711: sub rndseed_64bit5 {
11712: my ($symb,$courseid,$domain,$username)=@_;
11713: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11714: return "$num1:$num2";
11715: }
11716:
1.366 albertel 11717: sub rndseed_CODE_64bit {
11718: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11719: {
1.366 albertel 11720: use integer;
1.443 albertel 11721: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11722: my $symbseed=numval2($symb);
1.491 albertel 11723: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11724: my $CODEseed=numval(&getCODE());
1.443 albertel 11725: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11726: my $num1=$symbseed+$CODEchck;
11727: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11728: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11729: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11730: if ($_64bit) { $num1=(($num1<<32)>>32); }
11731: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11732: return "$num1:$num2";
1.366 albertel 11733: }
11734: }
11735:
1.575 albertel 11736: sub rndseed_CODE_64bit4 {
11737: my ($symb,$courseid,$domain,$username)=@_;
11738: {
11739: use integer;
11740: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11741: my $symbseed=numval3($symb);
11742: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11743: my $CODEseed=numval3(&getCODE());
11744: my $courseseed=unpack("%32S*",$courseid.' ');
11745: my $num1=$symbseed+$CODEchck;
11746: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11747: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11748: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11749: if ($_64bit) { $num1=(($num1<<32)>>32); }
11750: if ($_64bit) { $num2=(($num2<<32)>>32); }
11751: return "$num1:$num2";
11752: }
11753: }
11754:
1.675 albertel 11755: sub rndseed_CODE_64bit5 {
11756: my ($symb,$courseid,$domain,$username)=@_;
11757: my $code = &getCODE();
11758: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11759: return "$num1:$num2";
11760: }
11761:
1.366 albertel 11762: sub setup_random_from_rndseed {
11763: my ($rndseed)=@_;
1.503 albertel 11764: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11765: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11766: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11767: &Math::Random::random_set_seed_from_phrase($rndseed);
11768: } else {
11769: &Math::Random::random_set_seed($num1,$num2);
11770: }
1.366 albertel 11771: } else {
11772: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11773: }
1.36 albertel 11774: }
11775:
1.474 albertel 11776: sub latest_receipt_algorithm_id {
1.835 albertel 11777: return 'receipt3';
1.474 albertel 11778: }
11779:
1.480 www 11780: sub recunique {
11781: my $fucourseid=shift;
11782: my $unique;
1.835 albertel 11783: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11784: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11785: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11786: } else {
11787: $unique=$perlvar{'lonReceipt'};
11788: }
11789: return unpack("%32C*",$unique);
11790: }
11791:
11792: sub recprefix {
11793: my $fucourseid=shift;
11794: my $prefix;
1.835 albertel 11795: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11796: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11797: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11798: } else {
11799: $prefix=$perlvar{'lonHostID'};
11800: }
11801: return unpack("%32C*",$prefix);
11802: }
11803:
1.76 www 11804: sub ireceipt {
1.474 albertel 11805: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11806:
11807: my $return =&recprefix($fucourseid).'-';
11808:
11809: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11810: $env{'request.state'} eq 'construct') {
11811: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11812: return $return;
11813: }
11814:
1.76 www 11815: my $cuname=unpack("%32C*",$funame);
11816: my $cudom=unpack("%32C*",$fudom);
11817: my $cucourseid=unpack("%32C*",$fucourseid);
11818: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11819: my $cunique=&recunique($fucourseid);
1.474 albertel 11820: my $cpart=unpack("%32S*",$part);
1.835 albertel 11821: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11822:
1.790 albertel 11823: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11824:
11825: $return.= ($cunique%$cuname+
11826: $cunique%$cudom+
11827: $cusymb%$cuname+
11828: $cusymb%$cudom+
11829: $cucourseid%$cuname+
11830: $cucourseid%$cudom+
11831: $cpart%$cuname+
11832: $cpart%$cudom);
11833: } else {
11834: $return.= ($cunique%$cuname+
11835: $cunique%$cudom+
11836: $cusymb%$cuname+
11837: $cusymb%$cudom+
11838: $cucourseid%$cuname+
11839: $cucourseid%$cudom);
11840: }
11841: return $return;
1.76 www 11842: }
11843:
11844: sub receipt {
1.474 albertel 11845: my ($part)=@_;
1.790 albertel 11846: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11847: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11848: }
1.260 ng 11849:
1.790 albertel 11850: sub whichuser {
11851: my ($passedsymb)=@_;
11852: my ($symb,$courseid,$domain,$name,$publicuser);
11853: if (defined($env{'form.grade_symb'})) {
11854: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11855: my $allowed=&allowed('vgr',$tmp_courseid);
11856: if (!$allowed &&
11857: exists($env{'request.course.sec'}) &&
11858: $env{'request.course.sec'} !~ /^\s*$/) {
11859: $allowed=&allowed('vgr',$tmp_courseid.
11860: '/'.$env{'request.course.sec'});
11861: }
11862: if ($allowed) {
11863: ($symb)=&get_env_multiple('form.grade_symb');
11864: $courseid=$tmp_courseid;
11865: ($domain)=&get_env_multiple('form.grade_domain');
11866: ($name)=&get_env_multiple('form.grade_username');
11867: return ($symb,$courseid,$domain,$name,$publicuser);
11868: }
11869: }
11870: if (!$passedsymb) {
11871: $symb=&symbread();
11872: } else {
11873: $symb=$passedsymb;
11874: }
11875: $courseid=$env{'request.course.id'};
11876: $domain=$env{'user.domain'};
11877: $name=$env{'user.name'};
11878: if ($name eq 'public' && $domain eq 'public') {
11879: if (!defined($env{'form.username'})) {
11880: $env{'form.username'}.=time.rand(10000000);
11881: }
11882: $name.=$env{'form.username'};
11883: }
11884: return ($symb,$courseid,$domain,$name,$publicuser);
11885:
11886: }
11887:
1.36 albertel 11888: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11889: # returns either the contents of the file or
11890: # -1 if the file doesn't exist
1.481 raeburn 11891: #
11892: # if the target is a file that was uploaded via DOCS,
11893: # a check will be made to see if a current copy exists on the local server,
11894: # if it does this will be served, otherwise a copy will be retrieved from
11895: # the home server for the course and stored in /home/httpd/html/userfiles on
11896: # the local server.
1.472 albertel 11897:
1.36 albertel 11898: sub getfile {
1.538 albertel 11899: my ($file) = @_;
1.609 banghart 11900: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11901: &repcopy($file);
11902: return &readfile($file);
11903: }
11904:
11905: sub repcopy_userfile {
11906: my ($file)=@_;
1.1142 raeburn 11907: my $londocroot = $perlvar{'lonDocRoot'};
11908: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11909: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11910: my ($cdom,$cnum,$filename) =
1.811 albertel 11911: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11912: my $uri="/uploaded/$cdom/$cnum/$filename";
11913: if (-e "$file") {
1.828 www 11914: # we already have a local copy, check it out
1.538 albertel 11915: my @fileinfo = stat($file);
1.828 www 11916: my $rtncode;
11917: my $info;
1.538 albertel 11918: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11919: if ($lwpresp ne 'ok') {
1.828 www 11920: # there is no such file anymore, even though we had a local copy
1.482 albertel 11921: if ($rtncode eq '404') {
1.538 albertel 11922: unlink($file);
1.482 albertel 11923: }
11924: return -1;
11925: }
11926: if ($info < $fileinfo[9]) {
1.828 www 11927: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11928: return 'ok';
1.828 www 11929: } else {
11930: # the file is outdated, get rid of it
11931: unlink($file);
1.482 albertel 11932: }
1.828 www 11933: }
11934: # one way or the other, at this point, we don't have the file
11935: # construct the correct path for the file
11936: my @parts = ($cdom,$cnum);
11937: if ($filename =~ m|^(.+)/[^/]+$|) {
11938: push @parts, split(/\//,$1);
11939: }
11940: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11941: foreach my $part (@parts) {
11942: $path .= '/'.$part;
11943: if (!-e $path) {
11944: mkdir($path,0770);
1.482 albertel 11945: }
11946: }
1.828 www 11947: # now the path exists for sure
11948: # get a user agent
11949: my $ua=new LWP::UserAgent;
11950: my $transferfile=$file.'.in.transfer';
11951: # FIXME: this should flock
11952: if (-e $transferfile) { return 'ok'; }
11953: my $request;
11954: $uri=~s/^\///;
1.980 raeburn 11955: my $homeserver = &homeserver($cnum,$cdom);
11956: my $protocol = $protocol{$homeserver};
11957: $protocol = 'http' if ($protocol ne 'https');
11958: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11959: my $response=$ua->request($request,$transferfile);
11960: # did it work?
11961: if ($response->is_error()) {
11962: unlink($transferfile);
11963: &logthis("Userfile repcopy failed for $uri");
11964: return -1;
11965: }
11966: # worked, rename the transfer file
11967: rename($transferfile,$file);
1.607 raeburn 11968: return 'ok';
1.481 raeburn 11969: }
11970:
1.517 albertel 11971: sub tokenwrapper {
11972: my $uri=shift;
1.980 raeburn 11973: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11974: $uri=~s|^/||;
1.620 albertel 11975: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11976: my $token=$1;
1.552 albertel 11977: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11978: if ($udom && $uname && $file) {
11979: $file=~s|(\?\.*)*$||;
1.949 raeburn 11980: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11981: my $homeserver = &homeserver($uname,$udom);
11982: my $protocol = $protocol{$homeserver};
11983: $protocol = 'http' if ($protocol ne 'https');
11984: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11985: (($uri=~/\?/)?'&':'?').'token='.$token.
11986: '&tokenissued='.$perlvar{'lonHostID'};
11987: } else {
11988: return '/adm/notfound.html';
11989: }
11990: }
11991:
1.828 www 11992: # call with reqtype HEAD: get last modification time
11993: # call with reqtype GET: get the file contents
11994: # Do not call this with reqtype GET for large files! It loads everything into memory
11995: #
1.481 raeburn 11996: sub getuploaded {
11997: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11998: $uri=~s/^\///;
1.980 raeburn 11999: my $homeserver = &homeserver($cnum,$cdom);
12000: my $protocol = $protocol{$homeserver};
12001: $protocol = 'http' if ($protocol ne 'https');
12002: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12003: my $ua=new LWP::UserAgent;
12004: my $request=new HTTP::Request($reqtype,$uri);
12005: my $response=$ua->request($request);
12006: $$rtncode = $response->code;
1.482 albertel 12007: if (! $response->is_success()) {
12008: return 'failed';
12009: }
12010: if ($reqtype eq 'HEAD') {
1.486 www 12011: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12012: } elsif ($reqtype eq 'GET') {
12013: $$info = $response->content;
1.472 albertel 12014: }
1.482 albertel 12015: return 'ok';
1.36 albertel 12016: }
12017:
1.481 raeburn 12018: sub readfile {
12019: my $file = shift;
12020: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12021: my $fh;
12022: open($fh,"<$file");
12023: my $a='';
1.800 albertel 12024: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12025: return $a;
12026: }
12027:
1.36 albertel 12028: sub filelocation {
1.590 banghart 12029: my ($dir,$file) = @_;
12030: my $location;
12031: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12032:
12033: if ($file =~ m-^/adm/-) {
12034: $file=~s-^/adm/wrapper/-/-;
12035: $file=~s-^/adm/coursedocs/showdoc/-/-;
12036: }
1.882 albertel 12037:
1.1139 www 12038: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12039: $location = $file;
1.609 banghart 12040: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12041: my ($udom,$uname,$filename)=
1.811 albertel 12042: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12043: my $home=&homeserver($uname,$udom);
12044: my $is_me=0;
12045: my @ids=¤t_machine_ids();
12046: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12047: if ($is_me) {
1.1117 foxr 12048: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12049: } else {
12050: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12051: $udom.'/'.$uname.'/'.$filename;
12052: }
1.882 albertel 12053: } elsif ($file =~ m-^/adm/-) {
12054: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12055: } else {
12056: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12057: $file=~s:^/(res|priv)/:/:;
12058: my $space=$1;
1.590 banghart 12059: if ( !( $file =~ m:^/:) ) {
12060: $location = $dir. '/'.$file;
12061: } else {
1.1142 raeburn 12062: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12063: }
1.59 albertel 12064: }
1.590 banghart 12065: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12066: while ($location=~m{/\.\./}) {
12067: if ($location =~ m{/[^/]+/\.\./}) {
12068: $location=~ s{/[^/]+/\.\./}{/}g;
12069: } else {
12070: $location=~ s{/\.\./}{/}g;
12071: }
12072: } #remove dir/..
1.590 banghart 12073: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12074: return $location;
1.46 www 12075: }
1.36 albertel 12076:
1.46 www 12077: sub hreflocation {
12078: my ($dir,$file)=@_;
1.980 raeburn 12079: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12080: $file=filelocation($dir,$file);
1.700 albertel 12081: } elsif ($file=~m-^/adm/-) {
12082: $file=~s-^/adm/wrapper/-/-;
12083: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12084: }
12085: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12086: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12087: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12088: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12089: {/uploaded/$1/$2/}x;
1.46 www 12090: }
1.913 albertel 12091: if ($file=~ m{^/userfiles/}) {
12092: $file =~ s{^/userfiles/}{/uploaded/};
12093: }
1.462 albertel 12094: return $file;
1.465 albertel 12095: }
12096:
1.1139 www 12097:
12098:
12099:
12100:
1.465 albertel 12101: sub current_machine_domains {
1.853 albertel 12102: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12103: }
12104:
12105: sub machine_domains {
12106: my ($hostname) = @_;
1.465 albertel 12107: my @domains;
1.838 albertel 12108: my %hostname = &all_hostnames();
1.465 albertel 12109: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12110: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12111: if ($hostname eq $name) {
1.844 albertel 12112: push(@domains,&host_domain($id));
1.465 albertel 12113: }
12114: }
12115: return @domains;
12116: }
12117:
12118: sub current_machine_ids {
1.853 albertel 12119: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12120: }
12121:
12122: sub machine_ids {
12123: my ($hostname) = @_;
12124: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12125: my @ids;
1.888 albertel 12126: my %name_to_host = &all_names();
1.889 albertel 12127: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12128: return @{ $name_to_host{$hostname} };
12129: }
12130: return;
1.31 www 12131: }
12132:
1.824 raeburn 12133: sub additional_machine_domains {
12134: my @domains;
12135: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12136: while( my $line = <$fh>) {
12137: $line =~ s/\s//g;
12138: push(@domains,$line);
12139: }
12140: return @domains;
12141: }
12142:
12143: sub default_login_domain {
12144: my $domain = $perlvar{'lonDefDomain'};
12145: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12146: foreach my $posdom (¤t_machine_domains(),
12147: &additional_machine_domains()) {
12148: if (lc($posdom) eq lc($testdomain)) {
12149: $domain=$posdom;
12150: last;
12151: }
12152: }
12153: return $domain;
12154: }
12155:
1.31 www 12156: # ------------------------------------------------------------- Declutters URLs
12157:
12158: sub declutter {
12159: my $thisfn=shift;
1.569 albertel 12160: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12161: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12162: $thisfn=~s{^/home/httpd/html}{};
12163: }
1.31 www 12164: $thisfn=~s/^\///;
1.697 albertel 12165: $thisfn=~s|^adm/wrapper/||;
12166: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12167: $thisfn=~s/^res\///;
1.1172 bisitz 12168: $thisfn=~s/^priv\///;
1.1032 raeburn 12169: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12170: $thisfn=~s/\?.+$//;
12171: }
1.268 www 12172: return $thisfn;
12173: }
12174:
12175: # ------------------------------------------------------------- Clutter up URLs
12176:
12177: sub clutter {
12178: my $thisfn='/'.&declutter(shift);
1.887 albertel 12179: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12180: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12181: $thisfn='/res'.$thisfn;
12182: }
1.1031 raeburn 12183: if ($thisfn !~m|^/adm|) {
12184: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12185: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12186: } else {
12187: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12188: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12189: if ($embstyle eq 'ssi'
12190: || ($embstyle eq 'hdn')
12191: || ($embstyle eq 'rat')
12192: || ($embstyle eq 'prv')
12193: || ($embstyle eq 'ign')) {
12194: #do nothing with these
12195: } elsif (($embstyle eq 'img')
1.695 albertel 12196: || ($embstyle eq 'emb')
12197: || ($embstyle eq 'wrp')) {
12198: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12199: } elsif ($embstyle eq 'unk'
12200: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12201: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12202: } else {
1.718 www 12203: # &logthis("Got a blank emb style");
1.695 albertel 12204: }
1.694 albertel 12205: }
12206: }
1.31 www 12207: return $thisfn;
1.12 www 12208: }
12209:
1.787 albertel 12210: sub clutter_with_no_wrapper {
12211: my $uri = &clutter(shift);
12212: if ($uri =~ m-^/adm/-) {
12213: $uri =~ s-^/adm/wrapper/-/-;
12214: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12215: }
12216: return $uri;
12217: }
12218:
1.557 albertel 12219: sub freeze_escape {
12220: my ($value)=@_;
12221: if (ref($value)) {
12222: $value=&nfreeze($value);
12223: return '__FROZEN__'.&escape($value);
12224: }
12225: return &escape($value);
12226: }
12227:
1.11 www 12228:
1.557 albertel 12229: sub thaw_unescape {
12230: my ($value)=@_;
12231: if ($value =~ /^__FROZEN__/) {
12232: substr($value,0,10,undef);
12233: $value=&unescape($value);
12234: return &thaw($value);
12235: }
12236: return &unescape($value);
12237: }
12238:
1.436 albertel 12239: sub correct_line_ends {
12240: my ($result)=@_;
12241: $$result =~s/\r\n/\n/mg;
12242: $$result =~s/\r/\n/mg;
1.415 albertel 12243: }
1.1 albertel 12244: # ================================================================ Main Program
12245:
1.184 www 12246: sub goodbye {
1.204 albertel 12247: &logthis("Starting Shut down");
1.443 albertel 12248: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12249: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12250: #converted
1.599 albertel 12251: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12252: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12253: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12254: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12255: #1.1 only
1.870 albertel 12256: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12257: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12258: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12259: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12260: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12261: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12262: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12263: &flushcourselogs();
12264: &logthis("Shutting down");
12265: }
12266:
1.852 albertel 12267: sub get_dns {
1.1172.2.17 raeburn 12268: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12269: if (!$ignore_cache) {
12270: my ($content,$cached)=
12271: &Apache::lonnet::is_cached_new('dns',$url);
12272: if ($cached) {
1.1172.2.17 raeburn 12273: &$func($content,$hashref);
1.869 albertel 12274: return;
12275: }
12276: }
12277:
12278: my %alldns;
1.852 albertel 12279: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12280: foreach my $dns (<$config>) {
12281: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12282: my $line = $1;
12283: my ($host,$protocol) = split(/:/,$line);
12284: if ($protocol ne 'https') {
12285: $protocol = 'http';
12286: }
12287: $alldns{$host} = $protocol;
1.869 albertel 12288: }
12289: while (%alldns) {
1.1172.2.52 raeburn 12290: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12291: my $ua=new LWP::UserAgent;
1.1134 raeburn 12292: $ua->timeout(30);
1.979 raeburn 12293: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12294: my $response=$ua->request($request);
1.979 raeburn 12295: delete($alldns{$dns});
1.852 albertel 12296: next if ($response->is_error());
12297: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12298: unless ($nocache) {
1.1172.2.23 raeburn 12299: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12300: }
12301: &$func(\@content,$hashref);
1.869 albertel 12302: return;
1.852 albertel 12303: }
12304: close($config);
1.871 albertel 12305: my $which = (split('/',$url))[3];
12306: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12307: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12308: my @content = <$config>;
1.1172.2.17 raeburn 12309: &$func(\@content,$hashref);
12310: return;
12311: }
12312:
12313: # ------------------------------------------------------Get DNS checksums file
12314: sub parse_dns_checksums_tab {
12315: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12316: my $lonhost = $perlvar{'lonHostID'};
12317: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12318: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12319: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12320: my $webconfdir = '/etc/httpd/conf';
12321: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12322: $webconfdir = '/etc/apache2';
12323: } elsif ($distro =~ /^sles(\d+)$/) {
12324: if ($1 >= 10) {
12325: $webconfdir = '/etc/apache2';
12326: }
12327: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12328: if ($1 >= 10.0) {
12329: $webconfdir = '/etc/apache2';
12330: }
12331: }
1.1172.2.17 raeburn 12332: my ($release,$timestamp) = split(/\-/,$loncaparev);
12333: my (%chksum,%revnum);
12334: if (ref($lines) eq 'ARRAY') {
12335: chomp(@{$lines});
1.1172.2.34 raeburn 12336: my $version = shift(@{$lines});
12337: if ($version eq $release) {
1.1172.2.17 raeburn 12338: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12339: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12340: if ($file =~ m{^/etc/httpd/conf}) {
12341: if ($webconfdir eq '/etc/apache2') {
12342: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12343: }
12344: }
1.1172.2.34 raeburn 12345: $chksum{$file} = $shasum;
12346: $revnum{$file} = $version;
1.1172.2.17 raeburn 12347: }
12348: if (ref($hashref) eq 'HASH') {
12349: %{$hashref} = (
12350: sums => \%chksum,
12351: versions => \%revnum,
12352: );
12353: }
12354: }
12355: }
1.869 albertel 12356: return;
1.852 albertel 12357: }
1.1172.2.17 raeburn 12358:
12359: sub fetch_dns_checksums {
12360: my %checksums;
1.1172.2.34 raeburn 12361: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12362: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12363: my ($release,$timestamp) = split(/\-/,$loncaparev);
12364: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12365: \%checksums);
12366: return \%checksums;
12367: }
12368:
1.327 albertel 12369: # ------------------------------------------------------------ Read domain file
12370: {
1.852 albertel 12371: my $loaded;
1.846 albertel 12372: my %domain;
12373:
1.852 albertel 12374: sub parse_domain_tab {
12375: my ($lines) = @_;
12376: foreach my $line (@$lines) {
12377: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12378:
1.846 albertel 12379: chomp($line);
1.852 albertel 12380: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12381: my %this_domain;
12382: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12383: 'lang_def', 'city', 'longi', 'lati',
12384: 'primary') {
12385: $this_domain{$field} = shift(@elements);
12386: }
12387: $domain{$name} = \%this_domain;
1.852 albertel 12388: }
12389: }
1.864 albertel 12390:
12391: sub reset_domain_info {
12392: undef($loaded);
12393: undef(%domain);
12394: }
12395:
1.852 albertel 12396: sub load_domain_tab {
1.1172.2.70 raeburn 12397: my ($ignore_cache,$nocache) = @_;
12398: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12399: my $fh;
12400: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12401: my @lines = <$fh>;
12402: &parse_domain_tab(\@lines);
1.448 albertel 12403: }
1.852 albertel 12404: close($fh);
12405: $loaded = 1;
1.327 albertel 12406: }
1.846 albertel 12407:
12408: sub domain {
1.852 albertel 12409: &load_domain_tab() if (!$loaded);
12410:
1.846 albertel 12411: my ($name,$what) = @_;
12412: return if ( !exists($domain{$name}) );
12413:
12414: if (!$what) {
12415: return $domain{$name}{'description'};
12416: }
12417: return $domain{$name}{$what};
12418: }
1.974 raeburn 12419:
12420: sub domain_info {
12421: &load_domain_tab() if (!$loaded);
12422: return %domain;
12423: }
12424:
1.327 albertel 12425: }
12426:
12427:
1.1 albertel 12428: # ------------------------------------------------------------- Read hosts file
12429: {
1.838 albertel 12430: my %hostname;
1.844 albertel 12431: my %hostdom;
1.845 albertel 12432: my %libserv;
1.852 albertel 12433: my $loaded;
1.888 albertel 12434: my %name_to_host;
1.1074 raeburn 12435: my %internetdom;
1.1107 raeburn 12436: my %LC_dns_serv;
1.852 albertel 12437:
12438: sub parse_hosts_tab {
12439: my ($file) = @_;
12440: foreach my $configline (@$file) {
12441: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12442: chomp($configline);
12443: if ($configline =~ /^\^/) {
12444: if ($configline =~ /^\^([\w.\-]+)/) {
12445: $LC_dns_serv{$1} = 1;
12446: }
12447: next;
12448: }
1.1074 raeburn 12449: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12450: $name=~s/\s//g;
12451: if ($id && $domain && $role && $name) {
12452: $hostname{$id}=$name;
1.888 albertel 12453: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12454: $hostdom{$id}=$domain;
12455: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12456: if (defined($protocol)) {
12457: if ($protocol eq 'https') {
12458: $protocol{$id} = $protocol;
12459: } else {
12460: $protocol{$id} = 'http';
12461: }
1.968 raeburn 12462: } else {
1.969 raeburn 12463: $protocol{$id} = 'http';
1.968 raeburn 12464: }
1.1074 raeburn 12465: if (defined($intdom)) {
12466: $internetdom{$id} = $intdom;
12467: }
1.852 albertel 12468: }
12469: }
12470: }
1.864 albertel 12471:
12472: sub reset_hosts_info {
1.897 albertel 12473: &purge_remembered();
1.864 albertel 12474: &reset_domain_info();
12475: &reset_hosts_ip_info();
1.892 albertel 12476: undef(%name_to_host);
1.864 albertel 12477: undef(%hostname);
12478: undef(%hostdom);
12479: undef(%libserv);
12480: undef($loaded);
12481: }
1.1 albertel 12482:
1.852 albertel 12483: sub load_hosts_tab {
1.1172.2.70 raeburn 12484: my ($ignore_cache,$nocache) = @_;
12485: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12486: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12487: my @config = <$config>;
12488: &parse_hosts_tab(\@config);
12489: close($config);
12490: $loaded=1;
1.1 albertel 12491: }
1.852 albertel 12492:
1.838 albertel 12493: sub hostname {
1.852 albertel 12494: &load_hosts_tab() if (!$loaded);
12495:
1.838 albertel 12496: my ($lonid) = @_;
12497: return $hostname{$lonid};
12498: }
1.845 albertel 12499:
1.838 albertel 12500: sub all_hostnames {
1.852 albertel 12501: &load_hosts_tab() if (!$loaded);
12502:
1.838 albertel 12503: return %hostname;
12504: }
1.845 albertel 12505:
1.888 albertel 12506: sub all_names {
1.1172.2.70 raeburn 12507: my ($ignore_cache,$nocache) = @_;
12508: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12509:
12510: return %name_to_host;
12511: }
12512:
1.974 raeburn 12513: sub all_host_domain {
12514: &load_hosts_tab() if (!$loaded);
12515: return %hostdom;
12516: }
12517:
1.845 albertel 12518: sub is_library {
1.852 albertel 12519: &load_hosts_tab() if (!$loaded);
12520:
1.845 albertel 12521: return exists($libserv{$_[0]});
12522: }
12523:
12524: sub all_library {
1.852 albertel 12525: &load_hosts_tab() if (!$loaded);
12526:
1.845 albertel 12527: return %libserv;
12528: }
12529:
1.1062 droeschl 12530: sub unique_library {
12531: #2x reverse removes all hostnames that appear more than once
12532: my %unique = reverse &all_library();
12533: return reverse %unique;
12534: }
12535:
1.841 albertel 12536: sub get_servers {
1.852 albertel 12537: &load_hosts_tab() if (!$loaded);
12538:
1.841 albertel 12539: my ($domain,$type) = @_;
12540: my %possible_hosts = ($type eq 'library') ? %libserv
12541: : %hostname;
12542: my %result;
1.842 albertel 12543: if (ref($domain) eq 'ARRAY') {
12544: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12545: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12546: $result{$host} = $hostname;
12547: }
12548: }
12549: } else {
12550: while ( my ($host,$hostname) = each(%possible_hosts)) {
12551: if ($hostdom{$host} eq $domain) {
12552: $result{$host} = $hostname;
12553: }
1.841 albertel 12554: }
12555: }
12556: return %result;
12557: }
1.845 albertel 12558:
1.1062 droeschl 12559: sub get_unique_servers {
12560: my %unique = reverse &get_servers(@_);
12561: return reverse %unique;
12562: }
12563:
1.844 albertel 12564: sub host_domain {
1.852 albertel 12565: &load_hosts_tab() if (!$loaded);
12566:
1.844 albertel 12567: my ($lonid) = @_;
12568: return $hostdom{$lonid};
12569: }
12570:
1.841 albertel 12571: sub all_domains {
1.852 albertel 12572: &load_hosts_tab() if (!$loaded);
12573:
1.841 albertel 12574: my %seen;
12575: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12576: return @uniq;
12577: }
1.1074 raeburn 12578:
12579: sub internet_dom {
12580: &load_hosts_tab() if (!$loaded);
12581:
12582: my ($lonid) = @_;
12583: return $internetdom{$lonid};
12584: }
1.1107 raeburn 12585:
12586: sub is_LC_dns {
12587: &load_hosts_tab() if (!$loaded);
12588:
12589: my ($hostname) = @_;
12590: return exists($LC_dns_serv{$hostname});
12591: }
12592:
1.1 albertel 12593: }
12594:
1.847 albertel 12595: {
12596: my %iphost;
1.856 albertel 12597: my %name_to_ip;
12598: my %lonid_to_ip;
1.869 albertel 12599:
1.847 albertel 12600: sub get_hosts_from_ip {
12601: my ($ip) = @_;
12602: my %iphosts = &get_iphost();
12603: if (ref($iphosts{$ip})) {
12604: return @{$iphosts{$ip}};
12605: }
12606: return;
1.839 albertel 12607: }
1.864 albertel 12608:
12609: sub reset_hosts_ip_info {
12610: undef(%iphost);
12611: undef(%name_to_ip);
12612: undef(%lonid_to_ip);
12613: }
1.856 albertel 12614:
12615: sub get_host_ip {
12616: my ($lonid) = @_;
12617: if (exists($lonid_to_ip{$lonid})) {
12618: return $lonid_to_ip{$lonid};
12619: }
12620: my $name=&hostname($lonid);
12621: my $ip = gethostbyname($name);
12622: return if (!$ip || length($ip) ne 4);
12623: $ip=inet_ntoa($ip);
12624: $name_to_ip{$name} = $ip;
12625: $lonid_to_ip{$lonid} = $ip;
12626: return $ip;
12627: }
1.847 albertel 12628:
12629: sub get_iphost {
1.1172.2.70 raeburn 12630: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12631:
1.869 albertel 12632: if (!$ignore_cache) {
12633: if (%iphost) {
12634: return %iphost;
12635: }
12636: my ($ip_info,$cached)=
12637: &Apache::lonnet::is_cached_new('iphost','iphost');
12638: if ($cached) {
12639: %iphost = %{$ip_info->[0]};
12640: %name_to_ip = %{$ip_info->[1]};
12641: %lonid_to_ip = %{$ip_info->[2]};
12642: return %iphost;
12643: }
12644: }
1.894 albertel 12645:
12646: # get yesterday's info for fallback
12647: my %old_name_to_ip;
12648: my ($ip_info,$cached)=
12649: &Apache::lonnet::is_cached_new('iphost','iphost');
12650: if ($cached) {
12651: %old_name_to_ip = %{$ip_info->[1]};
12652: }
12653:
1.1172.2.70 raeburn 12654: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12655: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12656: my $ip;
12657: if (!exists($name_to_ip{$name})) {
12658: $ip = gethostbyname($name);
12659: if (!$ip || length($ip) ne 4) {
1.894 albertel 12660: if (defined($old_name_to_ip{$name})) {
12661: $ip = $old_name_to_ip{$name};
12662: &logthis("Can't find $name defaulting to old $ip");
12663: } else {
12664: &logthis("Name $name no IP found");
12665: next;
12666: }
12667: } else {
12668: $ip=inet_ntoa($ip);
1.847 albertel 12669: }
12670: $name_to_ip{$name} = $ip;
12671: } else {
12672: $ip = $name_to_ip{$name};
1.653 albertel 12673: }
1.888 albertel 12674: foreach my $id (@{ $name_to_host{$name} }) {
12675: $lonid_to_ip{$id} = $ip;
12676: }
12677: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12678: }
1.1172.2.70 raeburn 12679: unless ($nocache) {
12680: &do_cache_new('iphost','iphost',
12681: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12682: 48*60*60);
12683: }
1.869 albertel 12684:
1.847 albertel 12685: return %iphost;
1.598 albertel 12686: }
12687:
1.992 raeburn 12688: #
12689: # Given a DNS returns the loncapa host name for that DNS
12690: #
12691: sub host_from_dns {
12692: my ($dns) = @_;
12693: my @hosts;
12694: my $ip;
12695:
1.993 raeburn 12696: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12697: $ip = $name_to_ip{$dns};
12698: }
12699: if (!$ip) {
12700: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12701: if (length($ip) == 4) {
12702: $ip = &IO::Socket::inet_ntoa($ip);
12703: }
12704: }
12705: if ($ip) {
12706: @hosts = get_hosts_from_ip($ip);
12707: return $hosts[0];
12708: }
12709: return undef;
1.986 foxr 12710: }
1.992 raeburn 12711:
1.1074 raeburn 12712: sub get_internet_names {
12713: my ($lonid) = @_;
12714: return if ($lonid eq '');
12715: my ($idnref,$cached)=
12716: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12717: if ($cached) {
12718: return $idnref;
12719: }
12720: my $ip = &get_host_ip($lonid);
12721: my @hosts = &get_hosts_from_ip($ip);
12722: my %iphost = &get_iphost();
12723: my (@idns,%seen);
12724: foreach my $id (@hosts) {
12725: my $dom = &host_domain($id);
12726: my $prim_id = &domain($dom,'primary');
12727: my $prim_ip = &get_host_ip($prim_id);
12728: next if ($seen{$prim_ip});
12729: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12730: foreach my $id (@{$iphost{$prim_ip}}) {
12731: my $intdom = &internet_dom($id);
12732: unless (grep(/^\Q$intdom\E$/,@idns)) {
12733: push(@idns,$intdom);
12734: }
12735: }
12736: }
12737: $seen{$prim_ip} = 1;
12738: }
1.1172.2.23 raeburn 12739: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12740: }
12741:
1.986 foxr 12742: }
12743:
1.1079 raeburn 12744: sub all_loncaparevs {
1.1172.2.39 raeburn 12745: 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 12746: }
12747:
1.1172.2.27 raeburn 12748: # ------------------------------------------------------- Read loncaparev table
12749: {
12750: sub load_loncaparevs {
12751: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12752: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12753: while (my $configline=<$config>) {
12754: chomp($configline);
12755: my ($hostid,$loncaparev)=split(/:/,$configline);
12756: $loncaparevs{$hostid}=$loncaparev;
12757: }
12758: close($config);
12759: }
12760: }
12761: }
12762: }
12763:
12764: # ----------------------------------------------------- Read serverhostID table
12765: {
12766: sub load_serverhomeIDs {
12767: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12768: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12769: while (my $configline=<$config>) {
12770: chomp($configline);
12771: my ($name,$id)=split(/:/,$configline);
12772: $serverhomeIDs{$name}=$id;
12773: }
12774: close($config);
12775: }
12776: }
12777: }
12778: }
12779:
12780:
1.862 albertel 12781: BEGIN {
12782:
12783: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12784: unless ($readit) {
12785: {
12786: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12787: %perlvar = (%perlvar,%{$configvars});
12788: }
12789:
12790:
1.1 albertel 12791: # ------------------------------------------------------ Read spare server file
12792: {
1.448 albertel 12793: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12794:
12795: while (my $configline=<$config>) {
12796: chomp($configline);
1.284 matthew 12797: if ($configline) {
1.784 albertel 12798: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12799: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12800: push(@{ $spareid{$type} }, $host);
1.1 albertel 12801: }
12802: }
1.448 albertel 12803: close($config);
1.1 albertel 12804: }
1.11 www 12805: # ------------------------------------------------------------ Read permissions
12806: {
1.448 albertel 12807: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12808:
12809: while (my $configline=<$config>) {
1.448 albertel 12810: chomp($configline);
12811: if ($configline) {
12812: my ($role,$perm)=split(/ /,$configline);
12813: if ($perm ne '') { $pr{$role}=$perm; }
12814: }
1.11 www 12815: }
1.448 albertel 12816: close($config);
1.11 www 12817: }
12818:
12819: # -------------------------------------------- Read plain texts for permissions
12820: {
1.448 albertel 12821: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12822:
12823: while (my $configline=<$config>) {
1.448 albertel 12824: chomp($configline);
12825: if ($configline) {
1.742 raeburn 12826: my ($short,@plain)=split(/:/,$configline);
12827: %{$prp{$short}} = ();
12828: if (@plain > 0) {
12829: $prp{$short}{'std'} = $plain[0];
12830: for (my $i=1; $i<@plain; $i++) {
12831: $prp{$short}{'alt'.$i} = $plain[$i];
12832: }
12833: }
1.448 albertel 12834: }
1.135 www 12835: }
1.448 albertel 12836: close($config);
1.135 www 12837: }
12838:
12839: # ---------------------------------------------------------- Read package table
12840: {
1.448 albertel 12841: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12842:
12843: while (my $configline=<$config>) {
1.483 albertel 12844: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12845: chomp($configline);
12846: my ($short,$plain)=split(/:/,$configline);
12847: my ($pack,$name)=split(/\&/,$short);
12848: if ($plain ne '') {
12849: $packagetab{$pack.'&'.$name.'&name'}=$name;
12850: $packagetab{$short}=$plain;
12851: }
1.11 www 12852: }
1.448 albertel 12853: close($config);
1.329 matthew 12854: }
12855:
1.1172.2.27 raeburn 12856: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12857:
1.1172.2.27 raeburn 12858: &load_loncaparevs();
12859:
12860: # ------------------------------------------------------- Read serverhostID table
12861:
12862: &load_serverhomeIDs();
1.1074 raeburn 12863:
1.1172.2.27 raeburn 12864: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12865: {
12866: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12867: if (-e $file) {
12868: my $parser = HTML::LCParser->new($file);
12869: while (my $token = $parser->get_token()) {
12870: if ($token->[0] eq 'S') {
12871: my $item = $token->[1];
12872: my $name = $token->[2]{'name'};
12873: my $value = $token->[2]{'value'};
12874: if ($item ne '' && $name ne '' && $value ne '') {
12875: my $release = $parser->get_text();
12876: $release =~ s/(^\s*|\s*$ )//gx;
12877: $needsrelease{$item.':'.$name.':'.$value} = $release;
12878: }
12879: }
12880: }
12881: }
1.1073 raeburn 12882: }
12883:
1.1138 raeburn 12884: # ---------------------------------------------------------- Read managers table
12885: {
12886: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12887: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12888: while (my $configline=<$config>) {
12889: chomp($configline);
12890: next if ($configline =~ /^\#/);
12891: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12892: $managerstab{$configline} = 1;
12893: }
12894: }
12895: close($config);
12896: }
12897: }
12898: }
12899:
1.329 matthew 12900: # ------------- set up temporary directory
12901: {
1.1117 foxr 12902: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12903:
1.11 www 12904: }
12905:
1.794 albertel 12906: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12907: 'compress_threshold'=> 20_000,
12908: });
1.185 www 12909:
1.281 www 12910: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12911: $dumpcount=0;
1.958 www 12912: $locknum=0;
1.22 www 12913:
1.163 harris41 12914: &logtouch();
1.672 albertel 12915: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12916: $readit=1;
1.564 albertel 12917: {
12918: use integer;
12919: my $test=(2**32)+1;
1.568 albertel 12920: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12921: &logthis(" Detected 64bit platform ($_64bit)");
12922: }
1.195 www 12923: }
1.1 albertel 12924: }
1.179 www 12925:
1.1 albertel 12926: 1;
1.191 harris41 12927: __END__
12928:
1.243 albertel 12929: =pod
12930:
1.191 harris41 12931: =head1 NAME
12932:
1.243 albertel 12933: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12934:
12935: =head1 SYNOPSIS
12936:
1.243 albertel 12937: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12938:
12939: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12940:
1.243 albertel 12941: Common parameters:
12942:
12943: =over 4
12944:
12945: =item *
12946:
12947: $uname : an internal username (if $cname expecting a course Id specifically)
12948:
12949: =item *
12950:
12951: $udom : a domain (if $cdom expecting a course's domain specifically)
12952:
12953: =item *
12954:
12955: $symb : a resource instance identifier
12956:
12957: =item *
12958:
12959: $namespace : the name of a .db file that contains the data needed or
12960: being set.
12961:
12962: =back
12963:
1.394 bowersj2 12964: =head1 OVERVIEW
1.191 harris41 12965:
1.394 bowersj2 12966: lonnet provides subroutines which interact with the
12967: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12968: about classes, users, and resources.
1.243 albertel 12969:
12970: For many of these objects you can also use this to store data about
12971: them or modify them in various ways.
1.191 harris41 12972:
1.394 bowersj2 12973: =head2 Symbs
1.191 harris41 12974:
1.394 bowersj2 12975: To identify a specific instance of a resource, LON-CAPA uses symbols
12976: or "symbs"X<symb>. These identifiers are built from the URL of the
12977: map, the resource number of the resource in the map, and the URL of
12978: the resource itself. The latter is somewhat redundant, but might help
12979: if maps change.
12980:
12981: An example is
12982:
12983: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12984:
12985: The respective map entry is
12986:
12987: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12988: title="Problem 2">
12989: </resource>
12990:
12991: Symbs are used by the random number generator, as well as to store and
12992: restore data specific to a certain instance of for example a problem.
12993:
12994: =head2 Storing And Retrieving Data
12995:
12996: X<store()>X<cstore()>X<restore()>Three of the most important functions
12997: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12998: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12999: is is the non-critical message twin of cstore. These functions are for
13000: handlers to store a perl hash to a user's permanent data space in an
13001: easy manner, and to retrieve it again on another call. It is expected
13002: that a handler would use this once at the beginning to retrieve data,
13003: and then again once at the end to send only the new data back.
13004:
13005: The data is stored in the user's data directory on the user's
13006: homeserver under the ID of the course.
13007:
13008: The hash that is returned by restore will have all of the previous
13009: value for all of the elements of the hash.
13010:
13011: Example:
13012:
13013: #creating a hash
13014: my %hash;
13015: $hash{'foo'}='bar';
13016:
13017: #storing it
13018: &Apache::lonnet::cstore(\%hash);
13019:
13020: #changing a value
13021: $hash{'foo'}='notbar';
13022:
13023: #adding a new value
13024: $hash{'bar'}='foo';
13025: &Apache::lonnet::cstore(\%hash);
13026:
13027: #retrieving the hash
13028: my %history=&Apache::lonnet::restore();
13029:
13030: #print the hash
13031: foreach my $key (sort(keys(%history))) {
13032: print("\%history{$key} = $history{$key}");
13033: }
13034:
13035: Will print out:
1.191 harris41 13036:
1.394 bowersj2 13037: %history{1:foo} = bar
13038: %history{1:keys} = foo:timestamp
13039: %history{1:timestamp} = 990455579
13040: %history{2:bar} = foo
13041: %history{2:foo} = notbar
13042: %history{2:keys} = foo:bar:timestamp
13043: %history{2:timestamp} = 990455580
13044: %history{bar} = foo
13045: %history{foo} = notbar
13046: %history{timestamp} = 990455580
13047: %history{version} = 2
13048:
13049: Note that the special hash entries C<keys>, C<version> and
13050: C<timestamp> were added to the hash. C<version> will be equal to the
13051: total number of versions of the data that have been stored. The
13052: C<timestamp> attribute will be the UNIX time the hash was
13053: stored. C<keys> is available in every historical section to list which
13054: keys were added or changed at a specific historical revision of a
13055: hash.
13056:
13057: B<Warning>: do not store the hash that restore returns directly. This
13058: will cause a mess since it will restore the historical keys as if the
13059: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13060:
1.394 bowersj2 13061: Calling convention:
1.191 harris41 13062:
1.1172.2.27 raeburn 13063: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13064: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13065:
1.394 bowersj2 13066: For more detailed information, see lonnet specific documentation.
1.191 harris41 13067:
1.394 bowersj2 13068: =head1 RETURN MESSAGES
1.191 harris41 13069:
1.394 bowersj2 13070: =over 4
1.191 harris41 13071:
1.394 bowersj2 13072: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13073:
1.394 bowersj2 13074: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13075: when the connection is brought back up
1.191 harris41 13076:
1.394 bowersj2 13077: =item * B<con_failed>: unable to contact remote host and unable to save message
13078: for later delivery
1.191 harris41 13079:
1.967 bisitz 13080: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13081:
1.394 bowersj2 13082: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13083: that was requested
1.191 harris41 13084:
1.243 albertel 13085: =back
1.191 harris41 13086:
1.243 albertel 13087: =head1 PUBLIC SUBROUTINES
1.191 harris41 13088:
1.243 albertel 13089: =head2 Session Environment Functions
1.191 harris41 13090:
1.243 albertel 13091: =over 4
1.191 harris41 13092:
1.394 bowersj2 13093: =item *
13094: X<appenv()>
1.949 raeburn 13095: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13096: the user envirnoment file, and will be restored for each access this
1.620 albertel 13097: user makes during this session, also modifies the %env for the current
1.949 raeburn 13098: process. Optional rolesarrayref - if defined contains a reference to an array
13099: of roles which are exempt from the restriction on modifying user.role entries
13100: in the user's environment.db and in %env.
1.191 harris41 13101:
13102: =item *
1.394 bowersj2 13103: X<delenv()>
1.987 raeburn 13104: B<delenv($delthis,$regexp)>: removes all items from the session
13105: environment file that begin with $delthis. If the
13106: optional second arg - $regexp - is true, $delthis is treated as a
13107: regular expression, otherwise \Q$delthis\E is used.
13108: The values are also deleted from the current processes %env.
1.191 harris41 13109:
1.795 albertel 13110: =item * get_env_multiple($name)
13111:
13112: gets $name from the %env hash, it seemlessly handles the cases where multiple
13113: values may be defined and end up as an array ref.
13114:
13115: returns an array of values
13116:
1.243 albertel 13117: =back
13118:
13119: =head2 User Information
1.191 harris41 13120:
1.243 albertel 13121: =over 4
1.191 harris41 13122:
13123: =item *
1.394 bowersj2 13124: X<queryauthenticate()>
13125: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13126: authentication scheme
13127:
13128: =item *
1.394 bowersj2 13129: X<authenticate()>
1.1073 raeburn 13130: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13131: authenticate user from domain's lib servers (first use the current
13132: one). C<$upass> should be the users password.
1.1073 raeburn 13133: $checkdefauth is optional (value is 1 if a check should be made to
13134: authenticate user using default authentication method, and allow
13135: account creation if username does not have account in the domain).
13136: $clientcancheckhost is optional (value is 1 if checking whether the
13137: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13138:
13139: =item *
1.394 bowersj2 13140: X<homeserver()>
13141: B<homeserver($uname,$udom)>: find the server which has
13142: the user's directory and files (there must be only one), this caches
13143: the answer, and also caches if there is a borken connection.
1.191 harris41 13144:
13145: =item *
1.394 bowersj2 13146: X<idget()>
13147: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13148: (IDs are a unique resource in a domain, there must be only 1 ID per
13149: username, and only 1 username per ID in a specific domain) (returns
13150: hash: id=>name,id=>name)
1.191 harris41 13151:
13152: =item *
1.394 bowersj2 13153: X<idrget()>
13154: B<idrget($udom,@unames)>: find the IDs behind a list of
13155: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13156:
13157: =item *
1.394 bowersj2 13158: X<idput()>
13159: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13160:
13161: =item *
1.394 bowersj2 13162: X<rolesinit()>
1.1169 droeschl 13163: B<rolesinit($udom,$username)>: get user privileges.
13164: returns user role, first access and timer interval hashes
1.243 albertel 13165:
13166: =item *
1.1171 droeschl 13167: X<privileged()>
13168: B<privileged($username,$domain)>: returns a true if user has a
13169: privileged and active role (i.e. su or dc), false otherwise.
13170:
13171: =item *
1.551 albertel 13172: X<getsection()>
13173: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13174: course $cname, return section name/number or '' for "not in course"
13175: and '-1' for "no section"
13176:
13177: =item *
1.394 bowersj2 13178: X<userenvironment()>
13179: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13180: passed in @what from the requested user's environment, returns a hash
13181:
1.858 raeburn 13182: =item *
13183: X<userlog_query()>
1.859 albertel 13184: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13185: activity.log file. %filters defines filters applied when parsing the
13186: log file. These can be start or end timestamps, or the type of action
13187: - log to look for Login or Logout events, check for Checkin or
13188: Checkout, role for role selection. The response is in the form
13189: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13190: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13191:
1.243 albertel 13192: =back
13193:
13194: =head2 User Roles
13195:
13196: =over 4
13197:
13198: =item *
13199:
1.1172.2.65 raeburn 13200: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13201: returns codes for allowed actions.
13202:
13203: The first argument is required, all others are optional.
13204:
13205: $priv is the privilege being checked.
13206: $uri contains additional information about what is being checked for access (e.g.,
13207: URL, course ID etc.).
13208: $symb is the unique resource instance identifier in a course; if needed,
13209: but not provided, it will be retrieved via a call to &symbread().
13210: $role is the role for which a priv is being checked (only used if priv is evb).
13211: $clientip is the user's IP address (only used when checking for access to portfolio
13212: files).
13213: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13214: prevents recursive calls to &allowed.
13215:
1.243 albertel 13216: F: full access
13217: U,I,K: authentication modes (cxx only)
13218: '': forbidden
13219: 1: user needs to choose course
13220: 2: browse allowed
1.766 albertel 13221: A: passphrase authentication needed
1.1172.2.65 raeburn 13222: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13223:
13224: =item *
13225:
1.1172.2.13 raeburn 13226: constructaccess($url,$setpriv) : check for access to construction space URL
13227:
13228: See if the owner domain and name in the URL match those in the
13229: expected environment. If so, return three element list
13230: ($ownername,$ownerdomain,$ownerhome).
13231:
13232: Otherwise return the null string.
13233:
13234: If second argument 'setpriv' is true, it assigns the privileges,
13235: and returns the same three element list, unless the owner has
13236: blocked "ad hoc" Domain Coordinator access to the Author Space,
13237: in which case the null string is returned.
13238:
13239: =item *
13240:
1.1172.2.84! raeburn 13241: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
! 13242: define a custom role rolename set privileges in format of lonTabs/roles.tab
! 13243: for system, domain, and course level. $uname and $udom are optional (current
! 13244: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13245:
13246: =item *
13247:
1.988 raeburn 13248: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13249: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13250: $type is Course (default) or Community.
1.988 raeburn 13251: If $forcedefault evaluates to true, text returned will be default
13252: text for $type. Otherwise, if this is a course, the text returned
13253: will be a custom name for the role (if defined in the course's
13254: environment). If no custom name is defined the default is returned.
13255:
1.832 raeburn 13256: =item *
13257:
1.1172.2.23 raeburn 13258: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13259: All arguments are optional. Returns a hash of a roles, either for
13260: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13261: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13262: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13263: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13264: For each key, value is set to colon-separated start and end times for
13265: the role. If no username and domain are specified, will default to
1.934 raeburn 13266: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13267: of role statuses (active, future or previous), roles
13268: (e.g., cc,in, st etc.) and domains of the roles which can be used
13269: to restrict the list of roles reported. If no array ref is
13270: provided for types, will default to return only active roles.
1.834 albertel 13271:
1.1172.2.13 raeburn 13272: =item *
13273:
13274: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13275: user: $uname:$udom has a role in the course: $cdom_$cnum.
13276:
13277: Additional optional arguments are: $type (if role checking is to be restricted
13278: to certain user status types -- previous (expired roles), active (currently
13279: available roles) or future (roles available in the future), and
13280: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13281: have active Domain Coordinator role in course's domain or in additional
13282: domains (specified in 'Domains to check for privileged users' in course
13283: environment -- set via: Course Settings -> Classlists and staff listing).
13284:
13285: =item *
13286:
13287: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13288: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13289: $possdomains and $possroles are optional array refs -- to domains to check and
13290: roles to check. If $possdomains is not specified, a dump will be done of the
13291: users' roles.db to check for a dc or su role in any domain. This can be
13292: time consuming if &privileged is called repeatedly (e.g., when displaying a
13293: classlist), so in such cases, supplying a $possdomains array is preferred, as
13294: this then allows &privileged_by_domain() to be used, which caches the identity
13295: of privileged users, eliminating the need for repeated calls to &dump().
13296:
13297: =item *
13298:
13299: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13300: where the outer hash keys are domains specified in the $possdomains array ref,
13301: next inner hash keys are privileged roles specified in the $roles array ref,
13302: and the innermost hash contains key = value pairs for username:domain = end:start
13303: for active or future "privileged" users with that role in that domain. To avoid
13304: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13305: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13306:
1.243 albertel 13307: =back
13308:
13309: =head2 User Modification
13310:
13311: =over 4
13312:
13313: =item *
13314:
1.957 raeburn 13315: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13316: user for the level given by URL. Optional start and end dates (leave empty
13317: string or zero for "no date")
1.191 harris41 13318:
13319: =item *
13320:
1.243 albertel 13321: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13322: change a users, password, possible return values are: ok,
13323: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13324: refused
1.191 harris41 13325:
13326: =item *
13327:
1.243 albertel 13328: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13329:
13330: =item *
13331:
1.1058 raeburn 13332: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13333: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13334:
13335: will update user information (firstname,middlename,lastname,generation,
13336: permanentemail), and if forceid is true, student/employee ID also.
13337: A user's institutional affiliation(s) can also be updated.
13338: User information fields will not be overwritten with empty entries
13339: unless the field is included in the $candelete array reference.
13340: This array is included when a single user is modified via "Manage Users",
13341: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13342:
13343: =item *
13344:
1.286 matthew 13345: modifystudent
13346:
1.957 raeburn 13347: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13348: The course id is resolved based on the current user's environment.
13349: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13350: associated with a course.
13351:
1.297 matthew 13352: This call is essentially a wrapper for lonnet::modifyuser and
13353: lonnet::modify_student_enrollment
1.286 matthew 13354:
13355: Inputs:
13356:
13357: =over 4
13358:
1.957 raeburn 13359: =item B<$udom> Student's loncapa domain
1.286 matthew 13360:
1.957 raeburn 13361: =item B<$uname> Student's loncapa login name
1.286 matthew 13362:
1.964 bisitz 13363: =item B<$uid> Student/Employee ID
1.286 matthew 13364:
1.957 raeburn 13365: =item B<$umode> Student's authentication mode
1.286 matthew 13366:
1.957 raeburn 13367: =item B<$upass> Student's password
1.286 matthew 13368:
1.957 raeburn 13369: =item B<$first> Student's first name
1.286 matthew 13370:
1.957 raeburn 13371: =item B<$middle> Student's middle name
1.286 matthew 13372:
1.957 raeburn 13373: =item B<$last> Student's last name
1.286 matthew 13374:
1.957 raeburn 13375: =item B<$gene> Student's generation
1.286 matthew 13376:
1.957 raeburn 13377: =item B<$usec> Student's section in course
1.286 matthew 13378:
13379: =item B<$end> Unix time of the roles expiration
13380:
13381: =item B<$start> Unix time of the roles start date
13382:
13383: =item B<$forceid> If defined, allow $uid to be changed
13384:
13385: =item B<$desiredhome> server to use as home server for student
13386:
1.957 raeburn 13387: =item B<$email> Student's permanent e-mail address
13388:
13389: =item B<$type> Type of enrollment (auto or manual)
13390:
1.963 raeburn 13391: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13392:
13393: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13394:
1.963 raeburn 13395: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13396:
1.963 raeburn 13397: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13398:
1.1172.2.19 raeburn 13399: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13400:
13401: =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 13402:
1.286 matthew 13403: =back
1.297 matthew 13404:
13405: =item *
13406:
13407: modify_student_enrollment
13408:
1.1172.2.31 raeburn 13409: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13410: 'role.request.course' must be defined for this function to proceed.
13411:
13412: Inputs:
13413:
13414: =over 4
13415:
1.1172.2.31 raeburn 13416: =item $udom, student's domain
1.297 matthew 13417:
1.1172.2.31 raeburn 13418: =item $uname, student's name
1.297 matthew 13419:
1.1172.2.31 raeburn 13420: =item $uid, student's user id
1.297 matthew 13421:
1.1172.2.31 raeburn 13422: =item $first, student's first name
1.297 matthew 13423:
13424: =item $middle
13425:
13426: =item $last
13427:
13428: =item $gene
13429:
13430: =item $usec
13431:
13432: =item $end
13433:
13434: =item $start
13435:
1.957 raeburn 13436: =item $type
13437:
13438: =item $locktype
13439:
13440: =item $cid
13441:
13442: =item $selfenroll
13443:
13444: =item $context
13445:
1.1172.2.19 raeburn 13446: =item $credits, number of credits student will earn from this class
13447:
1.1172.2.76 raeburn 13448: =item $instsec, institutional course section code for student
13449:
1.297 matthew 13450: =back
13451:
1.191 harris41 13452:
13453: =item *
13454:
1.243 albertel 13455: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13456: custom role; give a custom role to a user for the level given by URL. Specify
13457: name and domain of role author, and role name
1.191 harris41 13458:
13459: =item *
13460:
1.243 albertel 13461: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13462:
13463: =item *
13464:
1.243 albertel 13465: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13466:
13467: =back
13468:
13469: =head2 Course Infomation
13470:
13471: =over 4
1.191 harris41 13472:
13473: =item *
13474:
1.1118 foxr 13475: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13476: specified course id, including all environment settings for the
13477: course, the description of the course will be in the hash under the
13478: key 'description'
1.191 harris41 13479:
1.1118 foxr 13480: $options is an optional parameter that if supplied is a hash reference that controls
13481: what how this function works. It has the following key/values:
13482:
13483: =over 4
13484:
13485: =item freshen_cache
13486:
13487: If defined, and the environment cache for the course is valid, it is
13488: returned in the returned hash.
13489:
13490: =item one_time
13491:
13492: If defined, the last cache time is set to _now_
13493:
13494: =item user
13495:
13496: If defined, the supplied username is used instead of the current user.
13497:
13498:
13499: =back
13500:
1.191 harris41 13501: =item *
13502:
1.624 albertel 13503: resdata($name,$domain,$type,@which) : request for current parameter
13504: setting for a specific $type, where $type is either 'course' or 'user',
13505: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13506: answers for 10 minutes.
1.243 albertel 13507:
1.877 foxr 13508: =item *
13509:
13510: get_courseresdata($courseid, $domain) : dump the entire course resource
13511: data base, returning a hash that is keyed by the resource name and has
13512: values that are the resource value. I believe that the timestamps and
13513: versions are also returned.
13514:
1.1172.2.31 raeburn 13515: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13516: supplemental content area. This routine caches the number of files for
13517: 10 minutes.
13518:
1.243 albertel 13519: =back
13520:
13521: =head2 Course Modification
13522:
13523: =over 4
1.191 harris41 13524:
13525: =item *
13526:
1.243 albertel 13527: writecoursepref($courseid,%prefs) : write preferences (environment
13528: database) for a course
1.191 harris41 13529:
13530: =item *
13531:
1.1011 raeburn 13532: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13533:
13534: =item *
13535:
1.1038 raeburn 13536: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13537:
1.1167 droeschl 13538: =item *
13539:
13540: is_course($courseid), is_course($cdom, $cnum)
13541:
13542: Accepts either a combined $courseid (in the form of domain_courseid) or the
13543: two component version $cdom, $cnum. It checks if the specified course exists.
13544:
13545: Returns:
13546: undef if the course doesn't exist, otherwise
13547: in scalar context the combined courseid.
13548: in list context the two components of the course identifier, domain and
13549: courseid.
13550:
1.243 albertel 13551: =back
13552:
13553: =head2 Resource Subroutines
13554:
13555: =over 4
1.191 harris41 13556:
13557: =item *
13558:
1.243 albertel 13559: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13560:
13561: =item *
13562:
1.243 albertel 13563: repcopy($filename) : subscribes to the requested file, and attempts to
13564: replicate from the owning library server, Might return
1.607 raeburn 13565: 'unavailable', 'not_found', 'forbidden', 'ok', or
13566: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13567: resource. Expects the local filesystem pathname
13568: (/home/httpd/html/res/....)
13569:
13570: =back
13571:
13572: =head2 Resource Information
13573:
13574: =over 4
1.191 harris41 13575:
13576: =item *
13577:
1.1172.2.28 raeburn 13578: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13579: and returns the value of a variety of different possible values,
13580: $varname should be a request string, and the other parameters can be
13581: used to specify who and what one is asking about. Ordinarily, $cid
13582: does not need to be specified, as it is retrived from
13583: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13584: within lonuserstate::loadmap() when initializing a course, before
13585: $env{'request.course.id'} has been set, so it needs to be provided
13586: in that one case.
1.243 albertel 13587:
13588: Possible values for $varname are environment.lastname (or other item
13589: from the envirnment hash), user.name (or someother aspect about the
13590: user), resource.0.maxtries (or some other part and parameter of a
13591: resource)
1.204 albertel 13592:
13593: =item *
13594:
1.243 albertel 13595: directcondval($number) : get current value of a condition; reads from a state
13596: string
1.204 albertel 13597:
13598: =item *
13599:
1.243 albertel 13600: condval($condidx) : value of condition index based on state
1.204 albertel 13601:
13602: =item *
13603:
1.243 albertel 13604: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13605: resource's metadata, $what should be either a specific key, or either
13606: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13607: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13608:
13609: this function automatically caches all requests
1.191 harris41 13610:
13611: =item *
13612:
1.243 albertel 13613: metadata_query($query,$custom,$customshow) : make a metadata query against the
13614: network of library servers; returns file handle of where SQL and regex results
13615: will be stored for query
1.191 harris41 13616:
13617: =item *
13618:
1.1172.2.66 raeburn 13619: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13620: return symbolic list entry (all arguments optional).
13621:
13622: Args: filename is the filename (including path) for the file for which a symb
13623: is required; donotrecurse, if true will prevent calls to allowed() being made
13624: to check access status if more than one resource was found in the bighash
13625: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13626: a randompick); ignorecachednull, if true will prevent a symb of '' being
13627: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13628: cause possible symbs to be checked to determine if they are subject to content
13629: blocking, if so they will not be included as possible symbs; possibles is a
13630: ref to a hash, which, as a side effect, will be populated with all possible
13631: symbs (content blocking not tested).
13632:
1.243 albertel 13633: returns the data handle
1.191 harris41 13634:
13635: =item *
13636:
1.1172.2.17 raeburn 13637: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13638: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13639: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13640: on failure, user must be in a course, as it assumes the existence of
13641: the course initial hash, and uses $env('request.course.id'}. The third
13642: arg is an optional reference to a scalar. If this arg is passed in the
13643: call to symbverify, it will be set to 1 if the symb has been set to be
13644: encrypted; otherwise it will be null.
1.243 albertel 13645:
1.191 harris41 13646: =item *
13647:
1.243 albertel 13648: symbclean($symb) : removes versions numbers from a symb, returns the
13649: cleaned symb
1.191 harris41 13650:
13651: =item *
13652:
1.243 albertel 13653: is_on_map($uri) : checks if the $uri is somewhere on the current
13654: course map, user must be in a course for it to work.
1.191 harris41 13655:
13656: =item *
13657:
1.243 albertel 13658: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13659:
13660: =item *
13661:
1.243 albertel 13662: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13663: a random seed, all arguments are optional, if they aren't sent it uses the
13664: environment to derive them. Note: if symb isn't sent and it can't get one
13665: from &symbread it will use the current time as its return value
1.191 harris41 13666:
13667: =item *
13668:
1.243 albertel 13669: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13670: unfakeable, receipt
1.191 harris41 13671:
13672: =item *
13673:
1.620 albertel 13674: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13675:
13676: =item *
13677:
1.243 albertel 13678: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13679:
13680: =item *
13681:
1.243 albertel 13682: 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 13683:
13684: =item *
13685:
1.243 albertel 13686: 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 13687:
13688: =item *
13689:
1.243 albertel 13690: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13691:
13692: =item *
13693:
1.243 albertel 13694: devalidate($symb) : devalidate temporary spreadsheet calculations,
13695: forcing spreadsheet to reevaluate the resource scores next time.
13696:
1.1172.2.13 raeburn 13697: =item *
13698:
13699: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13700: when viewing in course context.
13701:
13702: input: six args -- filename (decluttered), course number, course domain,
13703: url, symb (if registered) and group (if this is a
13704: group item -- e.g., bulletin board, group page etc.).
13705:
13706: output: array of five scalars --
13707: $cfile -- url for file editing if editable on current server
13708: $home -- homeserver of resource (i.e., for author if published,
13709: or course if uploaded.).
13710: $switchserver -- 1 if server switch will be needed.
13711: $forceedit -- 1 if icon/link should be to go to edit mode
13712: $forceview -- 1 if icon/link should be to go to view mode
13713:
13714: =item *
13715:
13716: is_course_upload($file,$cnum,$cdom)
13717:
13718: Used in course context to determine if current file was uploaded to
13719: the course (i.e., would be found in /userfiles/docs on the course's
13720: homeserver.
13721:
13722: input: 3 args -- filename (decluttered), course number and course domain.
13723: output: boolean -- 1 if file was uploaded.
13724:
1.243 albertel 13725: =back
13726:
13727: =head2 Storing/Retreiving Data
13728:
13729: =over 4
1.191 harris41 13730:
13731: =item *
13732:
1.1172.2.64 raeburn 13733: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13734: permanently for this url; hashref needs to be given and should be a \%hashname;
13735: the remaining args aren't required and if they aren't passed or are '' they will
13736: be derived from the env (with the exception of $laststore, which is an
13737: optional arg used when a user's submission is stored in grading).
13738: $laststore is $version=$timestamp, where $version is the most recent version
13739: number retrieved for the corresponding $symb in the $namespace db file, and
13740: $timestamp is the timestamp for that transaction (UNIX time).
13741: $laststore is currently only passed when cstore() is called by
13742: structuretags::finalize_storage().
1.191 harris41 13743:
13744: =item *
13745:
1.1172.2.64 raeburn 13746: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13747: but uses critical subroutine
1.191 harris41 13748:
13749: =item *
13750:
1.243 albertel 13751: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13752: all args are optional
1.191 harris41 13753:
13754: =item *
13755:
1.717 albertel 13756: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13757: dumps the complete (or key matching regexp) namespace into a hash
13758: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13759: normally &store()ed into
13760:
13761: $range should be either an integer '100' (give me the first 100
13762: matching records)
13763: or be two integers sperated by a - with no spaces
13764: '30-50' (give me the 30th through the 50th matching
13765: records)
13766:
13767:
13768: =item *
13769:
1.1172.2.59 raeburn 13770: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13771: replaces a &store() version of data with a replacement set of data
13772: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13773: reference. If $tolog is true, the transaction is logged in the courselog
13774: with an action=PUTSTORE.
1.717 albertel 13775:
13776: =item *
13777:
1.243 albertel 13778: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13779: works very similar to store/cstore, but all data is stored in a
13780: temporary location and can be reset using tmpreset, $storehash should
13781: be a hash reference, returns nothing on success
1.191 harris41 13782:
13783: =item *
13784:
1.243 albertel 13785: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13786: similar to restore, but all data is stored in a temporary location and
13787: can be reset using tmpreset. Returns a hash of values on success,
13788: error string otherwise.
1.191 harris41 13789:
13790: =item *
13791:
1.243 albertel 13792: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13793: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13794:
13795: =item *
13796:
1.243 albertel 13797: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13798: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13799:
13800: =item *
13801:
1.243 albertel 13802: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13803: namesp ($udom and $uname are optional)
1.191 harris41 13804:
13805: =item *
13806:
1.702 albertel 13807: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13808: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13809: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13810:
1.702 albertel 13811: $range should be either an integer '100' (give me the first 100
13812: matching records)
13813: or be two integers sperated by a - with no spaces
13814: '30-50' (give me the 30th through the 50th matching
13815: records)
1.449 matthew 13816: =item *
13817:
13818: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13819: $store can be a scalar, an array reference, or if the amount to be
13820: incremented is > 1, a hash reference.
13821:
13822: ($udom and $uname are optional)
1.191 harris41 13823:
13824: =item *
13825:
1.243 albertel 13826: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13827: ($udom and $uname are optional)
1.191 harris41 13828:
13829: =item *
13830:
1.243 albertel 13831: cput($namespace,$storehash,$udom,$uname) : critical put
13832: ($udom and $uname are optional)
1.191 harris41 13833:
13834: =item *
13835:
1.748 albertel 13836: newput($namespace,$storehash,$udom,$uname) :
13837:
13838: Attempts to store the items in the $storehash, but only if they don't
13839: currently exist, if this succeeds you can be certain that you have
13840: successfully created a new key value pair in the $namespace db.
13841:
13842:
13843: Args:
13844: $namespace: name of database to store values to
13845: $storehash: hashref to store to the db
13846: $udom: (optional) domain of user containing the db
13847: $uname: (optional) name of user caontaining the db
13848:
13849: Returns:
13850: 'ok' -> succeeded in storing all keys of $storehash
13851: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13852: least <key> already existed in the db (other
13853: requested keys may also already exist)
1.967 bisitz 13854: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13855: 'con_lost' -> unable to contact request server
13856: 'refused' -> action was not allowed by remote machine
13857:
13858:
13859: =item *
13860:
1.243 albertel 13861: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13862: reference filled in from namesp (encrypts the return communication)
13863: ($udom and $uname are optional)
1.191 harris41 13864:
13865: =item *
13866:
1.243 albertel 13867: log($udom,$name,$home,$message) : write to permanent log for user; use
13868: critical subroutine
13869:
1.806 raeburn 13870: =item *
13871:
1.860 raeburn 13872: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13873: array reference filled in from namespace found in domain level on either
13874: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13875:
13876: =item *
13877:
1.860 raeburn 13878: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13879: domain level either on specified domain server ($uhome) or primary domain
13880: server ($udom and $uhome are optional)
1.806 raeburn 13881:
1.943 raeburn 13882: =item *
13883:
1.1172.2.35 raeburn 13884: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13885: for: authentication, language, quotas, timezone, date locale, and portal URL in
13886: the target domain.
13887:
13888: May also include additional key => value pairs for the following groups:
13889:
13890: =over
13891:
13892: =item
13893: disk quotas (MB allocated by default to portfolios and authoring spaces).
13894:
13895: =over
13896:
13897: =item defaultquota, authorquota
13898:
13899: =back
13900:
13901: =item
13902: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13903: portfolio for users).
13904:
13905: =over
13906:
13907: =item
13908: aboutme, blog, webdav, portfolio
13909:
13910: =back
13911:
13912: =item
13913: requestcourses: ability to request courses, and how requests are processed.
13914:
13915: =over
13916:
13917: =item
1.1172.2.37 raeburn 13918: official, unofficial, community, textbook
1.1172.2.35 raeburn 13919:
13920: =back
13921:
13922: =item
13923: inststatus: types of institutional affiliation, and order in which they are displayed.
13924:
13925: =over
13926:
13927: =item
1.1172.2.44 raeburn 13928: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13929:
13930: =back
13931:
13932: =item
13933: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13934: for course's uploaded content.
13935:
13936: =over
13937:
13938: =item
1.1172.2.68 raeburn 13939: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13940: communityquota, textbookquota
1.1172.2.35 raeburn 13941:
13942: =back
13943:
13944: =item
13945: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13946: on your servers.
13947:
13948: =over
13949:
13950: =item
13951: remotesessions, hostedsessions
13952:
13953: =back
13954:
13955: =back
13956:
13957: In cases where a domain coordinator has never used the "Set Domain Configuration"
13958: utility to create a configuration.db file on a domain's primary library server
13959: only the following domain defaults: auth_def, auth_arg_def, lang_def
13960: -- corresponding values are authentication type (internal, krb4, krb5,
13961: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13962: will be available. Values are retrieved from cache (if current), unless the
13963: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13964: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13965:
13966: Typical usage:
1.943 raeburn 13967:
1.1172.2.35 raeburn 13968: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13969:
1.243 albertel 13970: =back
13971:
13972: =head2 Network Status Functions
13973:
13974: =over 4
1.191 harris41 13975:
13976: =item *
13977:
1.1137 raeburn 13978: dirlist() : return directory list based on URI (first arg).
13979:
13980: Inputs: 1 required, 5 optional.
13981:
13982: =over
13983:
13984: =item
13985: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13986:
13987: =item
13988: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13989:
13990: =item
13991: $username - username of user/course to be listed. Extracted from $uri if absent.
13992:
13993: =item
13994: $getpropath - boolean: 1 if prepend path using &propath().
13995:
13996: =item
13997: $getuserdir - boolean: 1 if prepend path for "userfiles".
13998:
13999: =item
14000: $alternateRoot - path to prepend in place of path from $uri.
14001:
14002: =back
14003:
14004: Returns: Array of up to two items.
14005:
14006: =over
14007:
14008: a reference to an array of files/subdirectories
14009:
14010: =over
14011:
14012: Each element in the array of files/subdirectories is a & separated list of
14013: item name and the result of running stat on the item. If dirlist was requested
14014: for a file instead of a directory, the item name will be ''. For a directory
14015: listing, if the item is a metadata file, the element will end &N&M
14016: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14017: default copyright set (1).
14018:
14019: =back
14020:
14021: a scalar containing error condition (if encountered).
14022:
14023: =over
14024:
14025: =item
14026: no_host (no homeserver identified for $username:$domain).
14027:
14028: =item
14029: no_such_host (server contacted for listing not identified as valid host).
14030:
14031: =item
14032: con_lost (connection to remote server failed).
14033:
14034: =item
14035: refused (invalid $username:$domain received on lond side).
14036:
14037: =item
14038: no_such_dir (directory at specified path on lond side does not exist).
14039:
14040: =item
14041: empty (directory at specified path on lond side is empty).
14042:
14043: =over
14044:
14045: This is currently not encountered because the &ls3, &ls2,
14046: &ls (_handler) routines on the lond side do not filter out
14047: . and .. from a directory listing.
14048:
14049: =back
14050:
14051: =back
14052:
14053: =back
1.191 harris41 14054:
14055: =item *
14056:
1.243 albertel 14057: spareserver() : find server with least workload from spare.tab
14058:
1.986 foxr 14059:
14060: =item *
14061:
14062: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14063: if there is no corresponding loncapa host.
14064:
1.243 albertel 14065: =back
14066:
1.986 foxr 14067:
1.243 albertel 14068: =head2 Apache Request
14069:
14070: =over 4
1.191 harris41 14071:
14072: =item *
14073:
1.243 albertel 14074: ssi($url,%hash) : server side include, does a complete request cycle on url to
14075: localhost, posts hash
14076:
14077: =back
14078:
14079: =head2 Data to String to Data
14080:
14081: =over 4
1.191 harris41 14082:
14083: =item *
14084:
1.243 albertel 14085: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14086: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14087:
14088: =item *
14089:
1.243 albertel 14090: hashref2str($hashref) : convert a hashref into a string complete with
14091: escaping and '=' and '&' separators, supports elements that are
14092: arrayrefs and hashrefs
1.191 harris41 14093:
14094: =item *
14095:
1.243 albertel 14096: arrayref2str($arrayref) : convert an arrayref into a string complete
14097: with escaping and '&' separators, supports elements that are arrayrefs
14098: and hashrefs
1.191 harris41 14099:
14100: =item *
14101:
1.243 albertel 14102: str2hash($string) : convert string to hash using unescaping and
14103: splitting on '=' and '&', supports elements that are arrayrefs and
14104: hashrefs
1.191 harris41 14105:
14106: =item *
14107:
1.243 albertel 14108: str2array($string) : convert string to hash using unescaping and
14109: splitting on '&', supports elements that are arrayrefs and hashrefs
14110:
14111: =back
14112:
14113: =head2 Logging Routines
14114:
14115:
14116: These routines allow one to make log messages in the lonnet.log and
14117: lonnet.perm logfiles.
1.191 harris41 14118:
1.1119 foxr 14119: =over 4
14120:
1.191 harris41 14121: =item *
14122:
1.243 albertel 14123: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14124:
14125: =item *
14126:
1.243 albertel 14127: logthis() : append message to the normal lonnet.log file, it gets
14128: preiodically rolled over and deleted.
1.191 harris41 14129:
14130: =item *
14131:
1.243 albertel 14132: logperm() : append a permanent message to lonnet.perm.log, this log
14133: file never gets deleted by any automated portion of the system, only
14134: messages of critical importance should go in here.
14135:
1.1119 foxr 14136:
1.243 albertel 14137: =back
14138:
14139: =head2 General File Helper Routines
14140:
14141: =over 4
1.191 harris41 14142:
14143: =item *
14144:
1.481 raeburn 14145: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14146: (a) files in /uploaded
14147: (i) If a local copy of the file exists -
14148: compares modification date of local copy with last-modified date for
14149: definitive version stored on home server for course. If local copy is
14150: stale, requests a new version from the home server and stores it.
14151: If the original has been removed from the home server, then local copy
14152: is unlinked.
14153: (ii) If local copy does not exist -
14154: requests the file from the home server and stores it.
14155:
14156: If $caller is 'uploadrep':
14157: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14158: for request for files originally uploaded via DOCS.
14159: - returns 'ok' if fresh local copy now available, -1 otherwise.
14160:
14161: Otherwise:
14162: This indicates a call from the content generation phase of the request.
14163: - returns the entire contents of the file or -1.
14164:
14165: (b) files in /res
14166: - returns the entire contents of a file or -1;
14167: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14168:
1.712 albertel 14169:
14170: =item *
14171:
14172: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14173: reference
14174:
14175: returns either a stat() list of data about the file or an empty list
14176: if the file doesn't exist or couldn't find out about it (connection
14177: problems or user unknown)
14178:
1.191 harris41 14179: =item *
14180:
1.243 albertel 14181: filelocation($dir,$file) : returns file system location of a file
14182: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14183: directory that relative $file lookups are to looked in ($dir of /a/dir
14184: and a file of ../bob will become /a/bob)
1.191 harris41 14185:
14186: =item *
14187:
14188: hreflocation($dir,$file) : returns file system location or a URL; same as
14189: filelocation except for hrefs
14190:
14191: =item *
14192:
1.1172.2.49 raeburn 14193: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14194: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14195:
1.243 albertel 14196: =back
14197:
1.608 albertel 14198: =head2 Usererfile file routines (/uploaded*)
14199:
14200: =over 4
14201:
14202: =item *
14203:
14204: userfileupload(): main rotine for putting a file in a user or course's
14205: filespace, arguments are,
14206:
1.620 albertel 14207: formname - required - this is the name of the element in $env where the
1.608 albertel 14208: filename, and the contents of the file to create/modifed exist
1.620 albertel 14209: the filename is in $env{'form.'.$formname.'.filename'} and the
14210: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14211: context - if coursedoc, store the file in the course of the active role
14212: of the current user;
14213: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14214: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14215: subdir - required - subdirectory to put the file in under ../userfiles/
14216: if undefined, it will be placed in "unknown"
14217:
14218: (This routine calls clean_filename() to remove any dangerous
14219: characters from the filename, and then calls finuserfileupload() to
14220: complete the transaction)
14221:
14222: returns either the url of the uploaded file (/uploaded/....) if successful
14223: and /adm/notfound.html if unsuccessful
14224:
14225: =item *
14226:
14227: clean_filename(): routine for cleaing a filename up for storage in
14228: userfile space, argument is:
14229:
14230: filename - proposed filename
14231:
14232: returns: the new clean filename
14233:
14234: =item *
14235:
1.1090 raeburn 14236: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14237: userspace, probably shouldn't be called directly
14238:
14239: docuname: username or courseid of destination for the file
14240: docudom: domain of user/course of destination for the file
14241: formname: same as for userfileupload()
1.1090 raeburn 14242: fname: filename (including subdirectories) for the file
14243: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14244: allfiles: reference to hash used to store objects found by parser
14245: codebase: reference to hash used for codebases of java objects found by parser
14246: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14247: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14248: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14249: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14250: context: if 'overwrite', will move the uploaded file from its temporary location to
14251: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14252: mimetype: reference to scalar to accommodate mime type determined
14253: from File::MMagic if $parser = parse.
1.608 albertel 14254:
14255: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14256: and /adm/notfound.html if unsuccessful (or an error message if context
14257: was 'overwrite').
14258:
1.608 albertel 14259:
14260: =item *
14261:
14262: renameuserfile(): renames an existing userfile to a new name
14263:
14264: Args:
14265: docuname: username or courseid of destination for the file
14266: docudom: domain of user/course of destination for the file
14267: old: current file name (including any subdirs under userfiles)
14268: new: desired file name (including any subdirs under userfiles)
14269:
14270: =item *
14271:
14272: mkdiruserfile(): creates a directory is a userfiles dir
14273:
14274: Args:
14275: docuname: username or courseid of destination for the file
14276: docudom: domain of user/course of destination for the file
14277: dir: dir to create (including any subdirs under userfiles)
14278:
14279: =item *
14280:
14281: removeuserfile(): removes a file that exists in userfiles
14282:
14283: Args:
14284: docuname: username or courseid of destination for the file
14285: docudom: domain of user/course of destination for the file
14286: fname: filname to delete (including any subdirs under userfiles)
14287:
14288: =item *
14289:
14290: removeuploadedurl(): convience function for removeuserfile()
14291:
14292: Args:
14293: url: a full /uploaded/... url to delete
14294:
1.747 albertel 14295: =item *
14296:
14297: get_portfile_permissions():
14298: Args:
14299: domain: domain of user or course contain the portfolio files
14300: user: name of user or num of course contain the portfolio files
14301: Returns:
14302: hashref of a dump of the proper file_permissions.db
14303:
14304:
14305: =item *
14306:
14307: get_access_controls():
14308:
14309: Args:
14310: current_permissions: the hash ref returned from get_portfile_permissions()
14311: group: (optional) the group you want the files associated with
14312: file: (optional) the file you want access info on
14313:
14314: Returns:
1.749 raeburn 14315: a hash (keys are file names) of hashes containing
14316: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14317: values are XML containing access control settings (see below)
1.747 albertel 14318:
14319: Internal notes:
14320:
1.749 raeburn 14321: access controls are stored in file_permissions.db as key=value pairs.
14322: key -> path to file/file_name\0uniqueID:scope_end_start
14323: where scope -> public,guest,course,group,domains or users.
14324: end -> UNIX time for end of access (0 -> no end date)
14325: start -> UNIX time for start of access
14326:
14327: value -> XML description of access control
14328: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14329: <start></start>
14330: <end></end>
14331:
14332: <password></password> for scope type = guest
14333:
14334: <domain></domain> for scope type = course or group
14335: <number></number>
14336: <roles id="">
14337: <role></role>
14338: <access></access>
14339: <section></section>
14340: <group></group>
14341: </roles>
14342:
14343: <dom></dom> for scope type = domains
14344:
14345: <users> for scope type = users
14346: <user>
14347: <uname></uname>
14348: <udom></udom>
14349: </user>
14350: </users>
14351: </scope>
14352:
14353: Access data is also aggregated for each file in an additional key=value pair:
14354: key -> path to file/file_name\0accesscontrol
14355: value -> reference to hash
14356: hash contains key = value pairs
14357: where key = uniqueID:scope_end_start
14358: value = UNIX time record was last updated
14359:
14360: Used to improve speed of look-ups of access controls for each file.
14361:
14362: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14363:
1.1172.2.13 raeburn 14364: =item *
14365:
1.749 raeburn 14366: modify_access_controls():
14367:
14368: Modifies access controls for a portfolio file
14369: Args
14370: 1. file name
14371: 2. reference to hash of required changes,
14372: 3. domain
14373: 4. username
14374: where domain,username are the domain of the portfolio owner
14375: (either a user or a course)
14376:
14377: Returns:
14378: 1. result of additions or updates ('ok' or 'error', with error message).
14379: 2. result of deletions ('ok' or 'error', with error message).
14380: 3. reference to hash of any new or updated access controls.
14381: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14382: key = integer (inbound ID)
1.1172.2.13 raeburn 14383: value = uniqueID
14384:
14385: =item *
14386:
14387: get_timebased_id():
14388:
14389: Attempts to get a unique timestamp-based suffix for use with items added to a
14390: course via the Course Editor (e.g., folders, composite pages,
14391: group bulletin boards).
14392:
14393: Args: (first three required; six others optional)
14394:
14395: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14396: docssequence, or name of group
14397:
14398: 2. keyid (alphanumeric): name of temporary locking key in hash,
14399: e.g., num, boardids
14400:
14401: 3. namespace: name of gdbm file used to store suffixes already assigned;
14402: file will be named nohist_namespace.db
14403:
14404: 4. cdom: domain of course; default is current course domain from %env
14405:
14406: 5. cnum: course number; default is current course number from %env
14407:
14408: 6. idtype: set to concat if an additional digit is to be appended to the
14409: unix timestamp to form the suffix, if the plain timestamp is already
14410: in use. Default is to not do this, but simply increment the unix
14411: timestamp by 1 until a unique key is obtained.
14412:
14413: 7. who: holder of locking key; defaults to user:domain for user.
14414:
14415: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14416: retrying); default is 3.
14417:
14418: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14419:
14420: Returns:
14421:
14422: 1. suffix obtained (numeric)
14423:
14424: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14425:
14426: 3. error: contains (localized) error message if an error occurred.
14427:
1.747 albertel 14428:
1.608 albertel 14429: =back
14430:
1.243 albertel 14431: =head2 HTTP Helper Routines
14432:
14433: =over 4
14434:
1.191 harris41 14435: =item *
14436:
14437: escape() : unpack non-word characters into CGI-compatible hex codes
14438:
14439: =item *
14440:
14441: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14442:
1.243 albertel 14443: =back
14444:
14445: =head1 PRIVATE SUBROUTINES
14446:
14447: =head2 Underlying communication routines (Shouldn't call)
14448:
14449: =over 4
14450:
14451: =item *
14452:
14453: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14454:
14455: =item *
14456:
14457: reply() : uses subreply to send a message to remote machine, logs all failures
14458:
14459: =item *
14460:
14461: critical() : passes a critical message to another server; if cannot
14462: get through then place message in connection buffer directory and
14463: returns con_delayed, if incapable of saving message, returns
14464: con_failed
14465:
14466: =item *
14467:
14468: reconlonc() : tries to reconnect lonc client processes.
14469:
14470: =back
14471:
14472: =head2 Resource Access Logging
14473:
14474: =over 4
14475:
14476: =item *
14477:
14478: flushcourselogs() : flush (save) buffer logs and access logs
14479:
14480: =item *
14481:
14482: courselog($what) : save message for course in hash
14483:
14484: =item *
14485:
14486: courseacclog($what) : save message for course using &courselog(). Perform
14487: special processing for specific resource types (problems, exams, quizzes, etc).
14488:
1.191 harris41 14489: =item *
14490:
14491: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14492: as a PerlChildExitHandler
1.243 albertel 14493:
14494: =back
14495:
14496: =head2 Other
14497:
14498: =over 4
14499:
14500: =item *
14501:
14502: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14503:
14504: =back
14505:
14506: =cut
1.877 foxr 14507:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>