Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.85
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.85! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.84 2016/10/23 12:21:47 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;
1.1172.2.85! raeburn 6139: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
! 6140: return %returnhash;
! 6141: }
1.667 albertel 6142: foreach my $item (split(/\&/,$rep)) {
6143: my ($key,$value)=split(/=/,$item);
6144: $returnhash{&unescape($key)}=&thaw_unescape($value);
6145: }
6146: return %returnhash;
6147: }
6148:
1.1113 raeburn 6149: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6150: sub tmpdel {
6151: my ($token,$server)=@_;
6152: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6153: return &reply("tmpdel:$token",$server);
6154: }
6155:
1.1172.2.13 raeburn 6156: # ------------------------------------------------------------ get_timebased_id
6157:
6158: sub get_timebased_id {
6159: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6160: $maxtries) = @_;
6161: my ($newid,$error,$dellock);
6162: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6163: return ('','ok','invalid call to get suffix');
6164: }
6165:
6166: # set defaults for any optional args for which values were not supplied
6167: if ($who eq '') {
6168: $who = $env{'user.name'}.':'.$env{'user.domain'};
6169: }
6170: if (!$locktries) {
6171: $locktries = 3;
6172: }
6173: if (!$maxtries) {
6174: $maxtries = 10;
6175: }
6176:
6177: if (($cdom eq '') || ($cnum eq '')) {
6178: if ($env{'request.course.id'}) {
6179: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6180: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6181: }
6182: if (($cdom eq '') || ($cnum eq '')) {
6183: return ('','ok','call to get suffix not in course context');
6184: }
6185: }
6186:
6187: # construct locking item
6188: my $lockhash = {
6189: $prefix."\0".'locked_'.$keyid => $who,
6190: };
6191: my $tries = 0;
6192:
6193: # attempt to get lock on nohist_$namespace file
6194: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6195: while (($gotlock ne 'ok') && $tries <$locktries) {
6196: $tries ++;
6197: sleep 1;
6198: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6199: }
6200:
6201: # attempt to get unique identifier, based on current timestamp
6202: if ($gotlock eq 'ok') {
6203: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6204: my $id = time;
6205: $newid = $id;
1.1172.2.56 raeburn 6206: if ($idtype eq 'addcode') {
6207: $newid .= &sixnum_code();
6208: }
1.1172.2.13 raeburn 6209: my $idtries = 0;
6210: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6211: if ($idtype eq 'concat') {
6212: $newid = $id.$idtries;
1.1172.2.56 raeburn 6213: } elsif ($idtype eq 'addcode') {
6214: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6215: } else {
6216: $newid ++;
6217: }
6218: $idtries ++;
6219: }
6220: if (!exists($inuse{$prefix."\0".$newid})) {
6221: my %new_item = (
6222: $prefix."\0".$newid => $who,
6223: );
6224: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6225: $cdom,$cnum);
6226: if ($putresult ne 'ok') {
6227: undef($newid);
6228: $error = 'error saving new item: '.$putresult;
6229: }
6230: } else {
1.1172.2.56 raeburn 6231: undef($newid);
1.1172.2.13 raeburn 6232: $error = ('error: no unique suffix available for the new item ');
6233: }
6234: # remove lock
6235: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6236: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6237: } else {
6238: $error = "error: could not obtain lockfile\n";
6239: $dellock = 'ok';
1.1172.2.58 raeburn 6240: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6241: $dellock = 'nolock';
6242: }
1.1172.2.13 raeburn 6243: }
6244: return ($newid,$dellock,$error);
6245: }
6246:
1.1172.2.56 raeburn 6247: sub sixnum_code {
6248: my $code;
6249: for (0..6) {
6250: $code .= int( rand(9) );
6251: }
6252: return $code;
6253: }
6254:
1.765 albertel 6255: # -------------------------------------------------- portfolio access checking
6256:
6257: sub portfolio_access {
1.1172.2.77 raeburn 6258: my ($requrl,$clientip) = @_;
1.765 albertel 6259: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6260: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6261: if ($result) {
6262: my %setters;
6263: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6264: my ($startblock,$endblock) =
6265: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6266: if ($startblock && $endblock) {
6267: return 'B';
6268: }
6269: } else {
6270: my ($startblock,$endblock) =
6271: &Apache::loncommon::blockcheck(\%setters,'port');
6272: if ($startblock && $endblock) {
6273: return 'B';
6274: }
6275: }
6276: }
1.765 albertel 6277: if ($result eq 'ok') {
1.766 albertel 6278: return 'F';
1.765 albertel 6279: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6280: return 'A';
1.765 albertel 6281: }
1.766 albertel 6282: return '';
1.765 albertel 6283: }
6284:
6285: sub get_portfolio_access {
1.1172.2.77 raeburn 6286: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6287:
6288: if (!ref($access_hash)) {
6289: my $current_perms = &get_portfile_permissions($udom,$unum);
6290: my %access_controls = &get_access_controls($current_perms,$group,
6291: $file_name);
6292: $access_hash = $access_controls{$file_name};
6293: }
6294:
1.1172.2.77 raeburn 6295: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6296: my $now = time;
6297: if (ref($access_hash) eq 'HASH') {
6298: foreach my $key (keys(%{$access_hash})) {
6299: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6300: if ($start > $now) {
6301: next;
6302: }
6303: if ($end && $end<$now) {
6304: next;
6305: }
6306: if ($scope eq 'public') {
6307: $public = $key;
6308: last;
6309: } elsif ($scope eq 'guest') {
6310: $guest = $key;
6311: } elsif ($scope eq 'domains') {
6312: push(@domains,$key);
6313: } elsif ($scope eq 'users') {
6314: push(@users,$key);
6315: } elsif ($scope eq 'course') {
6316: push(@courses,$key);
6317: } elsif ($scope eq 'group') {
6318: push(@groups,$key);
1.1172.2.77 raeburn 6319: } elsif ($scope eq 'ip') {
6320: push(@ips,$key);
1.765 albertel 6321: }
6322: }
6323: if ($public) {
6324: return 'ok';
1.1172.2.77 raeburn 6325: } elsif (@ips > 0) {
6326: my $allowed;
6327: foreach my $ipkey (@ips) {
6328: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6329: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6330: $allowed = 1;
6331: last;
6332: }
6333: }
6334: }
6335: if ($allowed) {
6336: return 'ok';
6337: }
1.765 albertel 6338: }
6339: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6340: if ($guest) {
6341: return $guest;
6342: }
6343: } else {
6344: if (@domains > 0) {
6345: foreach my $domkey (@domains) {
6346: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6347: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6348: return 'ok';
6349: }
6350: }
6351: }
6352: }
6353: if (@users > 0) {
6354: foreach my $userkey (@users) {
1.865 raeburn 6355: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6356: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6357: if (ref($item) eq 'HASH') {
6358: if (($item->{'uname'} eq $env{'user.name'}) &&
6359: ($item->{'udom'} eq $env{'user.domain'})) {
6360: return 'ok';
6361: }
6362: }
6363: }
6364: }
1.765 albertel 6365: }
6366: }
6367: my %roleshash;
6368: my @courses_and_groups = @courses;
6369: push(@courses_and_groups,@groups);
6370: if (@courses_and_groups > 0) {
6371: my (%allgroups,%allroles);
6372: my ($start,$end,$role,$sec,$group);
6373: foreach my $envkey (%env) {
1.1060 raeburn 6374: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6375: my $cid = $2.'_'.$3;
6376: if ($1 eq 'gr') {
6377: $group = $4;
6378: $allgroups{$cid}{$group} = $env{$envkey};
6379: } else {
6380: if ($4 eq '') {
6381: $sec = 'none';
6382: } else {
6383: $sec = $4;
6384: }
6385: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6386: }
1.811 albertel 6387: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6388: my $cid = $2.'_'.$3;
6389: if ($4 eq '') {
6390: $sec = 'none';
6391: } else {
6392: $sec = $4;
6393: }
6394: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6395: }
6396: }
6397: if (keys(%allroles) == 0) {
6398: return;
6399: }
6400: foreach my $key (@courses_and_groups) {
6401: my %content = %{$$access_hash{$key}};
6402: my $cnum = $content{'number'};
6403: my $cdom = $content{'domain'};
6404: my $cid = $cdom.'_'.$cnum;
6405: if (!exists($allroles{$cid})) {
6406: next;
6407: }
6408: foreach my $role_id (keys(%{$content{'roles'}})) {
6409: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6410: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6411: my @status = @{$content{'roles'}{$role_id}{'access'}};
6412: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6413: foreach my $role (keys(%{$allroles{$cid}})) {
6414: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6415: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6416: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6417: if (grep/^all$/,@sections) {
6418: return 'ok';
6419: } else {
6420: if (grep/^$sec$/,@sections) {
6421: return 'ok';
6422: }
6423: }
6424: }
6425: }
6426: if (keys(%{$allgroups{$cid}}) == 0) {
6427: if (grep/^none$/,@groups) {
6428: return 'ok';
6429: }
6430: } else {
6431: if (grep/^all$/,@groups) {
6432: return 'ok';
6433: }
6434: foreach my $group (keys(%{$allgroups{$cid}})) {
6435: if (grep/^$group$/,@groups) {
6436: return 'ok';
6437: }
6438: }
6439: }
6440: }
6441: }
6442: }
6443: }
6444: }
6445: if ($guest) {
6446: return $guest;
6447: }
6448: }
6449: }
6450: return;
6451: }
6452:
6453: sub course_group_datechecker {
6454: my ($dates,$now,$status) = @_;
6455: my ($start,$end) = split(/\./,$dates);
6456: if (!$start && !$end) {
6457: return 'ok';
6458: }
6459: if (grep/^active$/,@{$status}) {
6460: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6461: return 'ok';
6462: }
6463: }
6464: if (grep/^previous$/,@{$status}) {
6465: if ($end > $now ) {
6466: return 'ok';
6467: }
6468: }
6469: if (grep/^future$/,@{$status}) {
6470: if ($start > $now) {
6471: return 'ok';
6472: }
6473: }
6474: return;
6475: }
6476:
6477: sub parse_portfolio_url {
6478: my ($url) = @_;
6479:
6480: my ($type,$udom,$unum,$group,$file_name);
6481:
1.823 albertel 6482: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6483: $type = 1;
6484: $udom = $1;
6485: $unum = $2;
6486: $file_name = $3;
1.823 albertel 6487: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6488: $type = 2;
6489: $udom = $1;
6490: $unum = $2;
6491: $group = $3;
6492: $file_name = $3.'/'.$4;
6493: }
6494: if (wantarray) {
6495: return ($type,$udom,$unum,$file_name,$group);
6496: }
6497: return $type;
6498: }
6499:
6500: sub is_portfolio_url {
6501: my ($url) = @_;
6502: return scalar(&parse_portfolio_url($url));
6503: }
6504:
1.798 raeburn 6505: sub is_portfolio_file {
6506: my ($file) = @_;
1.820 raeburn 6507: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6508: return 1;
6509: }
6510: return;
6511: }
6512:
1.976 raeburn 6513: sub usertools_access {
1.1084 raeburn 6514: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6515: my ($access,%tools);
6516: if ($context eq '') {
6517: $context = 'tools';
6518: }
6519: if ($context eq 'requestcourses') {
6520: %tools = (
6521: official => 1,
6522: unofficial => 1,
1.1006 raeburn 6523: community => 1,
1.1172.2.37 raeburn 6524: textbook => 1,
1.985 raeburn 6525: );
1.1172.2.9 raeburn 6526: } elsif ($context eq 'requestauthor') {
6527: %tools = (
6528: requestauthor => 1,
6529: );
1.985 raeburn 6530: } else {
6531: %tools = (
6532: aboutme => 1,
6533: blog => 1,
1.1172.2.6 raeburn 6534: webdav => 1,
1.985 raeburn 6535: portfolio => 1,
6536: );
6537: }
1.976 raeburn 6538: return if (!defined($tools{$tool}));
6539:
1.1172.2.35 raeburn 6540: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6541: $udom = $env{'user.domain'};
6542: $uname = $env{'user.name'};
6543: }
6544:
1.978 raeburn 6545: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6546: if ($action ne 'reload') {
1.985 raeburn 6547: if ($context eq 'requestcourses') {
6548: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6549: } elsif ($context eq 'requestauthor') {
6550: return $env{'environment.canrequest.author'};
1.985 raeburn 6551: } else {
6552: return $env{'environment.availabletools.'.$tool};
6553: }
6554: }
1.976 raeburn 6555: }
6556:
1.1172.2.9 raeburn 6557: my ($toolstatus,$inststatus,$envkey);
6558: if ($context eq 'requestauthor') {
6559: $envkey = $context;
6560: } else {
6561: $envkey = $context.'.'.$tool;
6562: }
1.976 raeburn 6563:
1.985 raeburn 6564: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6565: ($action ne 'reload')) {
1.1172.2.9 raeburn 6566: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6567: $inststatus = $env{'environment.inststatus'};
6568: } else {
1.1084 raeburn 6569: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6570: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6571: $inststatus = $userenvref->{'inststatus'};
6572: } else {
1.1172.2.9 raeburn 6573: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6574: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6575: $inststatus = $userenv{'inststatus'};
6576: }
1.976 raeburn 6577: }
6578:
6579: if ($toolstatus ne '') {
6580: if ($toolstatus) {
6581: $access = 1;
6582: } else {
6583: $access = 0;
6584: }
6585: return $access;
6586: }
6587:
1.1084 raeburn 6588: my ($is_adv,%domdef);
6589: if (ref($is_advref) eq 'HASH') {
6590: $is_adv = $is_advref->{'is_adv'};
6591: } else {
6592: $is_adv = &is_advanced_user($udom,$uname);
6593: }
6594: if (ref($domdefref) eq 'HASH') {
6595: %domdef = %{$domdefref};
6596: } else {
6597: %domdef = &get_domain_defaults($udom);
6598: }
1.976 raeburn 6599: if (ref($domdef{$tool}) eq 'HASH') {
6600: if ($is_adv) {
6601: if ($domdef{$tool}{'_LC_adv'} ne '') {
6602: if ($domdef{$tool}{'_LC_adv'}) {
6603: $access = 1;
6604: } else {
6605: $access = 0;
6606: }
6607: return $access;
6608: }
6609: }
6610: if ($inststatus ne '') {
6611: my ($hasaccess,$hasnoaccess);
6612: foreach my $affiliation (split(/:/,$inststatus)) {
6613: if ($domdef{$tool}{$affiliation} ne '') {
6614: if ($domdef{$tool}{$affiliation}) {
6615: $hasaccess = 1;
6616: } else {
6617: $hasnoaccess = 1;
6618: }
6619: }
6620: }
6621: if ($hasaccess || $hasnoaccess) {
6622: if ($hasaccess) {
6623: $access = 1;
6624: } elsif ($hasnoaccess) {
6625: $access = 0;
6626: }
6627: return $access;
6628: }
6629: } else {
6630: if ($domdef{$tool}{'default'} ne '') {
6631: if ($domdef{$tool}{'default'}) {
6632: $access = 1;
6633: } elsif ($domdef{$tool}{'default'} == 0) {
6634: $access = 0;
6635: }
6636: return $access;
6637: }
6638: }
6639: } else {
1.1172.2.6 raeburn 6640: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6641: $access = 1;
6642: } else {
6643: $access = 0;
6644: }
1.976 raeburn 6645: return $access;
6646: }
6647: }
6648:
1.1050 raeburn 6649: sub is_course_owner {
6650: my ($cdom,$cnum,$udom,$uname) = @_;
6651: if (($udom eq '') || ($uname eq '')) {
6652: $udom = $env{'user.domain'};
6653: $uname = $env{'user.name'};
6654: }
6655: unless (($udom eq '') || ($uname eq '')) {
6656: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6657: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6658: return 1;
6659: } else {
6660: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6661: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6662: return 1;
6663: }
6664: }
6665: }
6666: }
6667: return;
6668: }
6669:
1.976 raeburn 6670: sub is_advanced_user {
6671: my ($udom,$uname) = @_;
1.1085 raeburn 6672: if ($udom ne '' && $uname ne '') {
6673: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6674: if (wantarray) {
6675: return ($env{'user.adv'},$env{'user.author'});
6676: } else {
6677: return $env{'user.adv'};
6678: }
1.1085 raeburn 6679: }
6680: }
1.976 raeburn 6681: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6682: my %allroles;
1.1128 raeburn 6683: my ($is_adv,$is_author);
1.976 raeburn 6684: foreach my $role (keys(%roleshash)) {
6685: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6686: my $area = '/'.$tdomain.'/'.$trest;
6687: if ($sec ne '') {
6688: $area .= '/'.$sec;
6689: }
6690: if (($area ne '') && ($trole ne '')) {
6691: my $spec=$trole.'.'.$area;
6692: if ($trole =~ /^cr\//) {
6693: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6694: } elsif ($trole ne 'gr') {
6695: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6696: }
1.1128 raeburn 6697: if ($trole eq 'au') {
6698: $is_author = 1;
6699: }
1.976 raeburn 6700: }
6701: }
6702: foreach my $role (keys(%allroles)) {
6703: last if ($is_adv);
6704: foreach my $item (split(/:/,$allroles{$role})) {
6705: if ($item ne '') {
6706: my ($privilege,$restrictions)=split(/&/,$item);
6707: if ($privilege eq 'adv') {
6708: $is_adv = 1;
6709: last;
6710: }
6711: }
6712: }
6713: }
1.1128 raeburn 6714: if (wantarray) {
6715: return ($is_adv,$is_author);
6716: }
1.976 raeburn 6717: return $is_adv;
6718: }
1.798 raeburn 6719:
1.1035 raeburn 6720: sub check_can_request {
1.1036 raeburn 6721: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6722: my $canreq = 0;
6723: my ($types,$typename) = &Apache::loncommon::course_types();
6724: my @options = ('approval','validate','autolimit');
6725: my $optregex = join('|',@options);
6726: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6727: foreach my $type (@{$types}) {
6728: if (&usertools_access($env{'user.name'},
6729: $env{'user.domain'},
6730: $type,undef,'requestcourses')) {
6731: $canreq ++;
1.1036 raeburn 6732: if (ref($request_domains) eq 'HASH') {
6733: push(@{$request_domains->{$type}},$env{'user.domain'});
6734: }
1.1035 raeburn 6735: if ($dom eq $env{'user.domain'}) {
6736: $can_request->{$type} = 1;
6737: }
6738: }
6739: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6740: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6741: if (@curr > 0) {
1.1036 raeburn 6742: foreach my $item (@curr) {
6743: if (ref($request_domains) eq 'HASH') {
6744: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6745: if ($otherdom ne '') {
6746: if (ref($request_domains->{$type}) eq 'ARRAY') {
6747: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6748: push(@{$request_domains->{$type}},$otherdom);
6749: }
6750: } else {
6751: push(@{$request_domains->{$type}},$otherdom);
6752: }
6753: }
6754: }
6755: }
6756: unless($dom eq $env{'user.domain'}) {
6757: $canreq ++;
1.1035 raeburn 6758: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6759: $can_request->{$type} = 1;
6760: }
6761: }
6762: }
6763: }
6764: }
6765: }
6766: return $canreq;
6767: }
6768:
1.341 www 6769: # ---------------------------------------------- Custom access rule evaluation
6770:
6771: sub customaccess {
6772: my ($priv,$uri)=@_;
1.807 albertel 6773: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6774: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6775: $udom = &LONCAPA::clean_domain($udom);
6776: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6777: my $access=0;
1.800 albertel 6778: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6779: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6780: if ($type eq 'user') {
6781: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6782: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6783: if ($tdom) {
6784: if ($tdom ne $env{'user.domain'}) { next; }
6785: }
1.896 albertel 6786: if ($tuname) {
6787: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6788: }
6789: $access=($effect eq 'allow');
6790: last;
6791: }
6792: } else {
6793: if ($role) {
6794: if ($role ne $urole) { next; }
6795: }
6796: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6797: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6798: if ($tdom) {
6799: if ($tdom ne $udom) { next; }
6800: }
6801: if ($tcrs) {
6802: if ($tcrs ne $ucrs) { next; }
6803: }
6804: if ($tsec) {
6805: if ($tsec ne $usec) { next; }
6806: }
6807: $access=($effect eq 'allow');
6808: last;
6809: }
6810: if ($realm eq '' && $role eq '') {
6811: $access=($effect eq 'allow');
6812: }
1.402 bowersj2 6813: }
1.341 www 6814: }
6815: return $access;
6816: }
6817:
1.103 harris41 6818: # ------------------------------------------------- Check for a user privilege
1.12 www 6819:
6820: sub allowed {
1.1172.2.65 raeburn 6821: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6822: my $ver_orguri=$uri;
1.439 www 6823: $uri=&deversion($uri);
1.152 www 6824: my $orguri=$uri;
1.52 www 6825: $uri=&declutter($uri);
1.809 raeburn 6826:
1.810 raeburn 6827: if ($priv eq 'evb') {
6828: # Evade communication block restrictions for specified role in a course
6829: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6830: return $1;
6831: } else {
6832: return;
6833: }
6834: }
6835:
1.620 albertel 6836: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6837: # Free bre access to adm and meta resources
1.775 albertel 6838: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6839: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6840: && ($priv eq 'bre')) {
1.14 www 6841: return 'F';
1.159 www 6842: }
6843:
1.545 banghart 6844: # Free bre access to user's own portfolio contents
1.714 raeburn 6845: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6846: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6847: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6848: my %setters;
6849: my ($startblock,$endblock) =
6850: &Apache::loncommon::blockcheck(\%setters,'port');
6851: if ($startblock && $endblock) {
6852: return 'B';
6853: } else {
6854: return 'F';
6855: }
1.545 banghart 6856: }
6857:
1.762 raeburn 6858: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6859: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6860: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6861: if (exists($env{'request.course.id'})) {
6862: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6863: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6864: if (($domain eq $cdom) && ($name eq $cnum)) {
6865: my $courseprivid=$env{'request.course.id'};
6866: $courseprivid=~s/\_/\//;
6867: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6868: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6869: return $1;
1.762 raeburn 6870: } else {
6871: if ($env{'request.course.sec'}) {
6872: $courseprivid.='/'.$env{'request.course.sec'};
6873: }
6874: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6875: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6876: return $2;
6877: }
1.714 raeburn 6878: }
6879: }
6880: }
6881: }
6882:
1.159 www 6883: # Free bre to public access
6884:
6885: if ($priv eq 'bre') {
1.238 www 6886: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6887: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6888: return 'F';
6889: }
1.238 www 6890: if ($copyright eq 'priv') {
6891: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6892: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6893: return '';
6894: }
6895: }
6896: if ($copyright eq 'domain') {
6897: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6898: unless (($env{'user.domain'} eq $1) ||
6899: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6900: return '';
6901: }
1.262 matthew 6902: }
1.620 albertel 6903: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6904: # Library role, so allow browsing of resources in this domain.
6905: return 'F';
1.238 www 6906: }
1.341 www 6907: if ($copyright eq 'custom') {
6908: unless (&customaccess($priv,$uri)) { return ''; }
6909: }
1.14 www 6910: }
1.264 matthew 6911: # Domain coordinator is trying to create a course
1.620 albertel 6912: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6913: # uri is the requested domain in this case.
6914: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6915: # a role of dc for the domain in question.
1.620 albertel 6916: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6917: }
1.29 www 6918:
1.52 www 6919: my $thisallowed='';
6920: my $statecond=0;
6921: my $courseprivid='';
6922:
1.1039 raeburn 6923: my $ownaccess;
1.1043 raeburn 6924: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6925: if (($priv eq 'bro') && ($env{'user.author'})) {
6926: if ($uri eq '') {
6927: $ownaccess = 1;
6928: } else {
6929: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6930: my $udom = $env{'user.domain'};
6931: my $uname = $env{'user.name'};
6932: if ($uri =~ m{^\Q$udom\E/?$}) {
6933: $ownaccess = 1;
1.1040 raeburn 6934: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6935: unless ($uri =~ m{\.\./}) {
6936: $ownaccess = 1;
6937: }
6938: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6939: my $now = time;
6940: if ($uri =~ m{^([^/]+)/?$}) {
6941: my $adom = $1;
6942: foreach my $key (keys(%env)) {
1.1042 raeburn 6943: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6944: my ($start,$end) = split('.',$env{$key});
6945: if (($now >= $start) && (!$end || $end < $now)) {
6946: $ownaccess = 1;
6947: last;
6948: }
6949: }
6950: }
6951: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6952: my $adom = $1;
6953: my $aname = $2;
1.1042 raeburn 6954: foreach my $role ('ca','aa') {
6955: if ($env{"user.role.$role./$adom/$aname"}) {
6956: my ($start,$end) =
6957: split('.',$env{"user.role.$role./$adom/$aname"});
6958: if (($now >= $start) && (!$end || $end < $now)) {
6959: $ownaccess = 1;
6960: last;
6961: }
1.1039 raeburn 6962: }
6963: }
6964: }
6965: }
6966: }
6967: }
6968: }
6969:
1.52 www 6970: # Course
6971:
1.620 albertel 6972: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6973: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6974: $thisallowed.=$1;
6975: }
1.52 www 6976: }
1.29 www 6977:
1.52 www 6978: # Domain
6979:
1.620 albertel 6980: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6981: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6982: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6983: $thisallowed.=$1;
6984: }
1.12 www 6985: }
1.52 www 6986:
1.1141 raeburn 6987: # User who is not author or co-author might still be able to edit
6988: # resource of an author in the domain (e.g., if Domain Coordinator).
6989: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6990: (&allowed('mdc',$env{'request.course.id'}))) {
6991: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6992: $thisallowed.=$1;
6993: }
6994: }
6995:
1.52 www 6996: # Course: uri itself is a course
1.66 www 6997: my $courseuri=$uri;
6998: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6999: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7000:
1.620 albertel 7001: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7002: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7003: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7004: $thisallowed.=$1;
7005: }
1.12 www 7006: }
1.29 www 7007:
1.665 albertel 7008: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7009: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7010: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7011: $thisallowed='';
1.671 raeburn 7012: my ($match)=&is_on_map($uri);
7013: if ($match) {
7014: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7015: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 7016: my $value = $1;
7017: if ($noblockcheck) {
7018: $thisallowed.=$value;
1.1162 raeburn 7019: } else {
1.1172.2.65 raeburn 7020: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7021: if (@blockers > 0) {
7022: $thisallowed = 'B';
7023: } else {
7024: $thisallowed.=$value;
7025: }
1.1162 raeburn 7026: }
1.671 raeburn 7027: }
7028: } else {
1.705 albertel 7029: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7030: if ($refuri) {
7031: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7032: $thisallowed='F';
1.671 raeburn 7033: } else {
7034: $refuri=&declutter($refuri);
7035: my ($match) = &is_on_map($refuri);
7036: if ($match) {
1.1172.2.65 raeburn 7037: if ($noblockcheck) {
1.1162 raeburn 7038: $thisallowed='F';
1.1172.2.65 raeburn 7039: } else {
7040: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7041: if (@blockers > 0) {
7042: $thisallowed = 'B';
7043: } else {
7044: $thisallowed='F';
7045: }
1.1162 raeburn 7046: }
1.671 raeburn 7047: }
1.669 raeburn 7048: }
1.671 raeburn 7049: }
7050: }
1.314 www 7051: }
1.492 albertel 7052:
1.766 albertel 7053: if ($priv eq 'bre'
7054: && $thisallowed ne 'F'
7055: && $thisallowed ne '2'
7056: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7057: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7058: }
7059:
1.52 www 7060: # Full access at system, domain or course-wide level? Exit.
1.29 www 7061: if ($thisallowed=~/F/) {
7062: return 'F';
7063: }
7064:
1.52 www 7065: # If this is generating or modifying users, exit with special codes
1.29 www 7066:
1.643 www 7067: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7068: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7069: my ($audom,$auname)=split('/',$uri);
1.643 www 7070: # no author name given, so this just checks on the general right to make a co-author in this domain
7071: unless ($auname) { return $thisallowed; }
7072: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7073: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7074: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7075: ($audom ne $env{'request.role.domain'}))) { return ''; }
7076: }
1.52 www 7077: return $thisallowed;
7078: }
7079: #
1.103 harris41 7080: # Gathered so far: system, domain and course wide privileges
1.52 www 7081: #
7082: # Course: See if uri or referer is an individual resource that is part of
7083: # the course
7084:
1.620 albertel 7085: if ($env{'request.course.id'}) {
1.232 www 7086:
1.620 albertel 7087: $courseprivid=$env{'request.course.id'};
7088: if ($env{'request.course.sec'}) {
7089: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7090: }
7091: $courseprivid=~s/\_/\//;
7092: my $checkreferer=1;
1.232 www 7093: my ($match,$cond)=&is_on_map($uri);
7094: if ($match) {
7095: $statecond=$cond;
1.620 albertel 7096: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7097: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7098: my $value = $1;
7099: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7100: if ($noblockcheck) {
1.1162 raeburn 7101: $thisallowed.=$value;
1.1172.2.65 raeburn 7102: } else {
7103: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7104: if (@blockers > 0) {
7105: $thisallowed = 'B';
7106: } else {
7107: $thisallowed.=$value;
7108: }
1.1162 raeburn 7109: }
7110: } else {
7111: $thisallowed.=$value;
7112: }
1.52 www 7113: $checkreferer=0;
7114: }
1.29 www 7115: }
1.83 www 7116:
1.148 www 7117: if ($checkreferer) {
1.620 albertel 7118: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7119: unless ($refuri) {
1.800 albertel 7120: foreach my $key (keys(%env)) {
7121: if ($key=~/^httpref\..*\*/) {
7122: my $pattern=$key;
1.156 www 7123: $pattern=~s/^httpref\.\/res\///;
1.148 www 7124: $pattern=~s/\*/\[\^\/\]\+/g;
7125: $pattern=~s/\//\\\//g;
1.152 www 7126: if ($orguri=~/$pattern/) {
1.800 albertel 7127: $refuri=$env{$key};
1.148 www 7128: }
7129: }
1.191 harris41 7130: }
1.148 www 7131: }
1.232 www 7132:
1.148 www 7133: if ($refuri) {
1.152 www 7134: $refuri=&declutter($refuri);
1.232 www 7135: my ($match,$cond)=&is_on_map($refuri);
7136: if ($match) {
7137: my $refstatecond=$cond;
1.620 albertel 7138: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7139: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7140: my $value = $1;
7141: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7142: if ($noblockcheck) {
1.1162 raeburn 7143: $thisallowed.=$value;
1.1172.2.65 raeburn 7144: } else {
7145: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7146: if (@blockers > 0) {
7147: $thisallowed = 'B';
7148: } else {
7149: $thisallowed.=$value;
7150: }
1.1162 raeburn 7151: }
7152: } else {
7153: $thisallowed.=$value;
7154: }
1.53 www 7155: $uri=$refuri;
7156: $statecond=$refstatecond;
1.52 www 7157: }
7158: }
1.148 www 7159: }
1.29 www 7160: }
1.52 www 7161: }
1.29 www 7162:
1.52 www 7163: #
1.103 harris41 7164: # Gathered now: all privileges that could apply, and condition number
1.52 www 7165: #
7166: #
7167: # Full or no access?
7168: #
1.29 www 7169:
1.52 www 7170: if ($thisallowed=~/F/) {
7171: return 'F';
7172: }
1.29 www 7173:
1.52 www 7174: unless ($thisallowed) {
7175: return '';
7176: }
1.29 www 7177:
1.52 www 7178: # Restrictions exist, deal with them
7179: #
7180: # C:according to course preferences
7181: # R:according to resource settings
7182: # L:unless locked
7183: # X:according to user session state
7184: #
7185:
7186: # Possibly locked functionality, check all courses
1.54 www 7187: # Locks might take effect only after 10 minutes cache expiration for other
7188: # courses, and 2 minutes for current course
1.52 www 7189:
7190: my $envkey;
7191: if ($thisallowed=~/L/) {
1.1000 raeburn 7192: foreach $envkey (keys(%env)) {
1.54 www 7193: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7194: my $courseid=$2;
7195: my $roleid=$1.'.'.$2;
1.92 www 7196: $courseid=~s/^\///;
1.54 www 7197: my $expiretime=600;
1.620 albertel 7198: if ($env{'request.role'} eq $roleid) {
1.54 www 7199: $expiretime=120;
7200: }
7201: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7202: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7203: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7204: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7205: }
1.620 albertel 7206: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7207: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7208: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7209: &log($env{'user.domain'},$env{'user.name'},
7210: $env{'user.home'},
1.57 www 7211: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7212: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7213: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7214: return '';
7215: }
7216: }
1.620 albertel 7217: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7218: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7219: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7220: &log($env{'user.domain'},$env{'user.name'},
7221: $env{'user.home'},
1.57 www 7222: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7223: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7224: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7225: return '';
7226: }
7227: }
7228: }
1.29 www 7229: }
1.52 www 7230: }
7231:
7232: #
7233: # Rest of the restrictions depend on selected course
7234: #
7235:
1.620 albertel 7236: unless ($env{'request.course.id'}) {
1.766 albertel 7237: if ($thisallowed eq 'A') {
7238: return 'A';
1.814 raeburn 7239: } elsif ($thisallowed eq 'B') {
7240: return 'B';
1.766 albertel 7241: } else {
7242: return '1';
7243: }
1.52 www 7244: }
1.29 www 7245:
1.52 www 7246: #
7247: # Now user is definitely in a course
7248: #
1.53 www 7249:
7250:
7251: # Course preferences
7252:
7253: if ($thisallowed=~/C/) {
1.620 albertel 7254: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7255: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7256: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7257: =~/\Q$rolecode\E/) {
1.1103 raeburn 7258: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7259: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7260: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7261: $env{'request.course.id'});
7262: }
1.237 www 7263: return '';
7264: }
7265:
1.620 albertel 7266: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7267: =~/\Q$unamedom\E/) {
1.1103 raeburn 7268: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7269: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7270: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7271: $env{'request.course.id'});
7272: }
1.54 www 7273: return '';
7274: }
1.53 www 7275: }
7276:
7277: # Resource preferences
7278:
7279: if ($thisallowed=~/R/) {
1.620 albertel 7280: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7281: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7282: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7283: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7284: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7285: }
7286: return '';
1.54 www 7287: }
1.53 www 7288: }
1.30 www 7289:
1.246 www 7290: # Restricted by state or randomout?
1.30 www 7291:
1.52 www 7292: if ($thisallowed=~/X/) {
1.620 albertel 7293: if ($env{'acc.randomout'}) {
1.579 albertel 7294: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7295: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7296: return '';
7297: }
1.247 www 7298: }
7299: if (&condval($statecond)) {
1.52 www 7300: return '2';
7301: } else {
7302: return '';
7303: }
7304: }
1.30 www 7305:
1.766 albertel 7306: if ($thisallowed eq 'A') {
7307: return 'A';
1.814 raeburn 7308: } elsif ($thisallowed eq 'B') {
7309: return 'B';
1.766 albertel 7310: }
1.52 www 7311: return 'F';
1.232 www 7312: }
1.1162 raeburn 7313:
1.1172.2.13 raeburn 7314: # ------------------------------------------- Check construction space access
7315:
7316: sub constructaccess {
7317: my ($url,$setpriv)=@_;
7318:
7319: # We do not allow editing of previous versions of files
7320: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7321:
7322: # Get username and domain from URL
7323: my ($ownername,$ownerdomain,$ownerhome);
7324:
7325: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 7326: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 7327:
7328: # The URL does not really point to any authorspace, forget it
7329: unless (($ownername) && ($ownerdomain)) { return ''; }
7330:
7331: # Now we need to see if the user has access to the authorspace of
7332: # $ownername at $ownerdomain
7333:
7334: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7335: # Real author for this?
7336: $ownerhome = $env{'user.home'};
7337: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7338: return ($ownername,$ownerdomain,$ownerhome);
7339: }
7340: } else {
7341: # Co-author for this?
7342: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7343: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7344: $ownerhome = &homeserver($ownername,$ownerdomain);
7345: return ($ownername,$ownerdomain,$ownerhome);
7346: }
7347: }
7348:
7349: # We don't have any access right now. If we are not possibly going to do anything about this,
7350: # we might as well leave
7351: unless ($setpriv) { return ''; }
7352:
7353: # Backdoor access?
7354: my $allowed=&allowed('eco',$ownerdomain);
7355: # Nope
7356: unless ($allowed) { return ''; }
7357: # Looks like we may have access, but could be locked by the owner of the construction space
7358: if ($allowed eq 'U') {
7359: my %blocked=&get('environment',['domcoord.author'],
7360: $ownerdomain,$ownername);
7361: # Is blocked by owner
7362: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7363: }
7364: if (($allowed eq 'F') || ($allowed eq 'U')) {
7365: # Grant temporary access
7366: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7367: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7368: if (!$update) { $update = $then; }
7369: my $refresh=$env{'user.refresh.time'};
7370: if (!$refresh) { $refresh = $update; }
7371: my $now = time;
7372: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7373: $now,'ca','constructaccess');
7374: $ownerhome = &homeserver($ownername,$ownerdomain);
7375: return($ownername,$ownerdomain,$ownerhome);
7376: }
7377: # No business here
7378: return '';
7379: }
7380:
1.1172.2.66 raeburn 7381: # ----------------------------------------------------------- Content Blocking
7382:
7383: {
7384: # Caches for faster Course Contents display where content blocking
7385: # is in operation (i.e., interval param set) for timed quiz.
7386: #
7387: # User for whom data are being temporarily cached.
7388: my $cacheduser='';
7389: # Cached blockers for this user (a hash of blocking items).
7390: my %cachedblockers=();
7391: # When the data were last cached.
7392: my $cachedlast='';
7393:
7394: sub load_all_blockers {
7395: my ($uname,$udom,$blocks)=@_;
7396: if (($uname ne '') && ($udom ne '')) {
7397: if (($cacheduser eq $uname.':'.$udom) &&
7398: (abs($cachedlast-time)<5)) {
7399: return;
7400: }
7401: }
7402: $cachedlast=time;
7403: $cacheduser=$uname.':'.$udom;
7404: %cachedblockers = &get_commblock_resources($blocks);
7405: }
7406:
1.1162 raeburn 7407: sub get_comm_blocks {
7408: my ($cdom,$cnum) = @_;
7409: if ($cdom eq '' || $cnum eq '') {
7410: return unless ($env{'request.course.id'});
7411: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7412: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7413: }
7414: my %commblocks;
7415: my $hashid=$cdom.'_'.$cnum;
7416: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7417: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7418: %commblocks = %{$blocksref};
7419: } else {
7420: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7421: my $cachetime = 600;
7422: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7423: }
7424: return %commblocks;
7425: }
7426:
1.1172.2.66 raeburn 7427: sub get_commblock_resources {
7428: my ($blocks) = @_;
7429: my %blockers = ();
7430: return %blockers unless ($env{'request.course.id'});
7431: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7432: my %commblocks;
7433: if (ref($blocks) eq 'HASH') {
7434: %commblocks = %{$blocks};
7435: } else {
7436: %commblocks = &get_comm_blocks();
7437: }
1.1172.2.66 raeburn 7438: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7439: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7440: return %blockers unless (ref($navmap));
7441: my $now = time;
1.1162 raeburn 7442: foreach my $block (keys(%commblocks)) {
7443: if ($block =~ /^(\d+)____(\d+)$/) {
7444: my ($start,$end) = ($1,$2);
7445: if ($start <= $now && $end >= $now) {
7446: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7447: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7448: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7449: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7450: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7451: }
7452: }
7453: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7454: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7455: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7456: }
7457: }
7458: }
7459: }
7460: }
7461: } elsif ($block =~ /^firstaccess____(.+)$/) {
7462: my $item = $1;
1.1163 raeburn 7463: my @to_test;
1.1162 raeburn 7464: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7465: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7466: my @interval;
7467: my $type = 'map';
7468: if ($item eq 'course') {
7469: $type = 'course';
7470: @interval=&EXT("resource.0.interval");
7471: } else {
7472: if ($item =~ /___\d+___/) {
7473: $type = 'resource';
7474: @interval=&EXT("resource.0.interval",$item);
7475: if (ref($navmap)) {
7476: my $res = $navmap->getBySymb($item);
7477: push(@to_test,$res);
7478: }
1.1162 raeburn 7479: } else {
1.1172.2.66 raeburn 7480: my $mapsymb = &symbread($item,1);
7481: if ($mapsymb) {
7482: if (ref($navmap)) {
7483: my $mapres = $navmap->getBySymb($mapsymb);
7484: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7485: foreach my $res (@to_test) {
7486: my $symb = $res->symb();
7487: next if ($symb eq $mapsymb);
7488: if ($symb ne '') {
7489: @interval=&EXT("resource.0.interval",$symb);
7490: if ($interval[1] eq 'map') {
7491: last;
1.1162 raeburn 7492: }
7493: }
7494: }
7495: }
7496: }
7497: }
1.1172.2.66 raeburn 7498: }
7499: if ($interval[0] =~ /^\d+$/) {
7500: my $first_access;
7501: if ($type eq 'resource') {
7502: $first_access=&get_first_access($interval[1],$item);
7503: } elsif ($type eq 'map') {
7504: $first_access=&get_first_access($interval[1],undef,$item);
7505: } else {
7506: $first_access=&get_first_access($interval[1]);
7507: }
7508: if ($first_access) {
7509: my $timesup = $first_access+$interval[0];
7510: if ($timesup > $now) {
7511: my $activeblock;
7512: foreach my $res (@to_test) {
7513: if ($res->answerable()) {
7514: $activeblock = 1;
7515: last;
7516: }
7517: }
7518: if ($activeblock) {
7519: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7520: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7521: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7522: }
7523: }
7524: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7525: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7526: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7527: }
1.1162 raeburn 7528: }
7529: }
7530: }
7531: }
7532: }
7533: }
7534: }
7535: }
7536: }
1.1172.2.66 raeburn 7537: return %blockers;
1.1162 raeburn 7538: }
7539:
1.1172.2.66 raeburn 7540: sub has_comm_blocking {
7541: my ($priv,$symb,$uri,$blocks) = @_;
7542: my @blockers;
7543: return unless ($env{'request.course.id'});
7544: return unless ($priv eq 'bre');
7545: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7546: return if ($env{'request.state'} eq 'construct');
7547: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7548: return unless (keys(%cachedblockers) > 0);
7549: my (%possibles,@symbs);
7550: if (!$symb) {
7551: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7552: }
1.1172.2.66 raeburn 7553: if ($symb) {
7554: @symbs = ($symb);
7555: } elsif (keys(%possibles)) {
7556: @symbs = keys(%possibles);
7557: }
7558: my $noblock;
7559: foreach my $symb (@symbs) {
7560: last if ($noblock);
7561: my ($map,$resid,$resurl)=&decode_symb($symb);
7562: foreach my $block (keys(%cachedblockers)) {
7563: if ($block =~ /^firstaccess____(.+)$/) {
7564: my $item = $1;
7565: if (($item eq $map) || ($item eq $symb)) {
7566: $noblock = 1;
7567: last;
7568: }
1.1162 raeburn 7569: }
1.1172.2.66 raeburn 7570: if (ref($cachedblockers{$block}) eq 'HASH') {
7571: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7572: if ($cachedblockers{$block}{'resources'}{$symb}) {
7573: unless (grep(/^\Q$block\E$/,@blockers)) {
7574: push(@blockers,$block);
7575: }
7576: }
7577: }
7578: }
7579: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7580: if ($cachedblockers{$block}{'maps'}{$map}) {
7581: unless (grep(/^\Q$block\E$/,@blockers)) {
7582: push(@blockers,$block);
7583: }
7584: }
1.1162 raeburn 7585: }
7586: }
7587: }
1.1172.2.66 raeburn 7588: return if ($noblock);
7589: return @blockers;
7590: }
1.1162 raeburn 7591: }
7592:
1.1172.2.66 raeburn 7593: # -------------------------------- Deversion and split uri into path an filename
7594:
1.1133 foxr 7595: #
1.1172.2.66 raeburn 7596: # Removes the version from a URI and
1.1133 foxr 7597: # splits it in to its filename and path to the filename.
7598: # Seems like File::Basename could have done this more clearly.
7599: # Parameters:
7600: # $uri - input URI
7601: # Returns:
7602: # Two element list consisting of
7603: # $pathname - the URI up to and excluding the trailing /
7604: # $filename - The part of the URI following the last /
7605: # NOTE:
7606: # Another realization of this is simply:
7607: # use File::Basename;
7608: # ...
7609: # $uri = shift;
7610: # $filename = basename($uri);
7611: # $path = dirname($uri);
7612: # return ($filename, $path);
7613: #
7614: # The implementation below is probably faster however.
7615: #
1.710 albertel 7616: sub split_uri_for_cond {
7617: my $uri=&deversion(&declutter(shift));
7618: my @uriparts=split(/\//,$uri);
7619: my $filename=pop(@uriparts);
7620: my $pathname=join('/',@uriparts);
7621: return ($pathname,$filename);
7622: }
1.232 www 7623: # --------------------------------------------------- Is a resource on the map?
7624:
7625: sub is_on_map {
1.710 albertel 7626: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7627: #Trying to find the conditional for the file
1.620 albertel 7628: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7629: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7630: if ($match) {
1.289 bowersj2 7631: return (1,$1);
7632: } else {
1.434 www 7633: return (0,0);
1.289 bowersj2 7634: }
1.12 www 7635: }
7636:
1.427 www 7637: # --------------------------------------------------------- Get symb from alias
7638:
7639: sub get_symb_from_alias {
7640: my $symb=shift;
7641: my ($map,$resid,$url)=&decode_symb($symb);
7642: # Already is a symb
7643: if ($url) { return $symb; }
7644: # Must be an alias
7645: my $aliassymb='';
7646: my %bighash;
1.620 albertel 7647: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7648: &GDBM_READER(),0640)) {
7649: my $rid=$bighash{'mapalias_'.$symb};
7650: if ($rid) {
7651: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7652: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7653: $resid,$bighash{'src_'.$rid});
1.427 www 7654: }
7655: untie %bighash;
7656: }
7657: return $aliassymb;
7658: }
7659:
1.12 www 7660: # ----------------------------------------------------------------- Define Role
7661:
7662: sub definerole {
7663: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 7664: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7665: foreach my $role (split(':',$sysrole)) {
7666: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7667: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7668: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7669: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7670: return "refused:s:$crole&$cqual";
7671: }
7672: }
1.191 harris41 7673: }
1.800 albertel 7674: foreach my $role (split(':',$domrole)) {
7675: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7676: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7677: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7678: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7679: return "refused:d:$crole&$cqual";
7680: }
7681: }
1.191 harris41 7682: }
1.800 albertel 7683: foreach my $role (split(':',$courole)) {
7684: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7685: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7686: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7687: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7688: return "refused:c:$crole&$cqual";
7689: }
7690: }
1.191 harris41 7691: }
1.1172.2.84 raeburn 7692: my $uhome;
7693: if (($uname ne '') && ($udom ne '')) {
7694: $uhome = &homeserver($uname,$udom);
7695: return $uhome if ($uhome eq 'no_host');
7696: } else {
7697: $uname = $env{'user.name'};
7698: $udom = $env{'user.domain'};
7699: $uhome = $env{'user.home'};
7700: }
1.620 albertel 7701: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 7702: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7703: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 7704: return reply($command,$uhome);
1.12 www 7705: } else {
7706: return 'refused';
7707: }
1.105 harris41 7708: }
7709:
7710: # ---------------- Make a metadata query against the network of library servers
7711:
7712: sub metadata_query {
1.1172.2.33 raeburn 7713: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7714: my %rhash;
1.845 albertel 7715: my %libserv = &all_library();
1.244 matthew 7716: my @server_list = (defined($server_array) ? @$server_array
7717: : keys(%libserv) );
7718: for my $server (@server_list) {
1.1172.2.33 raeburn 7719: my $domains = '';
7720: if (ref($domains_hash) eq 'HASH') {
7721: $domains = $domains_hash->{$server};
7722: }
1.118 harris41 7723: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7724: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7725: $rhash{$server}=$reply;
7726: }
7727: else {
7728: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7729: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7730: $server);
7731: $rhash{$server}=$reply;
7732: }
1.112 harris41 7733: }
1.118 harris41 7734: return \%rhash;
1.240 www 7735: }
7736:
7737: # ----------------------------------------- Send log queries and wait for reply
7738:
7739: sub log_query {
7740: my ($uname,$udom,$query,%filters)=@_;
7741: my $uhome=&homeserver($uname,$udom);
7742: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7743: my $uhost=&hostname($uhome);
1.800 albertel 7744: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7745: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7746: $uhome);
1.479 albertel 7747: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7748: return get_query_reply($queryid);
7749: }
7750:
1.818 raeburn 7751: # -------------------------- Update MySQL table for portfolio file
7752:
7753: sub update_portfolio_table {
1.821 raeburn 7754: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7755: if ($group ne '') {
7756: $file_name =~s /^\Q$group\E//;
7757: }
1.818 raeburn 7758: my $homeserver = &homeserver($uname,$udom);
7759: my $queryid=
1.821 raeburn 7760: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7761: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7762: my $reply = &get_query_reply($queryid);
7763: return $reply;
7764: }
7765:
1.899 raeburn 7766: # -------------------------- Update MySQL allusers table
7767:
7768: sub update_allusers_table {
7769: my ($uname,$udom,$names) = @_;
7770: my $homeserver = &homeserver($uname,$udom);
7771: my $queryid=
7772: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7773: 'lastname='.&escape($names->{'lastname'}).'%%'.
7774: 'firstname='.&escape($names->{'firstname'}).'%%'.
7775: 'middlename='.&escape($names->{'middlename'}).'%%'.
7776: 'generation='.&escape($names->{'generation'}).'%%'.
7777: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7778: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7779: return;
1.899 raeburn 7780: }
7781:
1.508 raeburn 7782: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7783:
7784: sub fetch_enrollment_query {
1.511 raeburn 7785: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 7786: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7787: my $maxtries = 1;
1.508 raeburn 7788: if ($context eq 'automated') {
7789: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 7790: $sleep = 2;
7791: $loopmax = 100;
1.547 raeburn 7792: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7793: } else {
7794: $homeserver = &homeserver($cnum,$dom);
7795: }
1.838 albertel 7796: my $host=&hostname($homeserver);
1.506 raeburn 7797: my $cmd = '';
1.1000 raeburn 7798: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7799: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7800: }
7801: $cmd =~ s/%%$//;
7802: $cmd = &escape($cmd);
7803: my $query = 'fetchenrollment';
1.620 albertel 7804: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7805: unless ($queryid=~/^\Q$host\E\_/) {
7806: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7807: return 'error: '.$queryid;
7808: }
1.1172.2.79 raeburn 7809: my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547 raeburn 7810: my $tries = 1;
7811: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 7812: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7813: $tries ++;
7814: }
1.526 raeburn 7815: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7816: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7817: } else {
1.901 albertel 7818: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 7819: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 7820: foreach my $line (@responses) {
7821: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7822: $$replyref{$key} = $value;
7823: }
7824: } else {
1.1117 foxr 7825: my $pathname = LONCAPA::tempdir();
1.800 albertel 7826: foreach my $line (@responses) {
7827: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7828: $$replyref{$key} = $value;
7829: if ($value > 0) {
1.800 albertel 7830: foreach my $item (@{$$affiliatesref{$key}}) {
7831: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7832: my $destname = $pathname.'/'.$filename;
7833: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7834: if ($xml_classlist =~ /^error/) {
7835: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7836: } else {
1.506 raeburn 7837: if ( open(FILE,">$destname") ) {
7838: print FILE &unescape($xml_classlist);
7839: close(FILE);
1.526 raeburn 7840: } else {
7841: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7842: }
7843: }
7844: }
7845: }
7846: }
7847: }
7848: return 'ok';
7849: }
7850: return 'error';
7851: }
7852:
1.242 www 7853: sub get_query_reply {
1.1172.2.79 raeburn 7854: my ($queryid,$sleep,$loopmax) = @_;
7855: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
7856: $sleep = 0.2;
7857: }
7858: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
7859: $loopmax = 100;
7860: }
1.1117 foxr 7861: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7862: my $reply='';
1.1172.2.79 raeburn 7863: for (1..$loopmax) {
7864: sleep($sleep);
1.240 www 7865: if (-e $replyfile.'.end') {
1.448 albertel 7866: if (open(my $fh,$replyfile)) {
1.904 albertel 7867: $reply = join('',<$fh>);
7868: close($fh);
1.240 www 7869: } else { return 'error: reply_file_error'; }
1.242 www 7870: return &unescape($reply);
7871: }
1.240 www 7872: }
1.242 www 7873: return 'timeout:'.$queryid;
1.240 www 7874: }
7875:
7876: sub courselog_query {
1.241 www 7877: #
7878: # possible filters:
7879: # url: url or symb
7880: # username
7881: # domain
7882: # action: view, submit, grade
7883: # start: timestamp
7884: # end: timestamp
7885: #
1.240 www 7886: my (%filters)=@_;
1.620 albertel 7887: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7888: if ($filters{'url'}) {
7889: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7890: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7891: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7892: }
1.620 albertel 7893: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7894: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7895: return &log_query($cname,$cdom,'courselog',%filters);
7896: }
7897:
7898: sub userlog_query {
1.858 raeburn 7899: #
7900: # possible filters:
7901: # action: log check role
7902: # start: timestamp
7903: # end: timestamp
7904: #
1.240 www 7905: my ($uname,$udom,%filters)=@_;
7906: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7907: }
7908:
1.506 raeburn 7909: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7910:
7911: sub auto_run {
1.508 raeburn 7912: my ($cnum,$cdom) = @_;
1.876 raeburn 7913: my $response = 0;
7914: my $settings;
7915: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7916: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7917: $settings = $domconfig{'autoenroll'};
7918: if ($settings->{'run'} eq '1') {
7919: $response = 1;
7920: }
7921: } else {
1.934 raeburn 7922: my $homeserver;
7923: if (&is_course($cdom,$cnum)) {
7924: $homeserver = &homeserver($cnum,$cdom);
7925: } else {
7926: $homeserver = &domain($cdom,'primary');
7927: }
7928: if ($homeserver ne 'no_host') {
7929: $response = &reply('autorun:'.$cdom,$homeserver);
7930: }
1.876 raeburn 7931: }
1.506 raeburn 7932: return $response;
7933: }
1.776 albertel 7934:
1.506 raeburn 7935: sub auto_get_sections {
1.508 raeburn 7936: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7937: my $homeserver;
7938: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7939: $homeserver = &homeserver($cnum,$cdom);
7940: }
7941: if (!defined($homeserver)) {
7942: if ($cdom =~ /^$match_domain$/) {
7943: $homeserver = &domain($cdom,'primary');
7944: }
7945: }
7946: my @secs;
7947: if (defined($homeserver)) {
7948: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7949: unless ($response eq 'refused') {
7950: @secs = split(/:/,$response);
7951: }
1.506 raeburn 7952: }
7953: return @secs;
7954: }
1.776 albertel 7955:
1.506 raeburn 7956: sub auto_new_course {
1.1099 raeburn 7957: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7958: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7959: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7960: return $response;
7961: }
1.776 albertel 7962:
1.506 raeburn 7963: sub auto_validate_courseID {
1.508 raeburn 7964: my ($cnum,$cdom,$inst_course_id) = @_;
7965: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7966: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7967: return $response;
7968: }
1.776 albertel 7969:
1.1007 raeburn 7970: sub auto_validate_instcode {
1.1020 raeburn 7971: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7972: my ($homeserver,$response);
7973: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7974: $homeserver = &homeserver($cnum,$cdom);
7975: }
7976: if (!defined($homeserver)) {
7977: if ($cdom =~ /^$match_domain$/) {
7978: $homeserver = &domain($cdom,'primary');
7979: }
7980: }
1.1065 raeburn 7981: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7982: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7983: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7984: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7985: }
7986:
1.506 raeburn 7987: sub auto_create_password {
1.873 raeburn 7988: my ($cnum,$cdom,$authparam,$udom) = @_;
7989: my ($homeserver,$response);
1.506 raeburn 7990: my $create_passwd = 0;
7991: my $authchk = '';
1.873 raeburn 7992: if ($udom =~ /^$match_domain$/) {
7993: $homeserver = &domain($udom,'primary');
7994: }
7995: if ($homeserver eq '') {
7996: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7997: $homeserver = &homeserver($cnum,$cdom);
7998: }
7999: }
8000: if ($homeserver eq '') {
8001: $authchk = 'nodomain';
1.506 raeburn 8002: } else {
1.873 raeburn 8003: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8004: if ($response eq 'refused') {
8005: $authchk = 'refused';
8006: } else {
1.901 albertel 8007: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8008: }
1.506 raeburn 8009: }
8010: return ($authparam,$create_passwd,$authchk);
8011: }
8012:
1.706 raeburn 8013: sub auto_photo_permission {
8014: my ($cnum,$cdom,$students) = @_;
8015: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8016: my ($outcome,$perm_reqd,$conditions) =
8017: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8018: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8019: return (undef,undef);
8020: }
1.706 raeburn 8021: return ($outcome,$perm_reqd,$conditions);
8022: }
8023:
8024: sub auto_checkphotos {
8025: my ($uname,$udom,$pid) = @_;
8026: my $homeserver = &homeserver($uname,$udom);
8027: my ($result,$resulttype);
8028: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8029: &escape($uname).':'.&escape($pid),
8030: $homeserver));
1.709 albertel 8031: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8032: return (undef,undef);
8033: }
1.706 raeburn 8034: if ($outcome) {
8035: ($result,$resulttype) = split(/:/,$outcome);
8036: }
8037: return ($result,$resulttype);
8038: }
8039:
8040: sub auto_photochoice {
8041: my ($cnum,$cdom) = @_;
8042: my $homeserver = &homeserver($cnum,$cdom);
8043: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8044: &escape($cdom),
8045: $homeserver)));
1.709 albertel 8046: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8047: return (undef,undef);
8048: }
1.706 raeburn 8049: return ($update,$comment);
8050: }
8051:
8052: sub auto_photoupdate {
8053: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8054: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8055: my $host=&hostname($homeserver);
1.706 raeburn 8056: my $cmd = '';
8057: my $maxtries = 1;
1.800 albertel 8058: foreach my $affiliate (keys(%{$affiliatesref})) {
8059: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8060: }
8061: $cmd =~ s/%%$//;
8062: $cmd = &escape($cmd);
8063: my $query = 'institutionalphotos';
8064: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8065: unless ($queryid=~/^\Q$host\E\_/) {
8066: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8067: return 'error: '.$queryid;
8068: }
8069: my $reply = &get_query_reply($queryid);
8070: my $tries = 1;
8071: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8072: $reply = &get_query_reply($queryid);
8073: $tries ++;
8074: }
8075: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8076: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8077: } else {
8078: my @responses = split(/:/,$reply);
8079: my $outcome = shift(@responses);
8080: foreach my $item (@responses) {
8081: my ($key,$value) = split(/=/,$item);
8082: $$photo{$key} = $value;
8083: }
8084: return $outcome;
8085: }
8086: return 'error';
8087: }
8088:
1.521 raeburn 8089: sub auto_instcode_format {
1.793 albertel 8090: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8091: $cat_order) = @_;
1.521 raeburn 8092: my $courses = '';
1.772 raeburn 8093: my @homeservers;
1.521 raeburn 8094: if ($caller eq 'global') {
1.841 albertel 8095: my %servers = &get_servers($codedom,'library');
8096: foreach my $tryserver (keys(%servers)) {
8097: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8098: push(@homeservers,$tryserver);
8099: }
1.584 raeburn 8100: }
1.1022 raeburn 8101: } elsif ($caller eq 'requests') {
8102: if ($codedom =~ /^$match_domain$/) {
8103: my $chome = &domain($codedom,'primary');
8104: unless ($chome eq 'no_host') {
8105: push(@homeservers,$chome);
8106: }
8107: }
1.521 raeburn 8108: } else {
1.772 raeburn 8109: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8110: }
1.793 albertel 8111: foreach my $code (keys(%{$instcodes})) {
8112: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8113: }
8114: chop($courses);
1.772 raeburn 8115: my $ok_response = 0;
8116: my $response;
8117: while (@homeservers > 0 && $ok_response == 0) {
8118: my $server = shift(@homeservers);
8119: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8120: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8121: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8122: split(/:/,$response);
1.772 raeburn 8123: %{$codes} = (%{$codes},&str2hash($codes_str));
8124: push(@{$codetitles},&str2array($codetitles_str));
8125: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8126: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8127: $ok_response = 1;
8128: }
8129: }
8130: if ($ok_response) {
1.521 raeburn 8131: return 'ok';
1.772 raeburn 8132: } else {
8133: return $response;
1.521 raeburn 8134: }
8135: }
8136:
1.792 raeburn 8137: sub auto_instcode_defaults {
8138: my ($domain,$returnhash,$code_order) = @_;
8139: my @homeservers;
1.841 albertel 8140:
8141: my %servers = &get_servers($domain,'library');
8142: foreach my $tryserver (keys(%servers)) {
8143: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8144: push(@homeservers,$tryserver);
8145: }
1.792 raeburn 8146: }
1.841 albertel 8147:
1.792 raeburn 8148: my $response;
1.841 albertel 8149: foreach my $server (@homeservers) {
1.792 raeburn 8150: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8151: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8152:
8153: foreach my $pair (split(/\&/,$response)) {
8154: my ($name,$value)=split(/\=/,$pair);
8155: if ($name eq 'code_order') {
8156: @{$code_order} = split(/\&/,&unescape($value));
8157: } else {
8158: $returnhash->{&unescape($name)}=&unescape($value);
8159: }
8160: }
8161: return 'ok';
1.792 raeburn 8162: }
1.841 albertel 8163:
8164: return $response;
1.1003 raeburn 8165: }
8166:
8167: sub auto_possible_instcodes {
1.1007 raeburn 8168: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8169: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8170: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8171: return;
8172: }
1.1003 raeburn 8173: my (@homeservers,$uhome);
8174: if (defined(&domain($domain,'primary'))) {
8175: $uhome=&domain($domain,'primary');
8176: push(@homeservers,&domain($domain,'primary'));
8177: } else {
8178: my %servers = &get_servers($domain,'library');
8179: foreach my $tryserver (keys(%servers)) {
8180: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8181: push(@homeservers,$tryserver);
8182: }
8183: }
8184: }
8185: my $response;
8186: foreach my $server (@homeservers) {
8187: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8188: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8189: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8190: split(':',$response);
8191: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8192: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8193: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8194: my ($name,$value)=split('=',$item);
8195: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8196: }
8197: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8198: my ($name,$value)=split('=',$item);
8199: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8200: }
8201: return 'ok';
8202: }
8203: return $response;
8204: }
1.792 raeburn 8205:
1.1010 raeburn 8206: sub auto_courserequest_checks {
8207: my ($dom) = @_;
1.1020 raeburn 8208: my ($homeserver,%validations);
8209: if ($dom =~ /^$match_domain$/) {
8210: $homeserver = &domain($dom,'primary');
8211: }
8212: unless ($homeserver eq 'no_host') {
8213: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8214: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8215: my @items = split(/&/,$response);
8216: foreach my $item (@items) {
8217: my ($key,$value) = split('=',$item);
8218: $validations{&unescape($key)} = &thaw_unescape($value);
8219: }
8220: }
8221: }
1.1010 raeburn 8222: return %validations;
8223: }
8224:
1.1020 raeburn 8225: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8226: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8227: my ($homeserver,$response);
8228: if ($dom =~ /^$match_domain$/) {
8229: $homeserver = &domain($dom,'primary');
8230: }
1.1172.2.43 raeburn 8231: unless ($homeserver eq 'no_host') {
8232: my $customdata;
8233: if (ref($custominfo) eq 'HASH') {
8234: $customdata = &freeze_escape($custominfo);
8235: }
1.1020 raeburn 8236: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8237: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8238: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8239: $customdata,$homeserver));
1.1020 raeburn 8240: }
8241: return $response;
8242: }
8243:
1.777 albertel 8244: sub auto_validate_class_sec {
1.918 raeburn 8245: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8246: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8247: my $ownerlist;
8248: if (ref($owners) eq 'ARRAY') {
8249: $ownerlist = join(',',@{$owners});
8250: } else {
8251: $ownerlist = $owners;
8252: }
1.773 raeburn 8253: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8254: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8255: return $response;
8256: }
8257:
1.1172.2.38 raeburn 8258: sub auto_crsreq_update {
8259: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8260: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8261: my ($homeserver,%crsreqresponse);
8262: if ($cdom =~ /^$match_domain$/) {
8263: $homeserver = &domain($cdom,'primary');
8264: }
8265: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8266: my $info;
8267: if (ref($inbound) eq 'HASH') {
8268: $info = &freeze_escape($inbound);
8269: }
8270: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8271: ':'.&escape($action).':'.&escape($ownername).':'.
8272: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8273: &escape($title).':'.&escape($code).':'.
8274: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8275: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8276: my @items = split(/&/,$response);
8277: foreach my $item (@items) {
8278: my ($key,$value) = split('=',$item);
8279: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8280: }
8281: }
8282: }
8283: return \%crsreqresponse;
8284: }
8285:
1.1172.2.78 raeburn 8286: sub auto_export_grades {
8287: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8288: my ($homeserver,%exportresponse);
8289: if ($cdom =~ /^$match_domain$/) {
8290: $homeserver = &domain($cdom,'primary');
8291: }
8292: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8293: my $info;
8294: if (ref($inforef) eq 'HASH') {
8295: $info = &freeze_escape($inforef);
8296: }
8297: if (ref($gradesref) eq 'HASH') {
8298: my $grades = &freeze_escape($gradesref);
8299: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8300: $info.':'.$grades,$homeserver);
8301: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8302: my @items = split(/&/,$response);
8303: foreach my $item (@items) {
8304: my ($key,$value) = split('=',$item);
8305: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8306: }
8307: }
8308: }
8309: }
8310: return \%exportresponse;
8311: }
8312:
1.1172.2.68 raeburn 8313: sub check_instcode_cloning {
8314: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8315: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8316: return;
8317: }
8318: my $canclone;
8319: if (@{$code_order} > 0) {
8320: my $instcoderegexp ='^';
8321: my @clonecodes = split(/\&/,$cloner);
8322: foreach my $item (@{$code_order}) {
8323: if (grep(/^\Q$item\E=/,@clonecodes)) {
8324: foreach my $pair (@clonecodes) {
8325: my ($key,$val) = split(/\=/,$pair,2);
8326: $val = &unescape($val);
8327: if ($key eq $item) {
8328: $instcoderegexp .= '('.$val.')';
8329: last;
8330: }
8331: }
8332: } else {
8333: $instcoderegexp .= $codedefaults->{$item};
8334: }
8335: }
8336: $instcoderegexp .= '$';
8337: my (@from,@to);
8338: eval {
8339: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8340: (@to) = ($clonetocode =~ /$instcoderegexp/);
8341: };
8342: if ((@from > 0) && (@to > 0)) {
8343: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8344: if (!@diffs) {
8345: $canclone = 1;
8346: }
8347: }
8348: }
8349: return $canclone;
8350: }
8351:
8352: sub default_instcode_cloning {
8353: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8354: my (%codedefaults,@code_order,$canclone);
8355: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8356: %codedefaults = %{$codedefaultsref};
8357: @code_order = @{$codeorderref};
8358: } elsif ($clonedom) {
8359: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8360: }
8361: if (($domdefclone) && (@code_order)) {
8362: my @clonecodes = split(/\+/,$domdefclone);
8363: my $instcoderegexp ='^';
8364: foreach my $item (@code_order) {
8365: if (grep(/^\Q$item\E$/,@clonecodes)) {
8366: $instcoderegexp .= '('.$codedefaults{$item}.')';
8367: } else {
8368: $instcoderegexp .= $codedefaults{$item};
8369: }
8370: }
8371: $instcoderegexp .= '$';
8372: my (@from,@to);
8373: eval {
8374: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8375: (@to) = ($clonetocode =~ /$instcoderegexp/);
8376: };
8377: if ((@from > 0) && (@to > 0)) {
8378: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8379: if (!@diffs) {
8380: $canclone = 1;
8381: }
8382: }
8383: }
8384: return $canclone;
8385: }
8386:
1.679 raeburn 8387: # ------------------------------------------------------- Course Group routines
8388:
8389: sub get_coursegroups {
1.809 raeburn 8390: my ($cdom,$cnum,$group,$namespace) = @_;
8391: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8392: }
8393:
1.679 raeburn 8394: sub modify_coursegroup {
8395: my ($cdom,$cnum,$groupsettings) = @_;
8396: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8397: }
8398:
1.809 raeburn 8399: sub toggle_coursegroup_status {
8400: my ($cdom,$cnum,$group,$action) = @_;
8401: my ($from_namespace,$to_namespace);
8402: if ($action eq 'delete') {
8403: $from_namespace = 'coursegroups';
8404: $to_namespace = 'deleted_groups';
8405: } else {
8406: $from_namespace = 'deleted_groups';
8407: $to_namespace = 'coursegroups';
8408: }
8409: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8410: if (my $tmp = &error(%curr_group)) {
8411: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8412: return ('read error',$tmp);
8413: } else {
8414: my %savedsettings = %curr_group;
1.809 raeburn 8415: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8416: my $deloutcome;
8417: if ($result eq 'ok') {
1.809 raeburn 8418: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8419: } else {
8420: return ('write error',$result);
8421: }
8422: if ($deloutcome eq 'ok') {
8423: return 'ok';
8424: } else {
8425: return ('delete error',$deloutcome);
8426: }
8427: }
8428: }
8429:
1.679 raeburn 8430: sub modify_group_roles {
1.957 raeburn 8431: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8432: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8433: my $role = 'gr/'.&escape($userprivs);
8434: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8435: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8436: if ($result eq 'ok') {
8437: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8438: }
1.679 raeburn 8439: return $result;
8440: }
8441:
8442: sub modify_coursegroup_membership {
8443: my ($cdom,$cnum,$membership) = @_;
8444: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8445: return $result;
8446: }
8447:
1.682 raeburn 8448: sub get_active_groups {
8449: my ($udom,$uname,$cdom,$cnum) = @_;
8450: my $now = time;
8451: my %groups = ();
8452: foreach my $key (keys(%env)) {
1.811 albertel 8453: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8454: my ($start,$end) = split(/\./,$env{$key});
8455: if (($end!=0) && ($end<$now)) { next; }
8456: if (($start!=0) && ($start>$now)) { next; }
8457: if ($1 eq $cdom && $2 eq $cnum) {
8458: $groups{$3} = $env{$key} ;
8459: }
8460: }
8461: }
8462: return %groups;
8463: }
8464:
1.683 raeburn 8465: sub get_group_membership {
8466: my ($cdom,$cnum,$group) = @_;
8467: return(&dump('groupmembership',$cdom,$cnum,$group));
8468: }
8469:
8470: sub get_users_groups {
8471: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8472: my @usersgroups;
1.683 raeburn 8473: my $cachetime=1800;
8474:
8475: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8476: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8477: if (defined($cached)) {
1.734 albertel 8478: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8479: } else {
8480: $grouplist = '';
1.816 raeburn 8481: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8482: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8483: my $access_end = $env{'course.'.$courseid.
8484: '.default_enrollment_end_date'};
8485: my $now = time;
8486: foreach my $key (keys(%roleshash)) {
8487: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8488: my $group = $1;
8489: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8490: my $start = $2;
8491: my $end = $1;
8492: if ($start == -1) { next; } # deleted from group
8493: if (($start!=0) && ($start>$now)) { next; }
8494: if (($end!=0) && ($end<$now)) {
8495: if ($access_end && $access_end < $now) {
8496: if ($access_end - $end < 86400) {
8497: push(@usersgroups,$group);
1.733 raeburn 8498: }
8499: }
1.817 raeburn 8500: next;
1.733 raeburn 8501: }
1.817 raeburn 8502: push(@usersgroups,$group);
1.683 raeburn 8503: }
8504: }
8505: }
1.817 raeburn 8506: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8507: $grouplist = join(':',@usersgroups);
8508: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8509: }
1.733 raeburn 8510: return @usersgroups;
1.683 raeburn 8511: }
8512:
8513: sub devalidate_getgroups_cache {
8514: my ($udom,$uname,$cdom,$cnum)=@_;
8515: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8516:
1.683 raeburn 8517: my $hashid="$udom:$uname:$courseid";
8518: &devalidate_cache_new('getgroups',$hashid);
8519: }
8520:
1.12 www 8521: # ------------------------------------------------------------------ Plain Text
8522:
8523: sub plaintext {
1.988 raeburn 8524: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8525: if ($short =~ m{^cr/}) {
1.758 albertel 8526: return (split('/',$short))[-1];
8527: }
1.742 raeburn 8528: if (!defined($cid)) {
8529: $cid = $env{'request.course.id'};
8530: }
8531: my %rolenames = (
1.1008 raeburn 8532: Course => 'std',
8533: Community => 'alt1',
1.742 raeburn 8534: );
1.1037 raeburn 8535: if ($cid ne '') {
8536: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8537: unless ($forcedefault) {
8538: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8539: &Apache::lonlocal::mt_escape(\$roletext);
8540: return &Apache::lonlocal::mt($roletext);
8541: }
8542: }
8543: }
8544: if ((defined($type)) && (defined($rolenames{$type})) &&
8545: (defined($rolenames{$type})) &&
8546: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8547: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8548: } elsif ($cid ne '') {
8549: my $crstype = $env{'course.'.$cid.'.type'};
8550: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8551: (defined($prp{$short}{$rolenames{$crstype}}))) {
8552: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8553: }
1.742 raeburn 8554: }
1.1037 raeburn 8555: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8556: }
8557:
8558: # ----------------------------------------------------------------- Assign Role
8559:
8560: sub assignrole {
1.957 raeburn 8561: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8562: $context)=@_;
1.21 www 8563: my $mrole;
8564: if ($role =~ /^cr\//) {
1.393 www 8565: my $cwosec=$url;
1.811 albertel 8566: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8567: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8568: my $refused = 1;
8569: if ($context eq 'requestcourses') {
8570: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8571: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8572: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8573: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8574: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8575: if ($crsenv{'internal.courseowner'} eq
8576: $env{'user.name'}.':'.$env{'user.domain'}) {
8577: $refused = '';
8578: }
8579: }
8580: }
8581: }
8582: }
8583: if ($refused) {
8584: &logthis('Refused custom assignrole: '.
8585: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8586: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8587: return 'refused';
8588: }
1.104 www 8589: }
1.21 www 8590: $mrole='cr';
1.678 raeburn 8591: } elsif ($role =~ /^gr\//) {
8592: my $cwogrp=$url;
1.811 albertel 8593: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8594: unless (&allowed('mdg',$cwogrp)) {
8595: &logthis('Refused group assignrole: '.
8596: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8597: $env{'user.name'}.' at '.$env{'user.domain'});
8598: return 'refused';
8599: }
8600: $mrole='gr';
1.21 www 8601: } else {
1.82 www 8602: my $cwosec=$url;
1.811 albertel 8603: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8604: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8605: my $refused;
8606: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8607: if (!(&allowed('c'.$role,$url))) {
8608: $refused = 1;
8609: }
8610: } else {
8611: $refused = 1;
8612: }
1.947 raeburn 8613: if ($refused) {
1.1045 raeburn 8614: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8615: if (!$selfenroll && $context eq 'course') {
8616: my %crsenv;
8617: if ($role eq 'cc' || $role eq 'co') {
8618: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8619: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8620: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8621: if ($crsenv{'internal.courseowner'} eq
8622: $env{'user.name'}.':'.$env{'user.domain'}) {
8623: $refused = '';
8624: }
8625: }
8626: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8627: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8628: if ($crsenv{'internal.courseowner'} eq
8629: $env{'user.name'}.':'.$env{'user.domain'}) {
8630: $refused = '';
8631: }
8632: }
8633: }
8634: }
8635: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8636: $refused = '';
1.1017 raeburn 8637: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8638: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8639: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8640: my $wrongcc;
8641: if ($cnum =~ /^$match_community$/) {
8642: $wrongcc = 1 if ($role eq 'cc');
8643: } else {
8644: $wrongcc = 1 if ($role eq 'co');
8645: }
8646: unless ($wrongcc) {
8647: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8648: if ($crsenv{'internal.courseowner'} eq
8649: $env{'user.name'}.':'.$env{'user.domain'}) {
8650: $refused = '';
8651: }
1.1017 raeburn 8652: }
8653: }
1.1172.2.9 raeburn 8654: } elsif ($context eq 'requestauthor') {
8655: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8656: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8657: if ($env{'environment.requestauthor'} eq 'automatic') {
8658: $refused = '';
8659: } else {
8660: my %domdefaults = &get_domain_defaults($udom);
8661: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8662: my $checkbystatus;
8663: if ($env{'user.adv'}) {
8664: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8665: if ($disposition eq 'automatic') {
8666: $refused = '';
8667: } elsif ($disposition eq '') {
8668: $checkbystatus = 1;
8669: }
8670: } else {
8671: $checkbystatus = 1;
8672: }
8673: if ($checkbystatus) {
8674: if ($env{'environment.inststatus'}) {
8675: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8676: foreach my $type (@inststatuses) {
8677: if (($type ne '') &&
8678: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8679: $refused = '';
8680: }
8681: }
8682: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8683: $refused = '';
8684: }
8685: }
8686: }
8687: }
8688: }
1.1017 raeburn 8689: }
8690: if ($refused) {
1.947 raeburn 8691: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8692: ' '.$role.' '.$end.' '.$start.' by '.
8693: $env{'user.name'}.' at '.$env{'user.domain'});
8694: return 'refused';
8695: }
1.932 raeburn 8696: }
1.1131 raeburn 8697: } elsif ($role eq 'au') {
8698: if ($url ne '/'.$udom.'/') {
8699: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8700: ' to assign author role for '.$uname.':'.$udom.
8701: ' in domain: '.$url.' refused (wrong domain).');
8702: return 'refused';
8703: }
1.104 www 8704: }
1.21 www 8705: $mrole=$role;
8706: }
1.620 albertel 8707: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8708: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8709: if ($end) { $command.='_'.$end; }
1.21 www 8710: if ($start) {
8711: if ($end) {
1.81 www 8712: $command.='_'.$start;
1.21 www 8713: } else {
1.81 www 8714: $command.='_0_'.$start;
1.21 www 8715: }
8716: }
1.739 raeburn 8717: my $origstart = $start;
8718: my $origend = $end;
1.957 raeburn 8719: my $delflag;
1.357 www 8720: # actually delete
8721: if ($deleteflag) {
1.373 www 8722: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8723: # modify command to delete the role
1.620 albertel 8724: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8725: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8726: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8727: # set start and finish to negative values for userrolelog
8728: $start=-1;
8729: $end=-1;
1.957 raeburn 8730: $delflag = 1;
1.357 www 8731: }
8732: }
8733: # send command
1.349 www 8734: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8735: # log new user role if status is ok
1.349 www 8736: if ($answer eq 'ok') {
1.663 raeburn 8737: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8738: if (($role eq 'cc') || ($role eq 'in') ||
8739: ($role eq 'ep') || ($role eq 'ad') ||
8740: ($role eq 'ta') || ($role eq 'st') ||
8741: ($role=~/^cr/) || ($role eq 'gr') ||
8742: ($role eq 'co')) {
1.1172.2.13 raeburn 8743: # for course roles, perform group memberships changes triggered by role change.
8744: unless ($role =~ /^gr/) {
8745: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8746: $origstart,$selfenroll,$context);
8747: }
1.1172.2.9 raeburn 8748: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8749: $selfenroll,$context);
8750: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.84 raeburn 8751: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1172.2.9 raeburn 8752: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8753: $context);
8754: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8755: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8756: $context);
8757: }
1.1053 raeburn 8758: if ($role eq 'cc') {
8759: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8760: }
1.349 www 8761: }
8762: return $answer;
1.169 harris41 8763: }
8764:
1.1053 raeburn 8765: sub autoupdate_coowners {
8766: my ($url,$end,$start,$uname,$udom) = @_;
8767: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8768: if (($cdom ne '') && ($cnum ne '')) {
8769: my $now = time;
8770: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8771: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8772: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8773: my $instcode = $coursehash{'internal.coursecode'};
8774: if ($instcode ne '') {
1.1056 raeburn 8775: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8776: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8777: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8778: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8779: if ($result eq 'valid') {
8780: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8781: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8782: push(@newcoowners,$coowner);
8783: }
8784: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8785: push(@newcoowners,$uname.':'.$udom);
8786: }
8787: @newcoowners = sort(@newcoowners);
8788: } else {
8789: push(@newcoowners,$uname.':'.$udom);
8790: }
8791: } else {
8792: if ($coursehash{'internal.co-owners'}) {
8793: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8794: unless ($coowner eq $uname.':'.$udom) {
8795: push(@newcoowners,$coowner);
8796: }
8797: }
8798: unless (@newcoowners > 0) {
8799: $delcoowners = 1;
8800: $coowners = '';
8801: }
8802: }
8803: }
8804: if (@newcoowners || $delcoowners) {
8805: &store_coowners($cdom,$cnum,$coursehash{'home'},
8806: $delcoowners,@newcoowners);
8807: }
8808: }
8809: }
8810: }
8811: }
8812: }
8813: }
8814:
8815: sub store_coowners {
8816: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8817: my $cid = $cdom.'_'.$cnum;
8818: my ($coowners,$delresult,$putresult);
8819: if (@newcoowners) {
8820: $coowners = join(',',@newcoowners);
8821: my %coownershash = (
8822: 'internal.co-owners' => $coowners,
8823: );
8824: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8825: if ($putresult eq 'ok') {
8826: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8827: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8828: }
8829: }
8830: }
8831: if ($delcoowners) {
8832: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8833: if ($delresult eq 'ok') {
8834: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8835: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8836: }
8837: }
8838: }
8839: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8840: my %crsinfo =
8841: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8842: if (ref($crsinfo{$cid}) eq 'HASH') {
8843: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8844: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8845: }
8846: }
8847: }
8848:
1.169 harris41 8849: # -------------------------------------------------- Modify user authentication
1.197 www 8850: # Overrides without validation
8851:
1.169 harris41 8852: sub modifyuserauth {
8853: my ($udom,$uname,$umode,$upass)=@_;
8854: my $uhome=&homeserver($uname,$udom);
1.197 www 8855: unless (&allowed('mau',$udom)) { return 'refused'; }
8856: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8857: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8858: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8859: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8860: &escape($upass),$uhome);
1.620 albertel 8861: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8862: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8863: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8864: &log($udom,,$uname,$uhome,
1.620 albertel 8865: 'Authentication changed by '.$env{'user.domain'}.', '.
8866: $env{'user.name'}.', '.$umode.
1.197 www 8867: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8868: unless ($reply eq 'ok') {
1.197 www 8869: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8870: return 'error: '.$reply;
8871: }
1.170 harris41 8872: return 'ok';
1.80 www 8873: }
8874:
1.81 www 8875: # --------------------------------------------------------------- Modify a user
1.80 www 8876:
1.81 www 8877: sub modifyuser {
1.206 matthew 8878: my ($udom, $uname, $uid,
8879: $umode, $upass, $first,
8880: $middle, $last, $gene,
1.1058 raeburn 8881: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8882: $udom= &LONCAPA::clean_domain($udom);
8883: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8884: my $showcandelete = 'none';
8885: if (ref($candelete) eq 'ARRAY') {
8886: if (@{$candelete} > 0) {
8887: $showcandelete = join(', ',@{$candelete});
8888: }
8889: }
1.81 www 8890: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8891: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8892: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8893: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8894: ' desiredhome not specified').
1.620 albertel 8895: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8896: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8897: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8898: my $newuser;
8899: if ($uhome eq 'no_host') {
8900: $newuser = 1;
8901: }
1.80 www 8902: # ----------------------------------------------------------------- Create User
1.406 albertel 8903: if (($uhome eq 'no_host') &&
8904: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8905: my $unhome='';
1.844 albertel 8906: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8907: $unhome = $desiredhome;
1.620 albertel 8908: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8909: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8910: } else { # load balancing routine for determining $unhome
1.81 www 8911: my $loadm=10000000;
1.841 albertel 8912: my %servers = &get_servers($udom,'library');
8913: foreach my $tryserver (keys(%servers)) {
8914: my $answer=reply('load',$tryserver);
8915: if (($answer=~/\d+/) && ($answer<$loadm)) {
8916: $loadm=$answer;
8917: $unhome=$tryserver;
8918: }
1.80 www 8919: }
8920: }
8921: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8922: return 'error: unable to find a home server for '.$uname.
8923: ' in domain '.$udom;
1.80 www 8924: }
8925: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8926: &escape($upass),$unhome);
8927: unless ($reply eq 'ok') {
8928: return 'error: '.$reply;
8929: }
1.230 stredwic 8930: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8931: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8932: return 'error: unable verify users home machine.';
1.80 www 8933: }
1.209 matthew 8934: } # End of creation of new user
1.80 www 8935: # ---------------------------------------------------------------------- Add ID
8936: if ($uid) {
8937: $uid=~tr/A-Z/a-z/;
8938: my %uidhash=&idrget($udom,$uname);
1.196 www 8939: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8940: && (!$forceid)) {
1.80 www 8941: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8942: return 'error: user id "'.$uid.'" does not match '.
8943: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8944: }
8945: } else {
8946: &idput($udom,($uname => $uid));
8947: }
8948: }
8949: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8950: my @tmp=&get('environment',
1.899 raeburn 8951: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8952: 'permanentemail','inststatus'],
1.134 albertel 8953: $udom,$uname);
1.1075 raeburn 8954: my (%names,%oldnames);
1.313 matthew 8955: if ($tmp[0] =~ m/^error:.*/) {
8956: %names=();
8957: } else {
8958: %names = @tmp;
1.1075 raeburn 8959: %oldnames = %names;
1.313 matthew 8960: }
1.388 www 8961: #
1.1058 raeburn 8962: # If name, email and/or uid are blank (e.g., because an uploaded file
8963: # of users did not contain them), do not overwrite existing values
8964: # unless field is in $candelete array ref.
8965: #
8966:
8967: my @fields = ('firstname','middlename','lastname','generation',
8968: 'permanentemail','id');
8969: my %newvalues;
8970: if (ref($candelete) eq 'ARRAY') {
8971: foreach my $field (@fields) {
8972: if (grep(/^\Q$field\E$/,@{$candelete})) {
8973: if ($field eq 'firstname') {
8974: $names{$field} = $first;
8975: } elsif ($field eq 'middlename') {
8976: $names{$field} = $middle;
8977: } elsif ($field eq 'lastname') {
8978: $names{$field} = $last;
8979: } elsif ($field eq 'generation') {
8980: $names{$field} = $gene;
8981: } elsif ($field eq 'permanentemail') {
8982: $names{$field} = $email;
8983: } elsif ($field eq 'id') {
8984: $names{$field} = $uid;
8985: }
8986: }
8987: }
8988: }
1.388 www 8989: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8990: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8991: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8992: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8993: if ($email) {
8994: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8995: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8996: }
1.899 raeburn 8997: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8998: if (defined($inststatus)) {
8999: $names{'inststatus'} = '';
9000: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9001: if (ref($usertypes) eq 'HASH') {
9002: my @okstatuses;
9003: foreach my $item (split(/:/,$inststatus)) {
9004: if (defined($usertypes->{$item})) {
9005: push(@okstatuses,$item);
9006: }
9007: }
9008: if (@okstatuses) {
9009: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9010: }
9011: }
9012: }
1.1075 raeburn 9013: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9014: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9015: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9016: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9017: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9018: } else {
9019: $logmsg .= ' during self creation';
9020: }
1.1075 raeburn 9021: my $changed;
9022: if ($newuser) {
9023: $changed = 1;
9024: } else {
9025: foreach my $field (@fields) {
9026: if ($names{$field} ne $oldnames{$field}) {
9027: $changed = 1;
9028: last;
9029: }
9030: }
9031: }
9032: unless ($changed) {
9033: $logmsg = 'No changes in user information needed for: '.$logmsg;
9034: &logthis($logmsg);
9035: return 'ok';
9036: }
9037: my $reply = &put('environment', \%names, $udom,$uname);
9038: if ($reply ne 'ok') {
9039: return 'error: '.$reply;
9040: }
1.1087 raeburn 9041: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9042: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9043: }
1.1075 raeburn 9044: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9045: &devalidate_cache_new('namescache',$uname.':'.$udom);
9046: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9047: &logthis($logmsg);
1.134 albertel 9048: return 'ok';
1.80 www 9049: }
9050:
1.81 www 9051: # -------------------------------------------------------------- Modify student
1.80 www 9052:
1.81 www 9053: sub modifystudent {
9054: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9055: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9056: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9057: if (!$cid) {
1.620 albertel 9058: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9059: return 'not_in_class';
9060: }
1.80 www 9061: }
9062: # --------------------------------------------------------------- Make the user
1.81 www 9063: my $reply=&modifyuser
1.209 matthew 9064: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9065: $desiredhome,$email,$inststatus);
1.80 www 9066: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9067: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9068: # student's environment
1.297 matthew 9069: $uid = undef if (!$forceid);
1.455 albertel 9070: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9071: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9072: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9073: return $reply;
9074: }
9075:
9076: sub modify_student_enrollment {
1.1172.2.23 raeburn 9077: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9078: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9079: my ($cdom,$cnum,$chome);
9080: if (!$cid) {
1.620 albertel 9081: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9082: return 'not_in_class';
9083: }
1.620 albertel 9084: $cdom=$env{'course.'.$cid.'.domain'};
9085: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9086: } else {
9087: ($cdom,$cnum)=split(/_/,$cid);
9088: }
1.620 albertel 9089: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9090: if (!$chome) {
1.457 raeburn 9091: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9092: }
1.455 albertel 9093: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9094: # Make sure the user exists
1.81 www 9095: my $uhome=&homeserver($uname,$udom);
9096: if (($uhome eq '') || ($uhome eq 'no_host')) {
9097: return 'error: no such user';
9098: }
1.297 matthew 9099: # Get student data if we were not given enough information
9100: if (!defined($first) || $first eq '' ||
9101: !defined($last) || $last eq '' ||
9102: !defined($uid) || $uid eq '' ||
9103: !defined($middle) || $middle eq '' ||
9104: !defined($gene) || $gene eq '') {
1.294 matthew 9105: # They did not supply us with enough data to enroll the student, so
9106: # we need to pick up more information.
1.297 matthew 9107: my %tmp = &get('environment',
1.294 matthew 9108: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9109: ,$udom,$uname);
9110:
1.800 albertel 9111: #foreach my $key (keys(%tmp)) {
9112: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9113: #}
1.294 matthew 9114: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9115: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9116: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9117: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9118: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9119: }
1.556 albertel 9120: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9121: my $user = "$uname:$udom";
9122: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9123: my $reply=cput('classlist',
1.1148 raeburn 9124: {$user =>
1.1172.2.76 raeburn 9125: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9126: $cdom,$cnum);
1.1148 raeburn 9127: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9128: &devalidate_getsection_cache($udom,$uname,$cid);
9129: } else {
1.81 www 9130: return 'error: '.$reply;
9131: }
1.297 matthew 9132: # Add student role to user
1.83 www 9133: my $uurl='/'.$cid;
1.81 www 9134: $uurl=~s/\_/\//g;
9135: if ($usec) {
9136: $uurl.='/'.$usec;
9137: }
1.1148 raeburn 9138: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9139: $selfenroll,$context);
9140: if ($result ne 'ok') {
9141: if ($old_entry{$user} ne '') {
9142: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9143: } else {
9144: $reply = &del('classlist',[$user],$cdom,$cnum);
9145: }
9146: }
9147: return $result;
1.21 www 9148: }
9149:
1.556 albertel 9150: sub format_name {
9151: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9152: my $name;
9153: if ($first ne 'lastname') {
9154: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9155: } else {
9156: if ($lastname=~/\S/) {
9157: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9158: $name=~s/\s+,/,/;
9159: } else {
9160: $name.= $firstname.' '.$middlename.' '.$generation;
9161: }
9162: }
9163: $name=~s/^\s+//;
9164: $name=~s/\s+$//;
9165: $name=~s/\s+/ /g;
9166: return $name;
9167: }
9168:
1.84 www 9169: # ------------------------------------------------- Write to course preferences
9170:
9171: sub writecoursepref {
9172: my ($courseid,%prefs)=@_;
9173: $courseid=~s/^\///;
9174: $courseid=~s/\_/\//g;
9175: my ($cdomain,$cnum)=split(/\//,$courseid);
9176: my $chome=homeserver($cnum,$cdomain);
9177: if (($chome eq '') || ($chome eq 'no_host')) {
9178: return 'error: no such course';
9179: }
9180: my $cstring='';
1.800 albertel 9181: foreach my $pref (keys(%prefs)) {
9182: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9183: }
1.84 www 9184: $cstring=~s/\&$//;
9185: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9186: }
9187:
9188: # ---------------------------------------------------------- Make/modify course
9189:
9190: sub createcourse {
1.741 raeburn 9191: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9192: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9193: $url=&declutter($url);
9194: my $cid='';
1.1028 raeburn 9195: if ($context eq 'requestcourses') {
9196: my $can_create = 0;
9197: my ($ownername,$ownerdom) = split(':',$course_owner);
9198: if ($udom eq $ownerdom) {
9199: if (&usertools_access($ownername,$ownerdom,$category,undef,
9200: $context)) {
9201: $can_create = 1;
9202: }
9203: } else {
9204: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9205: $category);
9206: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9207: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9208: if (@curr > 0) {
9209: my @options = qw(approval validate autolimit);
9210: my $optregex = join('|',@options);
9211: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9212: $can_create = 1;
9213: }
9214: }
9215: }
9216: }
9217: if ($can_create) {
9218: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9219: unless (&allowed('ccc',$udom)) {
9220: return 'refused';
9221: }
1.1017 raeburn 9222: }
9223: } else {
9224: return 'refused';
9225: }
1.1028 raeburn 9226: } elsif (!&allowed('ccc',$udom)) {
9227: return 'refused';
1.84 www 9228: }
1.1011 raeburn 9229: # --------------------------------------------------------------- Get Unique ID
9230: my $uname;
9231: if ($cnum =~ /^$match_courseid$/) {
9232: my $chome=&homeserver($cnum,$udom,'true');
9233: if (($chome eq '') || ($chome eq 'no_host')) {
9234: $uname = $cnum;
9235: } else {
1.1038 raeburn 9236: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9237: }
9238: } else {
1.1038 raeburn 9239: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9240: }
9241: return $uname if ($uname =~ /^error/);
9242: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9243: if (!defined($course_server)) {
9244: if (defined(&domain($udom,'primary'))) {
9245: $course_server = &domain($udom,'primary');
9246: } else {
9247: $course_server = $env{'user.home'};
9248: }
9249: }
9250: my %host_servers =
9251: &Apache::lonnet::get_servers($udom,'library');
9252: unless ($host_servers{$course_server}) {
9253: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9254: }
1.84 www 9255: # ------------------------------------------------------------- Make the course
9256: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9257: $course_server);
1.84 www 9258: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9259: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9260: if (($uhome eq '') || ($uhome eq 'no_host')) {
9261: return 'error: no such course';
9262: }
1.271 www 9263: # ----------------------------------------------------------------- Course made
1.516 raeburn 9264: # log existence
1.1029 raeburn 9265: my $now = time;
1.918 raeburn 9266: my $newcourse = {
9267: $udom.'_'.$uname => {
1.921 raeburn 9268: description => $description,
9269: inst_code => $inst_code,
9270: owner => $course_owner,
9271: type => $crstype,
1.1029 raeburn 9272: creator => $env{'user.name'}.':'.
9273: $env{'user.domain'},
9274: created => $now,
9275: context => $context,
1.918 raeburn 9276: },
9277: };
1.921 raeburn 9278: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9279: # set toplevel url
1.271 www 9280: my $topurl=$url;
9281: unless ($nonstandard) {
9282: # ------------------------------------------ For standard courses, make top url
9283: my $mapurl=&clutter($url);
1.278 www 9284: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9285: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9286: <map>
9287: <resource id="1" type="start"></resource>
9288: <resource id="2" src="$mapurl"></resource>
9289: <resource id="3" type="finish"></resource>
9290: <link index="1" from="1" to="2"></link>
9291: <link index="2" from="2" to="3"></link>
9292: </map>
9293: ENDINITMAP
9294: $topurl=&declutter(
1.638 albertel 9295: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9296: );
9297: }
9298: # ----------------------------------------------------------- Write preferences
1.84 www 9299: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9300: ('description' => $description,
9301: 'url' => $topurl,
9302: 'internal.creator' => $env{'user.name'}.':'.
9303: $env{'user.domain'},
9304: 'internal.created' => $now,
9305: 'internal.creationcontext' => $context)
9306: );
1.84 www 9307: return '/'.$udom.'/'.$uname;
9308: }
9309:
1.1011 raeburn 9310: # ------------------------------------------------------------------- Create ID
9311: sub generate_coursenum {
1.1038 raeburn 9312: my ($udom,$crstype) = @_;
1.1011 raeburn 9313: my $domdesc = &domain($udom);
9314: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9315: my $first;
9316: if ($crstype eq 'Community') {
9317: $first = '0';
9318: } else {
9319: $first = int(1+rand(9));
9320: }
9321: my $uname=$first.
1.1011 raeburn 9322: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9323: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9324: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9325: # ----------------------------------------------- Make sure that does not exist
9326: my $uhome=&homeserver($uname,$udom,'true');
9327: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9328: if ($crstype eq 'Community') {
9329: $first = '0';
9330: } else {
9331: $first = int(1+rand(9));
9332: }
9333: $uname=$first.
1.1011 raeburn 9334: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9335: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9336: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9337: $uhome=&homeserver($uname,$udom,'true');
9338: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9339: return 'error: unable to generate unique course-ID';
9340: }
9341: }
9342: return $uname;
9343: }
9344:
1.813 albertel 9345: sub is_course {
1.1167 droeschl 9346: my ($cdom, $cnum) = scalar(@_) == 1 ?
9347: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9348:
9349: return unless $cdom and $cnum;
9350:
9351: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9352: '.');
9353:
1.1172.2.23 raeburn 9354: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9355: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9356: }
9357:
1.1015 raeburn 9358: sub store_userdata {
9359: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9360: my $result;
1.1016 raeburn 9361: if ($datakey ne '') {
1.1013 raeburn 9362: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9363: if ($udom eq '' || $uname eq '') {
9364: $udom = $env{'user.domain'};
9365: $uname = $env{'user.name'};
9366: }
9367: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9368: if (($uhome eq '') || ($uhome eq 'no_host')) {
9369: $result = 'error: no_host';
9370: } else {
9371: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9372: $storehash->{'host'} = $perlvar{'lonHostID'};
9373:
9374: my $namevalue='';
9375: foreach my $key (keys(%{$storehash})) {
9376: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9377: }
9378: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9379: unless ($namespace eq 'courserequests') {
9380: $datakey = &escape($datakey);
9381: }
1.1105 raeburn 9382: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9383: $namevalue,$uhome);
1.1013 raeburn 9384: }
9385: } else {
9386: $result = 'error: data to store was not a hash reference';
9387: }
9388: } else {
9389: $result= 'error: invalid requestkey';
9390: }
9391: return $result;
9392: }
9393:
1.21 www 9394: # ---------------------------------------------------------- Assign Custom Role
9395:
9396: sub assigncustomrole {
1.957 raeburn 9397: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9398: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9399: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9400: }
9401:
9402: # ----------------------------------------------------------------- Revoke Role
9403:
9404: sub revokerole {
1.957 raeburn 9405: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9406: my $now=time;
1.965 raeburn 9407: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9408: }
9409:
9410: # ---------------------------------------------------------- Revoke Custom Role
9411:
9412: sub revokecustomrole {
1.957 raeburn 9413: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9414: my $now=time;
1.357 www 9415: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9416: $deleteflag,$selfenroll,$context);
1.17 www 9417: }
9418:
1.533 banghart 9419: # ------------------------------------------------------------ Disk usage
1.535 albertel 9420: sub diskusage {
1.955 raeburn 9421: my ($udom,$uname,$directorypath,$getpropath)=@_;
9422: $directorypath =~ s/\/$//;
9423: my $listing=&reply('du2:'.&escape($directorypath).':'
9424: .&escape($getpropath).':'.&escape($uname).':'
9425: .&escape($udom),homeserver($uname,$udom));
9426: if ($listing eq 'unknown_cmd') {
9427: if ($getpropath) {
9428: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9429: }
9430: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9431: }
1.514 albertel 9432: return $listing;
1.512 banghart 9433: }
9434:
1.566 banghart 9435: sub is_locked {
1.1096 raeburn 9436: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9437: my @check;
9438: my $is_locked;
1.1093 raeburn 9439: push (@check,$file_name);
1.613 albertel 9440: my %locked = &get('file_permissions',\@check,
1.620 albertel 9441: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9442: my ($tmp)=keys(%locked);
9443: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9444:
1.566 banghart 9445: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9446: $is_locked = 'false';
9447: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9448: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9449: $is_locked = 'true';
1.1096 raeburn 9450: if (ref($which) eq 'ARRAY') {
9451: push(@{$which},$entry);
9452: } else {
9453: last;
9454: }
1.745 raeburn 9455: }
9456: }
1.566 banghart 9457: } else {
9458: $is_locked = 'false';
9459: }
1.1093 raeburn 9460: return $is_locked;
1.566 banghart 9461: }
9462:
1.759 albertel 9463: sub declutter_portfile {
9464: my ($file) = @_;
1.833 albertel 9465: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9466: return $file;
9467: }
9468:
1.559 banghart 9469: # ------------------------------------------------------------- Mark as Read Only
9470:
9471: sub mark_as_readonly {
9472: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9473: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9474: my ($tmp)=keys(%current_permissions);
9475: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9476: foreach my $file (@{$files}) {
1.759 albertel 9477: $file = &declutter_portfile($file);
1.561 banghart 9478: push(@{$current_permissions{$file}},$what);
1.559 banghart 9479: }
1.613 albertel 9480: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9481: return;
9482: }
9483:
1.572 banghart 9484: # ------------------------------------------------------------Save Selected Files
9485:
9486: sub save_selected_files {
9487: my ($user, $path, @files) = @_;
9488: my $filename = $user."savedfiles";
1.573 banghart 9489: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9490: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9491: foreach my $file (@files) {
1.620 albertel 9492: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9493: }
9494: foreach my $file (@other_files) {
1.574 banghart 9495: print (OUT $file."\n");
1.572 banghart 9496: }
1.574 banghart 9497: close (OUT);
1.572 banghart 9498: return 'ok';
9499: }
9500:
1.574 banghart 9501: sub clear_selected_files {
9502: my ($user) = @_;
9503: my $filename = $user."savedfiles";
1.1117 foxr 9504: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9505: print (OUT undef);
9506: close (OUT);
9507: return ("ok");
9508: }
9509:
1.572 banghart 9510: sub files_in_path {
9511: my ($user, $path) = @_;
9512: my $filename = $user."savedfiles";
9513: my %return_files;
1.1117 foxr 9514: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9515: while (my $line_in = <IN>) {
1.574 banghart 9516: chomp ($line_in);
9517: my @paths_and_file = split (m!/!, $line_in);
9518: my $file_part = pop (@paths_and_file);
9519: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9520: $path_part.='/';
9521: my $path_and_file = $path_part.$file_part;
9522: if ($path_part eq $path) {
9523: $return_files{$file_part}= 'selected';
9524: }
9525: }
1.574 banghart 9526: close (IN);
9527: return (\%return_files);
1.572 banghart 9528: }
9529:
9530: # called in portfolio select mode, to show files selected NOT in current directory
9531: sub files_not_in_path {
9532: my ($user, $path) = @_;
9533: my $filename = $user."savedfiles";
9534: my @return_files;
9535: my $path_part;
1.1117 foxr 9536: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9537: while (my $line = <IN>) {
1.572 banghart 9538: #ok, I know it's clunky, but I want it to work
1.800 albertel 9539: my @paths_and_file = split(m|/|, $line);
9540: my $file_part = pop(@paths_and_file);
9541: chomp($file_part);
9542: my $path_part = join('/', @paths_and_file);
1.572 banghart 9543: $path_part .= '/';
9544: my $path_and_file = $path_part.$file_part;
9545: if ($path_part ne $path) {
1.800 albertel 9546: push(@return_files, ($path_and_file));
1.572 banghart 9547: }
9548: }
1.800 albertel 9549: close(OUT);
1.574 banghart 9550: return (@return_files);
1.572 banghart 9551: }
9552:
1.745 raeburn 9553: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9554:
1.745 raeburn 9555: sub get_portfile_permissions {
9556: my ($domain,$user) = @_;
1.613 albertel 9557: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9558: my ($tmp)=keys(%current_permissions);
9559: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9560: return \%current_permissions;
9561: }
9562:
9563: #---------------------------------------------Get portfolio file access controls
9564:
1.749 raeburn 9565: sub get_access_controls {
1.745 raeburn 9566: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9567: my %access;
9568: my $real_file = $file;
9569: $file =~ s/\.meta$//;
1.745 raeburn 9570: if (defined($file)) {
1.749 raeburn 9571: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9572: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9573: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9574: }
9575: }
1.745 raeburn 9576: } else {
1.749 raeburn 9577: foreach my $key (keys(%{$current_permissions})) {
9578: if ($key =~ /\0accesscontrol$/) {
9579: if (defined($group)) {
9580: if ($key !~ m-^\Q$group\E/-) {
9581: next;
9582: }
9583: }
9584: my ($fullpath) = split(/\0/,$key);
9585: if (ref($$current_permissions{$key}) eq 'HASH') {
9586: foreach my $control (keys(%{$$current_permissions{$key}})) {
9587: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9588: }
9589: }
9590: }
9591: }
9592: }
9593: return %access;
9594: }
9595:
9596: sub modify_access_controls {
9597: my ($file_name,$changes,$domain,$user)=@_;
9598: my ($outcome,$deloutcome);
9599: my %store_permissions;
9600: my %new_values;
9601: my %new_control;
9602: my %translation;
9603: my @deletions = ();
9604: my $now = time;
9605: if (exists($$changes{'activate'})) {
9606: if (ref($$changes{'activate'}) eq 'HASH') {
9607: my @newitems = sort(keys(%{$$changes{'activate'}}));
9608: my $numnew = scalar(@newitems);
9609: for (my $i=0; $i<$numnew; $i++) {
9610: my $newkey = $newitems[$i];
9611: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9612: if ($newkey =~ /^\d+:/) {
9613: $newkey =~ s/^(\d+)/$newid/;
9614: $translation{$1} = $newid;
9615: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9616: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9617: $translation{$1} = $newid;
9618: }
1.749 raeburn 9619: $new_values{$file_name."\0".$newkey} =
9620: $$changes{'activate'}{$newitems[$i]};
9621: $new_control{$newkey} = $now;
9622: }
9623: }
9624: }
9625: my %todelete;
9626: my %changed_items;
9627: foreach my $action ('delete','update') {
9628: if (exists($$changes{$action})) {
9629: if (ref($$changes{$action}) eq 'HASH') {
9630: foreach my $key (keys(%{$$changes{$action}})) {
9631: my ($itemnum) = ($key =~ /^([^:]+):/);
9632: if ($action eq 'delete') {
9633: $todelete{$itemnum} = 1;
9634: } else {
9635: $changed_items{$itemnum} = $key;
9636: }
9637: }
1.745 raeburn 9638: }
9639: }
1.749 raeburn 9640: }
9641: # get lock on access controls for file.
9642: my $lockhash = {
9643: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9644: ':'.$env{'user.domain'},
9645: };
9646: my $tries = 0;
9647: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9648:
1.1172.2.79 raeburn 9649: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9650: $tries ++;
1.1172.2.79 raeburn 9651: sleep(0.1);
1.749 raeburn 9652: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9653: }
9654: if ($gotlock eq 'ok') {
9655: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9656: my ($tmp)=keys(%curr_permissions);
9657: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9658: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9659: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9660: if (ref($curr_controls) eq 'HASH') {
9661: foreach my $control_item (keys(%{$curr_controls})) {
9662: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9663: if (defined($todelete{$itemnum})) {
9664: push(@deletions,$file_name."\0".$control_item);
9665: } else {
9666: if (defined($changed_items{$itemnum})) {
9667: $new_control{$changed_items{$itemnum}} = $now;
9668: push(@deletions,$file_name."\0".$control_item);
9669: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9670: } else {
9671: $new_control{$control_item} = $$curr_controls{$control_item};
9672: }
9673: }
1.745 raeburn 9674: }
9675: }
9676: }
1.970 raeburn 9677: my ($group);
9678: if (&is_course($domain,$user)) {
9679: ($group,my $file) = split(/\//,$file_name,2);
9680: }
1.749 raeburn 9681: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9682: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9683: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9684: # remove lock
9685: my @del_lock = ($file_name."\0".'locked_access_records');
9686: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9687: my $sqlresult =
1.970 raeburn 9688: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9689: $group);
1.749 raeburn 9690: } else {
9691: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9692: }
1.749 raeburn 9693: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9694: }
9695:
1.827 raeburn 9696: sub make_public_indefinitely {
9697: my ($requrl) = @_;
9698: my $now = time;
9699: my $action = 'activate';
9700: my $aclnum = 0;
9701: if (&is_portfolio_url($requrl)) {
9702: my (undef,$udom,$unum,$file_name,$group) =
9703: &parse_portfolio_url($requrl);
9704: my $current_perms = &get_portfile_permissions($udom,$unum);
9705: my %access_controls = &get_access_controls($current_perms,
9706: $group,$file_name);
9707: foreach my $key (keys(%{$access_controls{$file_name}})) {
9708: my ($num,$scope,$end,$start) =
9709: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9710: if ($scope eq 'public') {
9711: if ($start <= $now && $end == 0) {
9712: $action = 'none';
9713: } else {
9714: $action = 'update';
9715: $aclnum = $num;
9716: }
9717: last;
9718: }
9719: }
9720: if ($action eq 'none') {
9721: return 'ok';
9722: } else {
9723: my %changes;
9724: my $newend = 0;
9725: my $newstart = $now;
9726: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9727: $changes{$action}{$newkey} = {
9728: type => 'public',
9729: time => {
9730: start => $newstart,
9731: end => $newend,
9732: },
9733: };
9734: my ($outcome,$deloutcome,$new_values,$translation) =
9735: &modify_access_controls($file_name,\%changes,$udom,$unum);
9736: return $outcome;
9737: }
9738: } else {
9739: return 'invalid';
9740: }
9741: }
9742:
1.745 raeburn 9743: #------------------------------------------------------Get Marked as Read Only
9744:
9745: sub get_marked_as_readonly {
9746: my ($domain,$user,$what,$group) = @_;
9747: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9748: my @readonly_files;
1.629 banghart 9749: my $cmp1=$what;
9750: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9751: while (my ($file_name,$value) = each(%{$current_permissions})) {
9752: if (defined($group)) {
9753: if ($file_name !~ m-^\Q$group\E/-) {
9754: next;
9755: }
9756: }
1.561 banghart 9757: if (ref($value) eq "ARRAY"){
9758: foreach my $stored_what (@{$value}) {
1.629 banghart 9759: my $cmp2=$stored_what;
1.759 albertel 9760: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9761: $cmp2=join('',@{$stored_what});
1.745 raeburn 9762: }
1.629 banghart 9763: if ($cmp1 eq $cmp2) {
1.561 banghart 9764: push(@readonly_files, $file_name);
1.745 raeburn 9765: last;
1.563 banghart 9766: } elsif (!defined($what)) {
9767: push(@readonly_files, $file_name);
1.745 raeburn 9768: last;
1.561 banghart 9769: }
9770: }
1.745 raeburn 9771: }
1.561 banghart 9772: }
9773: return @readonly_files;
9774: }
1.577 banghart 9775: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9776:
1.577 banghart 9777: sub get_marked_as_readonly_hash {
1.745 raeburn 9778: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9779: my %readonly_files;
1.745 raeburn 9780: while (my ($file_name,$value) = each(%{$current_permissions})) {
9781: if (defined($group)) {
9782: if ($file_name !~ m-^\Q$group\E/-) {
9783: next;
9784: }
9785: }
1.577 banghart 9786: if (ref($value) eq "ARRAY"){
9787: foreach my $stored_what (@{$value}) {
1.745 raeburn 9788: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9789: foreach my $lock_descriptor(@{$stored_what}) {
9790: if ($lock_descriptor eq 'graded') {
9791: $readonly_files{$file_name} = 'graded';
9792: } elsif ($lock_descriptor eq 'handback') {
9793: $readonly_files{$file_name} = 'handback';
9794: } else {
9795: if (!exists($readonly_files{$file_name})) {
9796: $readonly_files{$file_name} = 'locked';
9797: }
9798: }
1.745 raeburn 9799: }
1.750 banghart 9800: }
1.577 banghart 9801: }
9802: }
9803: }
9804: return %readonly_files;
9805: }
1.559 banghart 9806: # ------------------------------------------------------------ Unmark as Read Only
9807:
9808: sub unmark_as_readonly {
1.629 banghart 9809: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9810: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9811: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9812: $file_name = &declutter_portfile($file_name);
1.634 albertel 9813: my $symb_crs = $what;
9814: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9815: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9816: my ($tmp)=keys(%current_permissions);
9817: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9818: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9819: foreach my $file (@readonly_files) {
1.759 albertel 9820: my $clean_file = &declutter_portfile($file);
9821: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9822: my $current_locks = $current_permissions{$file};
1.563 banghart 9823: my @new_locks;
9824: my @del_keys;
9825: if (ref($current_locks) eq "ARRAY"){
9826: foreach my $locker (@{$current_locks}) {
1.632 albertel 9827: my $compare=$locker;
1.749 raeburn 9828: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9829: $compare=join('',@{$locker});
1.746 raeburn 9830: if ($compare ne $symb_crs) {
9831: push(@new_locks, $locker);
9832: }
1.563 banghart 9833: }
9834: }
1.650 albertel 9835: if (scalar(@new_locks) > 0) {
1.563 banghart 9836: $current_permissions{$file} = \@new_locks;
9837: } else {
9838: push(@del_keys, $file);
1.613 albertel 9839: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9840: delete($current_permissions{$file});
1.563 banghart 9841: }
9842: }
1.561 banghart 9843: }
1.613 albertel 9844: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9845: return;
9846: }
1.512 banghart 9847:
1.17 www 9848: # ------------------------------------------------------------ Directory lister
9849:
9850: sub dirlist {
1.955 raeburn 9851: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9852: $uri=~s/^\///;
9853: $uri=~s/\/$//;
1.253 stredwic 9854: my ($udom, $uname);
1.955 raeburn 9855: if ($getuserdir) {
1.253 stredwic 9856: $udom = $userdomain;
9857: $uname = $username;
1.955 raeburn 9858: } else {
9859: (undef,$udom,$uname)=split(/\//,$uri);
9860: if(defined($userdomain)) {
9861: $udom = $userdomain;
9862: }
9863: if(defined($username)) {
9864: $uname = $username;
9865: }
1.253 stredwic 9866: }
1.955 raeburn 9867: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9868:
1.955 raeburn 9869: $dirRoot = $perlvar{'lonDocRoot'};
9870: if (defined($getpropath)) {
9871: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9872: $dirRoot =~ s/\/$//;
1.955 raeburn 9873: } elsif (defined($getuserdir)) {
9874: my $subdir=$uname.'__';
9875: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9876: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9877: ."/$udom/$subdir/$uname";
9878: } elsif (defined($alternateRoot)) {
9879: $dirRoot = $alternateRoot;
1.751 banghart 9880: }
1.253 stredwic 9881:
9882: if($udom) {
9883: if($uname) {
1.1135 raeburn 9884: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9885: if ($uhome eq 'no_host') {
9886: return ([],'no_host');
9887: }
1.955 raeburn 9888: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9889: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9890: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9891: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9892: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9893: } else {
9894: @listing_results = map { &unescape($_); } split(/:/,$listing);
9895: }
1.605 matthew 9896: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9897: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9898: @listing_results = split(/:/,$listing);
9899: } else {
9900: @listing_results = map { &unescape($_); } split(/:/,$listing);
9901: }
1.1135 raeburn 9902: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9903: ($listing eq 'rejected') || ($listing eq 'refused') ||
9904: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9905: return ([],$listing);
9906: } else {
9907: return (\@listing_results);
1.1135 raeburn 9908: }
1.955 raeburn 9909: } elsif(!$alternateRoot) {
1.1136 raeburn 9910: my (%allusers,%listerror);
1.841 albertel 9911: my %servers = &get_servers($udom,'library');
1.955 raeburn 9912: foreach my $tryserver (keys(%servers)) {
9913: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9914: &escape($udom),$tryserver);
9915: if ($listing eq 'unknown_cmd') {
9916: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9917: $udom, $tryserver);
9918: } else {
9919: @listing_results = map { &unescape($_); } split(/:/,$listing);
9920: }
1.841 albertel 9921: if ($listing eq 'unknown_cmd') {
9922: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9923: $udom, $tryserver);
9924: @listing_results = split(/:/,$listing);
9925: } else {
9926: @listing_results =
9927: map { &unescape($_); } split(/:/,$listing);
9928: }
1.1136 raeburn 9929: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9930: ($listing eq 'rejected') || ($listing eq 'refused') ||
9931: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9932: $listerror{$tryserver} = $listing;
9933: } else {
1.841 albertel 9934: foreach my $line (@listing_results) {
9935: my ($entry) = split(/&/,$line,2);
9936: $allusers{$entry} = 1;
9937: }
9938: }
1.253 stredwic 9939: }
1.1136 raeburn 9940: my @alluserslist=();
1.800 albertel 9941: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9942: push(@alluserslist,$user.'&user');
1.253 stredwic 9943: }
1.1172.2.80 raeburn 9944: if (!%listerror) {
9945: # no errors
9946: return (\@alluserslist);
9947: } elsif (scalar(keys(%servers)) == 1) {
9948: # one library server, one error
9949: my ($key) = keys(%listerror);
9950: return (\@alluserslist, $listerror{$key});
9951: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
9952: # con_lost indicates that we might miss data from at least one
9953: # library server
9954: return (\@alluserslist, 'con_lost');
9955: } else {
9956: # multiple library servers and no con_lost -> data should be
9957: # complete.
9958: return (\@alluserslist);
9959: }
9960:
1.253 stredwic 9961: } else {
1.1136 raeburn 9962: return ([],'missing username');
1.253 stredwic 9963: }
1.955 raeburn 9964: } elsif(!defined($getpropath)) {
1.1136 raeburn 9965: my $path = $perlvar{'lonDocRoot'}.'/res/';
9966: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9967: return (\@all_domains);
1.955 raeburn 9968: } else {
1.1136 raeburn 9969: return ([],'missing domain');
1.275 stredwic 9970: }
9971: }
9972:
9973: # --------------------------------------------- GetFileTimestamp
9974: # This function utilizes dirlist and returns the date stamp for
9975: # when it was last modified. It will also return an error of -1
9976: # if an error occurs
9977:
9978: sub GetFileTimestamp {
1.955 raeburn 9979: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9980: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9981: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9982: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9983: undef,$getuserdir);
9984: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9985: return -1;
9986: }
9987: if (ref($fileref) eq 'ARRAY') {
9988: my @stats = split('&',$fileref->[0]);
1.375 matthew 9989: # @stats contains first the filename, then the stat output
9990: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9991: } else {
9992: return -1;
1.253 stredwic 9993: }
1.26 www 9994: }
9995:
1.712 albertel 9996: sub stat_file {
9997: my ($uri) = @_;
1.787 albertel 9998: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9999:
1.955 raeburn 10000: my ($udom,$uname,$file);
1.712 albertel 10001: if ($uri =~ m-^/(uploaded|editupload)/-) {
10002: ($udom,$uname,$file) =
1.811 albertel 10003: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10004: $file = 'userfiles/'.$file;
10005: }
10006: if ($uri =~ m-^/res/-) {
10007: ($udom,$uname) =
1.807 albertel 10008: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10009: $file = $uri;
10010: }
10011:
10012: if (!$udom || !$uname || !$file) {
10013: # unable to handle the uri
10014: return ();
10015: }
1.956 raeburn 10016: my $getpropath;
10017: if ($file =~ /^userfiles\//) {
10018: $getpropath = 1;
10019: }
1.1136 raeburn 10020: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10021: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10022: return ();
10023: } else {
10024: if (ref($listref) eq 'ARRAY') {
10025: my @stats = split('&',$listref->[0]);
10026: shift(@stats); #filename is first
10027: return @stats;
10028: }
1.712 albertel 10029: }
10030: return ();
10031: }
10032:
1.26 www 10033: # -------------------------------------------------------- Value of a Condition
10034:
1.713 albertel 10035: # gets the value of a specific preevaluated condition
10036: # stored in the string $env{user.state.<cid>}
10037: # or looks up a condition reference in the bighash and if if hasn't
10038: # already been evaluated recurses into docondval to get the value of
10039: # the condition, then memoizing it to
10040: # $env{user.state.<cid>.<condition>}
1.40 www 10041: sub directcondval {
10042: my $number=shift;
1.620 albertel 10043: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10044: &Apache::lonuserstate::evalstate();
10045: }
1.713 albertel 10046: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10047: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10048: } elsif ($number =~ /^_/) {
10049: my $sub_condition;
10050: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10051: &GDBM_READER(),0640)) {
10052: $sub_condition=$bighash{'conditions'.$number};
10053: untie(%bighash);
10054: }
10055: my $value = &docondval($sub_condition);
1.949 raeburn 10056: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10057: return $value;
10058: }
1.620 albertel 10059: if ($env{'user.state.'.$env{'request.course.id'}}) {
10060: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10061: } else {
10062: return 2;
10063: }
10064: }
10065:
1.713 albertel 10066: # get the collection of conditions for this resource
1.26 www 10067: sub condval {
10068: my $condidx=shift;
1.54 www 10069: my $allpathcond='';
1.713 albertel 10070: foreach my $cond (split(/\|/,$condidx)) {
10071: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10072: $allpathcond.=
10073: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10074: }
1.191 harris41 10075: }
1.54 www 10076: $allpathcond=~s/\|$//;
1.713 albertel 10077: return &docondval($allpathcond);
10078: }
10079:
10080: #evaluates an expression of conditions
10081: sub docondval {
10082: my ($allpathcond) = @_;
10083: my $result=0;
10084: if ($env{'request.course.id'}
10085: && defined($allpathcond)) {
10086: my $operand='|';
10087: my @stack;
10088: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10089: if ($chunk eq '(') {
10090: push @stack,($operand,$result);
10091: } elsif ($chunk eq ')') {
10092: my $before=pop @stack;
10093: if (pop @stack eq '&') {
10094: $result=$result>$before?$before:$result;
10095: } else {
10096: $result=$result>$before?$result:$before;
10097: }
10098: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10099: $operand=$chunk;
10100: } else {
10101: my $new=directcondval($chunk);
10102: if ($operand eq '&') {
10103: $result=$result>$new?$new:$result;
10104: } else {
10105: $result=$result>$new?$result:$new;
10106: }
10107: }
10108: }
1.26 www 10109: }
10110: return $result;
1.421 albertel 10111: }
10112:
10113: # ---------------------------------------------------- Devalidate courseresdata
10114:
10115: sub devalidatecourseresdata {
10116: my ($coursenum,$coursedomain)=@_;
10117: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10118: &devalidate_cache_new('courseres',$hashid);
1.28 www 10119: }
10120:
1.763 www 10121:
1.200 www 10122: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10123: #
10124: # Parameters:
10125: # $coursenum - Number of the course.
10126: # $coursedomain - Domain at which the course was created.
10127: # Returns:
10128: # A hash of the course parameters along (I think) with timestamps
10129: # and version info.
1.877 foxr 10130:
1.624 albertel 10131: sub get_courseresdata {
10132: my ($coursenum,$coursedomain)=@_;
1.200 www 10133: my $coursehom=&homeserver($coursenum,$coursedomain);
10134: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10135: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10136: my %dumpreply;
1.417 albertel 10137: unless (defined($cached)) {
1.624 albertel 10138: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10139: $result=\%dumpreply;
1.251 albertel 10140: my ($tmp) = keys(%dumpreply);
10141: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10142: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10143: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10144: return $tmp;
1.416 albertel 10145: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10146: $result=undef;
1.599 albertel 10147: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10148: }
10149: }
1.624 albertel 10150: return $result;
10151: }
10152:
1.633 albertel 10153: sub devalidateuserresdata {
10154: my ($uname,$udom)=@_;
10155: my $hashid="$udom:$uname";
10156: &devalidate_cache_new('userres',$hashid);
10157: }
10158:
1.624 albertel 10159: sub get_userresdata {
10160: my ($uname,$udom)=@_;
10161: #most student don\'t have any data set, check if there is some data
10162: if (&EXT_cache_status($udom,$uname)) { return undef; }
10163:
10164: my $hashid="$udom:$uname";
10165: my ($result,$cached)=&is_cached_new('userres',$hashid);
10166: if (!defined($cached)) {
10167: my %resourcedata=&dump('resourcedata',$udom,$uname);
10168: $result=\%resourcedata;
10169: &do_cache_new('userres',$hashid,$result,600);
10170: }
10171: my ($tmp)=keys(%$result);
10172: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10173: return $result;
10174: }
10175: #error 2 occurs when the .db doesn't exist
10176: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10177: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10178: &logthis("<font color=\"blue\">WARNING:".
10179: " Trying to get resource data for ".
10180: $uname." at ".$udom.": ".
10181: $tmp."</font>");
10182: }
1.624 albertel 10183: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10184: #&EXT_cache_set($udom,$uname);
10185: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10186: undef($tmp); # not really an error so don't send it back
1.624 albertel 10187: }
10188: return $tmp;
10189: }
1.879 foxr 10190: #----------------------------------------------- resdata - return resource data
10191: # Purpose:
10192: # Return resource data for either users or for a course.
10193: # Parameters:
10194: # $name - Course/user name.
10195: # $domain - Name of the domain the user/course is registered on.
10196: # $type - Type of thing $name is (must be 'course' or 'user'
10197: # @which - Array of names of resources desired.
10198: # Returns:
10199: # The value of the first reasource in @which that is found in the
10200: # resource hash.
10201: # Exceptional Conditions:
10202: # If the $type passed in is not valid (not the string 'course' or
10203: # 'user', an undefined reference is returned.
10204: # If none of the resources are found, an undef is returned
1.624 albertel 10205: sub resdata {
10206: my ($name,$domain,$type,@which)=@_;
10207: my $result;
10208: if ($type eq 'course') {
10209: $result=&get_courseresdata($name,$domain);
10210: } elsif ($type eq 'user') {
10211: $result=&get_userresdata($name,$domain);
10212: }
10213: if (!ref($result)) { return $result; }
1.251 albertel 10214: foreach my $item (@which) {
1.927 albertel 10215: if (defined($result->{$item->[0]})) {
10216: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10217: }
1.250 albertel 10218: }
1.291 albertel 10219: return undef;
1.200 www 10220: }
10221:
1.1172.2.31 raeburn 10222: sub get_numsuppfiles {
10223: my ($cnum,$cdom,$ignorecache)=@_;
10224: my $hashid=$cnum.':'.$cdom;
10225: my ($suppcount,$cached);
10226: unless ($ignorecache) {
10227: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10228: }
10229: unless (defined($cached)) {
10230: my $chome=&homeserver($cnum,$cdom);
10231: unless ($chome eq 'no_host') {
10232: ($suppcount,my $errors) = (0,0);
10233: my $suppmap = 'supplemental.sequence';
10234: ($suppcount,$errors) =
10235: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10236: }
10237: &do_cache_new('suppcount',$hashid,$suppcount,600);
10238: }
10239: return $suppcount;
10240: }
10241:
1.379 matthew 10242: #
10243: # EXT resource caching routines
10244: #
10245:
10246: sub clear_EXT_cache_status {
1.383 albertel 10247: &delenv('cache.EXT.');
1.379 matthew 10248: }
10249:
10250: sub EXT_cache_status {
10251: my ($target_domain,$target_user) = @_;
1.383 albertel 10252: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10253: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10254: # We know already the user has no data
10255: return 1;
10256: } else {
10257: return 0;
10258: }
10259: }
10260:
10261: sub EXT_cache_set {
10262: my ($target_domain,$target_user) = @_;
1.383 albertel 10263: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10264: #&appenv({$cachename => time});
1.379 matthew 10265: }
10266:
1.28 www 10267: # --------------------------------------------------------- Value of a Variable
1.58 www 10268: sub EXT {
1.715 albertel 10269:
1.1172.2.28 raeburn 10270: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10271: unless ($varname) { return ''; }
1.218 albertel 10272: #get real user name/domain, courseid and symb
10273: my $courseid;
1.359 albertel 10274: my $publicuser;
1.427 www 10275: if ($symbparm) {
10276: $symbparm=&get_symb_from_alias($symbparm);
10277: }
1.218 albertel 10278: if (!($uname && $udom)) {
1.790 albertel 10279: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10280: if (!$symbparm) { $symbparm=$cursymb; }
10281: } else {
1.620 albertel 10282: $courseid=$env{'request.course.id'};
1.218 albertel 10283: }
1.48 www 10284: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10285: my $rest;
1.320 albertel 10286: if (defined($therest[0])) {
1.48 www 10287: $rest=join('.',@therest);
10288: } else {
10289: $rest='';
10290: }
1.320 albertel 10291:
1.57 www 10292: my $qualifierrest=$qualifier;
10293: if ($rest) { $qualifierrest.='.'.$rest; }
10294: my $spacequalifierrest=$space;
10295: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10296: if ($realm eq 'user') {
1.48 www 10297: # --------------------------------------------------------------- user.resource
10298: if ($space eq 'resource') {
1.651 albertel 10299: if ( (defined($Apache::lonhomework::parsing_a_problem)
10300: || defined($Apache::lonhomework::parsing_a_task))
10301: &&
1.744 albertel 10302: ($symbparm eq &symbread()) ) {
10303: # if we are in the middle of processing the resource the
10304: # get the value we are planning on committing
10305: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10306: return $Apache::lonhomework::results{$qualifierrest};
10307: } else {
10308: return $Apache::lonhomework::history{$qualifierrest};
10309: }
1.335 albertel 10310: } else {
1.359 albertel 10311: my %restored;
1.620 albertel 10312: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10313: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10314: } else {
10315: %restored=&restore($symbparm,$courseid,$udom,$uname);
10316: }
1.335 albertel 10317: return $restored{$qualifierrest};
10318: }
1.48 www 10319: # ----------------------------------------------------------------- user.access
10320: } elsif ($space eq 'access') {
1.218 albertel 10321: # FIXME - not supporting calls for a specific user
1.48 www 10322: return &allowed($qualifier,$rest);
10323: # ------------------------------------------ user.preferences, user.environment
10324: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10325: if (($uname eq $env{'user.name'}) &&
10326: ($udom eq $env{'user.domain'})) {
10327: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10328: } else {
1.359 albertel 10329: my %returnhash;
10330: if (!$publicuser) {
10331: %returnhash=&userenvironment($udom,$uname,
10332: $qualifierrest);
10333: }
1.218 albertel 10334: return $returnhash{$qualifierrest};
10335: }
1.48 www 10336: # ----------------------------------------------------------------- user.course
10337: } elsif ($space eq 'course') {
1.218 albertel 10338: # FIXME - not supporting calls for a specific user
1.620 albertel 10339: return $env{join('.',('request.course',$qualifier))};
1.48 www 10340: # ------------------------------------------------------------------- user.role
10341: } elsif ($space eq 'role') {
1.218 albertel 10342: # FIXME - not supporting calls for a specific user
1.620 albertel 10343: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10344: if ($qualifier eq 'value') {
10345: return $role;
10346: } elsif ($qualifier eq 'extent') {
10347: return $where;
10348: }
10349: # ----------------------------------------------------------------- user.domain
10350: } elsif ($space eq 'domain') {
1.218 albertel 10351: return $udom;
1.48 www 10352: # ------------------------------------------------------------------- user.name
10353: } elsif ($space eq 'name') {
1.218 albertel 10354: return $uname;
1.48 www 10355: # ---------------------------------------------------- Any other user namespace
1.29 www 10356: } else {
1.359 albertel 10357: my %reply;
10358: if (!$publicuser) {
10359: %reply=&get($space,[$qualifierrest],$udom,$uname);
10360: }
10361: return $reply{$qualifierrest};
1.48 www 10362: }
1.236 www 10363: } elsif ($realm eq 'query') {
10364: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10365: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10366: [$spacequalifierrest]);
1.620 albertel 10367: return $env{'form.'.$spacequalifierrest};
1.236 www 10368: } elsif ($realm eq 'request') {
1.48 www 10369: # ------------------------------------------------------------- request.browser
10370: if ($space eq 'browser') {
1.1145 bisitz 10371: return $env{'browser.'.$qualifier};
1.57 www 10372: # ------------------------------------------------------------ request.filename
10373: } else {
1.620 albertel 10374: return $env{'request.'.$spacequalifierrest};
1.29 www 10375: }
1.28 www 10376: } elsif ($realm eq 'course') {
1.48 www 10377: # ---------------------------------------------------------- course.description
1.620 albertel 10378: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10379: } elsif ($realm eq 'resource') {
1.165 www 10380:
1.620 albertel 10381: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10382: if (!$symbparm) { $symbparm=&symbread(); }
10383: }
1.693 albertel 10384:
1.1172.2.30 raeburn 10385: if ($qualifier eq '') {
10386: if ($space eq 'title') {
10387: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10388: return &gettitle($symbparm);
10389: }
1.693 albertel 10390:
1.1172.2.30 raeburn 10391: if ($space eq 'map') {
10392: my ($map) = &decode_symb($symbparm);
10393: return &symbread($map);
10394: }
10395: if ($space eq 'maptitle') {
10396: my ($map) = &decode_symb($symbparm);
10397: return &gettitle($map);
10398: }
10399: if ($space eq 'filename') {
10400: if ($symbparm) {
10401: return &clutter((&decode_symb($symbparm))[2]);
10402: }
10403: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10404: }
1.1172.2.30 raeburn 10405:
10406: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10407: if ($space eq 'visibleparts') {
10408: my $navmap = Apache::lonnavmaps::navmap->new();
10409: my $item;
10410: if (ref($navmap)) {
10411: my $res = $navmap->getBySymb($symbparm);
10412: my $parts = $res->parts();
10413: if (ref($parts) eq 'ARRAY') {
10414: $item = join(',',@{$parts});
10415: }
10416: undef($navmap);
10417: }
10418: return $item;
10419: }
10420: }
10421: }
1.693 albertel 10422:
10423: my ($section, $group, @groups);
1.593 albertel 10424: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10425: if (($courseid eq '') && ($cid)) {
10426: $courseid = $cid;
10427: }
10428: if (($symbparm && $courseid) &&
10429: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10430:
1.218 albertel 10431: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10432:
1.60 www 10433: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10434: my $symbp=$symbparm;
1.735 albertel 10435: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10436:
10437: my $symbparm=$symbp.'.'.$spacequalifierrest;
10438: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10439:
1.620 albertel 10440: if (($env{'user.name'} eq $uname) &&
10441: ($env{'user.domain'} eq $udom)) {
10442: $section=$env{'request.course.sec'};
1.733 raeburn 10443: @groups = split(/:/,$env{'request.course.groups'});
10444: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10445: } else {
1.539 albertel 10446: if (! defined($usection)) {
1.551 albertel 10447: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10448: } else {
10449: $section = $usection;
10450: }
1.733 raeburn 10451: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10452: }
10453:
10454: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10455: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10456: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10457:
1.593 albertel 10458: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10459: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10460: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10461:
1.60 www 10462: # ----------------------------------------------------------- first, check user
1.624 albertel 10463:
10464: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10465: ([$courselevelr,'resource'],
10466: [$courselevelm,'map' ],
10467: [$courselevel, 'course' ]));
1.931 albertel 10468: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10469:
1.594 albertel 10470: # ------------------------------------------------ second, check some of course
1.684 raeburn 10471: my $coursereply;
1.691 raeburn 10472: if (@groups > 0) {
10473: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10474: $mapparm,$spacequalifierrest);
1.927 albertel 10475: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10476: }
1.96 www 10477:
1.684 raeburn 10478: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10479: $env{'course.'.$courseid.'.domain'},
10480: 'course',
10481: ([$seclevelr, 'resource'],
10482: [$seclevelm, 'map' ],
10483: [$seclevel, 'course' ],
10484: [$courselevelr,'resource']));
10485: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10486:
1.60 www 10487: # ------------------------------------------------------ third, check map parms
1.218 albertel 10488: my %parmhash=();
10489: my $thisparm='';
10490: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10491: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10492: &GDBM_READER(),0640)) {
1.218 albertel 10493: $thisparm=$parmhash{$symbparm};
10494: untie(%parmhash);
10495: }
1.927 albertel 10496: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10497: }
1.594 albertel 10498: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10499:
1.218 albertel 10500: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10501: my $filename;
10502: if (!$symbparm) { $symbparm=&symbread(); }
10503: if ($symbparm) {
1.409 www 10504: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10505: } else {
1.620 albertel 10506: $filename=$env{'request.filename'};
1.282 albertel 10507: }
10508: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10509: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10510: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10511: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10512:
1.927 albertel 10513: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10514: if ($symbparm && defined($courseid) &&
1.620 albertel 10515: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10516: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10517: $env{'course.'.$courseid.'.domain'},
10518: 'course',
1.927 albertel 10519: ([$courselevelm,'map' ],
10520: [$courselevel, 'course']));
10521: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10522: }
1.145 www 10523: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10524: unless ($space eq '0') {
1.336 albertel 10525: my @parts=split(/_/,$space);
10526: my $id=pop(@parts);
10527: my $part=join('_',@parts);
10528: if ($part eq '') { $part='0'; }
1.927 albertel 10529: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10530: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10531: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10532: }
1.395 albertel 10533: if ($recurse) { return undef; }
10534: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10535: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10536: # ---------------------------------------------------- Any other user namespace
10537: } elsif ($realm eq 'environment') {
10538: # ----------------------------------------------------------------- environment
1.620 albertel 10539: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10540: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10541: } else {
1.770 albertel 10542: if ($uname eq 'anonymous' && $udom eq '') {
10543: return '';
10544: }
1.219 albertel 10545: my %returnhash=&userenvironment($udom,$uname,
10546: $spacequalifierrest);
10547: return $returnhash{$spacequalifierrest};
10548: }
1.28 www 10549: } elsif ($realm eq 'system') {
1.48 www 10550: # ----------------------------------------------------------------- system.time
10551: if ($space eq 'time') {
10552: return time;
10553: }
1.696 albertel 10554: } elsif ($realm eq 'server') {
10555: # ----------------------------------------------------------------- system.time
10556: if ($space eq 'name') {
10557: return $ENV{'SERVER_NAME'};
10558: }
1.28 www 10559: }
1.48 www 10560: return '';
1.61 www 10561: }
10562:
1.927 albertel 10563: sub get_reply {
10564: my ($reply_value) = @_;
1.940 raeburn 10565: if (ref($reply_value) eq 'ARRAY') {
10566: if (wantarray) {
10567: return @$reply_value;
10568: }
10569: return $reply_value->[0];
10570: } else {
10571: return $reply_value;
1.927 albertel 10572: }
10573: }
10574:
1.691 raeburn 10575: sub check_group_parms {
10576: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10577: my @groupitems = ();
10578: my $resultitem;
1.927 albertel 10579: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10580: foreach my $group (@{$groups}) {
10581: foreach my $level (@levels) {
1.927 albertel 10582: my $item = $courseid.'.['.$group.'].'.$level->[0];
10583: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10584: }
10585: }
10586: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10587: $env{'course.'.$courseid.'.domain'},
10588: 'course',@groupitems);
10589: return $coursereply;
10590: }
10591:
10592: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10593: my ($courseid,@groups) = @_;
10594: @groups = sort(@groups);
1.691 raeburn 10595: return @groups;
10596: }
10597:
1.395 albertel 10598: sub packages_tab_default {
10599: my ($uri,$varname)=@_;
10600: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10601:
10602: my (@extension,@specifics,$do_default);
10603: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10604: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10605: if ($pack_type eq 'default') {
10606: $do_default=1;
10607: } elsif ($pack_type eq 'extension') {
10608: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10609: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10610: # only look at packages defaults for packages that this id is
1.738 albertel 10611: push(@specifics,[$package,$pack_type,$pack_part]);
10612: }
10613: }
10614: # first look for a package that matches the requested part id
10615: foreach my $package (@specifics) {
10616: my (undef,$pack_type,$pack_part)=@{$package};
10617: next if ($pack_part ne $part);
10618: if (defined($packagetab{"$pack_type&$name&default"})) {
10619: return $packagetab{"$pack_type&$name&default"};
10620: }
10621: }
10622: # look for any possible matching non extension_ package
10623: foreach my $package (@specifics) {
10624: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10625: if (defined($packagetab{"$pack_type&$name&default"})) {
10626: return $packagetab{"$pack_type&$name&default"};
10627: }
1.585 albertel 10628: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10629: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10630: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10631: }
10632: }
1.738 albertel 10633: # look for any posible extension_ match
10634: foreach my $package (@extension) {
10635: my ($package,$pack_type)=@{$package};
10636: if (defined($packagetab{"$pack_type&$name&default"})) {
10637: return $packagetab{"$pack_type&$name&default"};
10638: }
10639: if (defined($packagetab{$package."&$name&default"})) {
10640: return $packagetab{$package."&$name&default"};
10641: }
10642: }
10643: # look for a global default setting
10644: if ($do_default && defined($packagetab{"default&$name&default"})) {
10645: return $packagetab{"default&$name&default"};
10646: }
1.395 albertel 10647: return undef;
10648: }
10649:
1.334 albertel 10650: sub add_prefix_and_part {
10651: my ($prefix,$part)=@_;
10652: my $keyroot;
10653: if (defined($prefix) && $prefix !~ /^__/) {
10654: # prefix that has a part already
10655: $keyroot=$prefix;
10656: } elsif (defined($prefix)) {
10657: # prefix that is missing a part
10658: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10659: } else {
10660: # no prefix at all
10661: if (defined($part)) { $keyroot='_'.$part; }
10662: }
10663: return $keyroot;
10664: }
10665:
1.71 www 10666: # ---------------------------------------------------------------- Get metadata
10667:
1.599 albertel 10668: my %metaentry;
1.1070 www 10669: my %importedpartids;
1.71 www 10670: sub metadata {
1.176 www 10671: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10672: $uri=&declutter($uri);
1.288 albertel 10673: # if it is a non metadata possible uri return quickly
1.529 albertel 10674: if (($uri eq '') ||
10675: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10676: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10677: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10678: return undef;
10679: }
1.1172.2.49 raeburn 10680: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10681: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10682: return undef;
1.288 albertel 10683: }
1.73 www 10684: my $filename=$uri;
10685: $uri=~s/\.meta$//;
1.172 www 10686: #
10687: # Is the metadata already cached?
1.177 www 10688: # Look at timestamp of caching
1.172 www 10689: # Everything is cached by the main uri, libraries are never directly cached
10690: #
1.428 albertel 10691: if (!defined($liburi)) {
1.599 albertel 10692: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10693: if (defined($cached)) { return $result->{':'.$what}; }
10694: }
10695: {
1.1069 www 10696: # Imported parts would go here
1.1070 www 10697: my %importedids=();
10698: my @origfileimportpartids=();
1.1069 www 10699: my $importedparts=0;
1.172 www 10700: #
10701: # Is this a recursive call for a library?
10702: #
1.599 albertel 10703: # if (! exists($metacache{$uri})) {
10704: # $metacache{$uri}={};
10705: # }
1.924 albertel 10706: my $cachetime = 60*60;
1.171 www 10707: if ($liburi) {
10708: $liburi=&declutter($liburi);
10709: $filename=$liburi;
1.401 bowersj2 10710: } else {
1.599 albertel 10711: &devalidate_cache_new('meta',$uri);
10712: undef(%metaentry);
1.401 bowersj2 10713: }
1.140 www 10714: my %metathesekeys=();
1.73 www 10715: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10716: my $metastring;
1.1140 www 10717: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10718: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10719: $metastring =
1.929 albertel 10720: &Apache::lonnet::ssi_body($which,
1.924 albertel 10721: ('grade_target' => 'meta'));
10722: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10723: } elsif (($uri !~ m -^(editupload)/-) &&
10724: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10725: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10726: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10727: $metastring=&getfile($file);
1.489 albertel 10728: }
1.208 albertel 10729: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10730: my $token;
1.140 www 10731: undef %metathesekeys;
1.71 www 10732: while ($token=$parser->get_token) {
1.339 albertel 10733: if ($token->[0] eq 'S') {
10734: if (defined($token->[2]->{'package'})) {
1.172 www 10735: #
10736: # This is a package - get package info
10737: #
1.339 albertel 10738: my $package=$token->[2]->{'package'};
10739: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10740: if (defined($token->[2]->{'id'})) {
10741: $keyroot.='_'.$token->[2]->{'id'};
10742: }
1.599 albertel 10743: if ($metaentry{':packages'}) {
10744: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10745: } else {
1.599 albertel 10746: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10747: }
1.736 albertel 10748: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10749: my $part=$keyroot;
10750: $part=~s/^\_//;
1.736 albertel 10751: if ($pack_entry=~/^\Q$package\E\&/ ||
10752: $pack_entry=~/^\Q$package\E_0\&/) {
10753: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10754: # ignore package.tab specified default values
10755: # here &package_tab_default() will fetch those
10756: if ($subp eq 'default') { next; }
1.736 albertel 10757: my $value=$packagetab{$pack_entry};
1.432 albertel 10758: my $unikey;
10759: if ($pack =~ /_0$/) {
10760: $unikey='parameter_0_'.$name;
10761: $part=0;
10762: } else {
10763: $unikey='parameter'.$keyroot.'_'.$name;
10764: }
1.339 albertel 10765: if ($subp eq 'display') {
10766: $value.=' [Part: '.$part.']';
10767: }
1.599 albertel 10768: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10769: $metathesekeys{$unikey}=1;
1.599 albertel 10770: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10771: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10772: }
1.599 albertel 10773: if (defined($metaentry{':'.$unikey.'.default'})) {
10774: $metaentry{':'.$unikey}=
10775: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10776: }
1.339 albertel 10777: }
10778: }
10779: } else {
1.172 www 10780: #
10781: # This is not a package - some other kind of start tag
1.339 albertel 10782: #
10783: my $entry=$token->[1];
1.1068 www 10784: my $unikey='';
1.175 www 10785:
1.339 albertel 10786: if ($entry eq 'import') {
1.175 www 10787: #
10788: # Importing a library here
1.339 albertel 10789: #
1.1067 www 10790: my $location=$parser->get_text('/import');
10791: my $dir=$filename;
10792: $dir=~s|[^/]*$||;
10793: $location=&filelocation($dir,$location);
1.1069 www 10794:
1.1068 www 10795: my $importmode=$token->[2]->{'importmode'};
10796: if ($importmode eq 'problem') {
1.1069 www 10797: # Import as problem/response
1.1068 www 10798: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10799: } elsif ($importmode eq 'part') {
10800: # Import as part(s)
1.1069 www 10801: $importedparts=1;
10802: # We need to get the original file and the imported file to get the part order correct
10803: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10804: # Load and inspect original file
1.1070 www 10805: if ($#origfileimportpartids<0) {
10806: undef(%importedpartids);
10807: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10808: my $origfile=&getfile($origfilelocation);
10809: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10810: }
10811:
1.1069 www 10812: # Load and inspect imported file
10813: my $impfile=&getfile($location);
10814: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10815: if ($#impfilepartids>=0) {
10816: # This problem had parts
1.1070 www 10817: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10818: } else {
10819: # Importing by turning a single problem into a problem part
10820: # It gets the import-tags ID as part-ID
10821: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10822: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10823: }
1.1068 www 10824: } else {
10825: # Normal import
10826: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10827: if (defined($token->[2]->{'id'})) {
10828: $unikey.='_'.$token->[2]->{'id'};
10829: }
1.1067 www 10830: }
10831:
1.339 albertel 10832: if ($depthcount<20) {
1.736 albertel 10833: my $metadata =
10834: &metadata($uri,'keys', $location,$unikey,
10835: $depthcount+1);
10836: foreach my $meta (split(',',$metadata)) {
10837: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10838: $metathesekeys{$meta}=1;
1.339 albertel 10839: }
1.1068 www 10840:
10841: }
1.1067 www 10842: } else {
10843: #
10844: # Not importing, some other kind of non-package, non-library start tag
10845: #
10846: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10847: if (defined($token->[2]->{'id'})) {
10848: $unikey.='_'.$token->[2]->{'id'};
10849: }
1.339 albertel 10850: if (defined($token->[2]->{'name'})) {
10851: $unikey.='_'.$token->[2]->{'name'};
10852: }
10853: $metathesekeys{$unikey}=1;
1.736 albertel 10854: foreach my $param (@{$token->[3]}) {
10855: $metaentry{':'.$unikey.'.'.$param} =
10856: $token->[2]->{$param};
1.339 albertel 10857: }
10858: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10859: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10860: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10861: # only ws inside the tag, and not in default, so use default
10862: # as value
1.599 albertel 10863: $metaentry{':'.$unikey}=$default;
1.908 albertel 10864: } elsif ( $internaltext =~ /\S/ ) {
10865: # something interesting inside the tag
10866: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10867: } else {
1.908 albertel 10868: # no interesting values, don't set a default
1.339 albertel 10869: }
1.172 www 10870: # end of not-a-package not-a-library import
1.339 albertel 10871: }
1.172 www 10872: # end of not-a-package start tag
1.339 albertel 10873: }
1.172 www 10874: # the next is the end of "start tag"
1.339 albertel 10875: }
10876: }
1.483 albertel 10877: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10878: $extension = lc($extension);
10879: if ($extension eq 'htm') { $extension='html'; }
10880:
1.737 albertel 10881: foreach my $key (keys(%packagetab)) {
1.483 albertel 10882: #no specific packages #how's our extension
10883: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10884: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10885: \%metathesekeys);
10886: }
1.883 albertel 10887:
10888: if (!exists($metaentry{':packages'})
10889: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10890: foreach my $key (keys(%packagetab)) {
1.483 albertel 10891: #no specific packages well let's get default then
10892: if ($key!~/^default&/) { next; }
1.488 albertel 10893: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10894: \%metathesekeys);
10895: }
10896: }
1.338 www 10897: # are there custom rights to evaluate
1.599 albertel 10898: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10899:
1.338 www 10900: #
10901: # Importing a rights file here
1.339 albertel 10902: #
10903: unless ($depthcount) {
1.599 albertel 10904: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10905: my $dir=$filename;
10906: $dir=~s|[^/]*$||;
10907: $location=&filelocation($dir,$location);
1.736 albertel 10908: my $rights_metadata =
10909: &metadata($uri,'keys',$location,'_rights',
10910: $depthcount+1);
10911: foreach my $rights (split(',',$rights_metadata)) {
10912: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10913: $metathesekeys{$rights}=1;
1.339 albertel 10914: }
10915: }
10916: }
1.737 albertel 10917: # uniqifiy package listing
10918: my %seen;
10919: my @uniq_packages =
10920: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10921: $metaentry{':packages'} = join(',',@uniq_packages);
10922:
1.1070 www 10923: if ($importedparts) {
10924: # We had imported parts and need to rebuild partorder
10925: $metaentry{':partorder'}='';
10926: $metathesekeys{'partorder'}=1;
10927: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10928: if ($origfileimportpartids[$index] eq 'part') {
10929: # original part, part of the problem
10930: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10931: } else {
10932: # we have imported parts at this position
10933: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10934: }
10935: }
10936: $metaentry{':partorder'}=~s/^\,//;
10937: }
10938:
1.737 albertel 10939: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10940: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10941: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10942: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10943: # this is the end of "was not already recently cached
1.71 www 10944: }
1.599 albertel 10945: return $metaentry{':'.$what};
1.261 albertel 10946: }
10947:
1.488 albertel 10948: sub metadata_create_package_def {
1.483 albertel 10949: my ($uri,$key,$package,$metathesekeys)=@_;
10950: my ($pack,$name,$subp)=split(/\&/,$key);
10951: if ($subp eq 'default') { next; }
10952:
1.599 albertel 10953: if (defined($metaentry{':packages'})) {
10954: $metaentry{':packages'}.=','.$package;
1.483 albertel 10955: } else {
1.599 albertel 10956: $metaentry{':packages'}=$package;
1.483 albertel 10957: }
10958: my $value=$packagetab{$key};
10959: my $unikey;
10960: $unikey='parameter_0_'.$name;
1.599 albertel 10961: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10962: $$metathesekeys{$unikey}=1;
1.599 albertel 10963: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10964: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10965: }
1.599 albertel 10966: if (defined($metaentry{':'.$unikey.'.default'})) {
10967: $metaentry{':'.$unikey}=
10968: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10969: }
10970: }
10971:
1.261 albertel 10972: sub metadata_generate_part0 {
10973: my ($metadata,$metacache,$uri) = @_;
10974: my %allnames;
1.737 albertel 10975: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10976: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10977: my $part=$$metacache{':'.$metakey.'.part'};
10978: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10979: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10980: $allnames{$name}=$part;
10981: }
10982: }
10983: }
10984: foreach my $name (keys(%allnames)) {
10985: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10986: my $key=":parameter_0_$name";
1.261 albertel 10987: $$metacache{"$key.part"}='0';
10988: $$metacache{"$key.name"}=$name;
1.428 albertel 10989: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10990: $allnames{$name}.'_'.$name.
10991: '.type'};
1.428 albertel 10992: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10993: '.display'};
1.644 www 10994: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10995: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10996: $$metacache{"$key.display"}=$olddis;
10997: }
1.71 www 10998: }
10999:
1.764 albertel 11000: # ------------------------------------------------------ Devalidate title cache
11001:
11002: sub devalidate_title_cache {
11003: my ($url)=@_;
11004: if (!$env{'request.course.id'}) { return; }
11005: my $symb=&symbread($url);
11006: if (!$symb) { return; }
11007: my $key=$env{'request.course.id'}."\0".$symb;
11008: &devalidate_cache_new('title',$key);
11009: }
11010:
1.1014 droeschl 11011: # ------------------------------------------------- Get the title of a course
11012:
11013: sub current_course_title {
11014: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11015: }
1.301 www 11016: # ------------------------------------------------- Get the title of a resource
11017:
11018: sub gettitle {
11019: my $urlsymb=shift;
11020: my $symb=&symbread($urlsymb);
1.534 albertel 11021: if ($symb) {
1.620 albertel 11022: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11023: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11024: if (defined($cached)) {
11025: return $result;
11026: }
1.534 albertel 11027: my ($map,$resid,$url)=&decode_symb($symb);
11028: my $title='';
1.907 albertel 11029: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11030: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11031: } else {
11032: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11033: &GDBM_READER(),0640)) {
11034: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11035: $title=$bighash{'title_'.$mapid.'.'.$resid};
11036: untie(%bighash);
11037: }
1.534 albertel 11038: }
11039: $title=~s/\&colon\;/\:/gs;
11040: if ($title) {
1.1159 www 11041: # Remember both $symb and $title for dynamic metadata
11042: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11043: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11044: # Cache this title and then return it
1.599 albertel 11045: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11046: }
11047: $urlsymb=$url;
11048: }
11049: my $title=&metadata($urlsymb,'title');
11050: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11051: return $title;
1.301 www 11052: }
1.613 albertel 11053:
1.614 albertel 11054: sub get_slot {
11055: my ($which,$cnum,$cdom)=@_;
11056: if (!$cnum || !$cdom) {
1.790 albertel 11057: (undef,my $courseid)=&whichuser();
1.620 albertel 11058: $cdom=$env{'course.'.$courseid.'.domain'};
11059: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11060: }
1.703 albertel 11061: my $key=join("\0",'slots',$cdom,$cnum,$which);
11062: my %slotinfo;
11063: if (exists($remembered{$key})) {
11064: $slotinfo{$which} = $remembered{$key};
11065: } else {
11066: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11067: &Apache::lonhomework::showhash(%slotinfo);
11068: my ($tmp)=keys(%slotinfo);
11069: if ($tmp=~/^error:/) { return (); }
11070: $remembered{$key} = $slotinfo{$which};
11071: }
1.616 albertel 11072: if (ref($slotinfo{$which}) eq 'HASH') {
11073: return %{$slotinfo{$which}};
11074: }
11075: return $slotinfo{$which};
1.614 albertel 11076: }
1.1150 raeburn 11077:
11078: sub get_reservable_slots {
11079: my ($cnum,$cdom,$uname,$udom) = @_;
11080: my $now = time;
11081: my $reservable_info;
11082: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11083: if (exists($remembered{$key})) {
11084: $reservable_info = $remembered{$key};
11085: } else {
11086: my %resv;
11087: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11088: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11089: $reservable_info = \%resv;
11090: $remembered{$key} = $reservable_info;
11091: }
11092: return $reservable_info;
11093: }
11094:
11095: sub get_course_slots {
11096: my ($cnum,$cdom) = @_;
11097: my $hashid=$cnum.':'.$cdom;
11098: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11099: if (defined($cached)) {
11100: if (ref($result) eq 'HASH') {
11101: return %{$result};
11102: }
11103: } else {
11104: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11105: my ($tmp) = keys(%slots);
11106: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11107: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11108: return %slots;
11109: }
11110: }
11111: return;
11112: }
11113:
11114: sub devalidate_slots_cache {
11115: my ($cnum,$cdom)=@_;
11116: my $hashid=$cnum.':'.$cdom;
11117: &devalidate_cache_new('allslots',$hashid);
11118: }
11119:
1.1172.2.8 raeburn 11120: sub get_coursechange {
11121: my ($cdom,$cnum) = @_;
11122: if ($cdom eq '' || $cnum eq '') {
11123: return unless ($env{'request.course.id'});
11124: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11125: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11126: }
11127: my $hashid=$cdom.'_'.$cnum;
11128: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11129: if ((defined($cached)) && ($change ne '')) {
11130: return $change;
11131: } else {
11132: my %crshash;
11133: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11134: if ($crshash{'internal.contentchange'} eq '') {
11135: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11136: if ($change eq '') {
11137: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11138: $change = $crshash{'internal.created'};
11139: }
11140: } else {
11141: $change = $crshash{'internal.contentchange'};
11142: }
11143: my $cachetime = 600;
11144: &do_cache_new('crschange',$hashid,$change,$cachetime);
11145: }
11146: return $change;
11147: }
11148:
11149: sub devalidate_coursechange_cache {
11150: my ($cnum,$cdom)=@_;
11151: my $hashid=$cnum.':'.$cdom;
11152: &devalidate_cache_new('crschange',$hashid);
11153: }
11154:
1.31 www 11155: # ------------------------------------------------- Update symbolic store links
11156:
11157: sub symblist {
11158: my ($mapname,%newhash)=@_;
1.438 www 11159: $mapname=&deversion(&declutter($mapname));
1.31 www 11160: my %hash;
1.620 albertel 11161: if (($env{'request.course.fn'}) && (%newhash)) {
11162: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11163: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11164: foreach my $url (keys(%newhash)) {
1.711 albertel 11165: next if ($url eq 'last_known'
11166: && $env{'form.no_update_last_known'});
11167: $hash{declutter($url)}=&encode_symb($mapname,
11168: $newhash{$url}->[1],
11169: $newhash{$url}->[0]);
1.191 harris41 11170: }
1.31 www 11171: if (untie(%hash)) {
11172: return 'ok';
11173: }
11174: }
11175: }
11176: return 'error';
1.212 www 11177: }
11178:
11179: # --------------------------------------------------------------- Verify a symb
11180:
11181: sub symbverify {
1.1172.2.11 raeburn 11182: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11183: my $thisfn=$thisurl;
1.439 www 11184: $thisfn=&declutter($thisfn);
1.215 www 11185: # direct jump to resource in page or to a sequence - will construct own symbs
11186: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11187: # check URL part
1.409 www 11188: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11189:
1.431 www 11190: unless ($url eq $thisfn) { return 0; }
1.213 www 11191:
1.216 www 11192: $symb=&symbclean($symb);
1.510 www 11193: $thisurl=&deversion($thisurl);
1.439 www 11194: $thisfn=&deversion($thisfn);
1.213 www 11195:
11196: my %bighash;
11197: my $okay=0;
1.431 www 11198:
1.620 albertel 11199: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11200: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11201: my $noclutter;
1.1032 raeburn 11202: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11203: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11204: if ($map =~ m{^uploaded/.+\.page$}) {
11205: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11206: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11207: $noclutter = 1;
11208: }
11209: }
11210: my $ids;
11211: if ($noclutter) {
11212: $ids=$bighash{'ids_'.$thisurl};
11213: } else {
11214: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11215: }
1.1102 raeburn 11216: unless ($ids) {
1.1172.2.13 raeburn 11217: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11218: $ids=$bighash{$idkey};
1.216 www 11219: }
11220: if ($ids) {
11221: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11222: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11223: $symb =~ s/\?.+$//;
11224: }
1.800 albertel 11225: foreach my $id (split(/\,/,$ids)) {
11226: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11227: if (
11228: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11229: eq $symb) {
1.1172.2.11 raeburn 11230: if (ref($encstate)) {
11231: $$encstate = $bighash{'encrypted_'.$id};
11232: }
1.1172.2.13 raeburn 11233: if (($env{'request.role.adv'}) ||
11234: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11235: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11236: $okay=1;
11237: last;
11238: }
11239: }
11240: }
1.216 www 11241: }
1.213 www 11242: untie(%bighash);
11243: }
11244: return $okay;
1.31 www 11245: }
11246:
1.210 www 11247: # --------------------------------------------------------------- Clean-up symb
11248:
11249: sub symbclean {
11250: my $symb=shift;
1.568 albertel 11251: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11252: # remove version from map
11253: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11254:
1.210 www 11255: # remove version from URL
11256: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11257:
1.507 www 11258: # remove wrapper
11259:
1.510 www 11260: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11261: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11262: return $symb;
1.409 www 11263: }
11264:
11265: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11266:
11267: sub encode_symb {
11268: my ($map,$resid,$url)=@_;
11269: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11270: }
1.409 www 11271:
11272: sub decode_symb {
1.568 albertel 11273: my $symb=shift;
11274: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11275: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11276: return (&fixversion($map),$resid,&fixversion($url));
11277: }
11278:
11279: sub fixversion {
11280: my $fn=shift;
1.609 banghart 11281: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11282: my %bighash;
11283: my $uri=&clutter($fn);
1.620 albertel 11284: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11285: # is this cached?
1.599 albertel 11286: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11287: if (defined($cached)) { return $result; }
11288: # unfortunately not cached, or expired
1.620 albertel 11289: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11290: &GDBM_READER(),0640)) {
11291: if ($bighash{'version_'.$uri}) {
11292: my $version=$bighash{'version_'.$uri};
1.444 www 11293: unless (($version eq 'mostrecent') ||
11294: ($version==&getversion($uri))) {
1.440 www 11295: $uri=~s/\.(\w+)$/\.$version\.$1/;
11296: }
11297: }
11298: untie %bighash;
1.413 www 11299: }
1.599 albertel 11300: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11301: }
11302:
11303: sub deversion {
11304: my $url=shift;
11305: $url=~s/\.\d+\.(\w+)$/\.$1/;
11306: return $url;
1.210 www 11307: }
11308:
1.31 www 11309: # ------------------------------------------------------ Return symb list entry
11310:
11311: sub symbread {
1.1172.2.66 raeburn 11312: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11313: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11314: if (defined($env{$cache_str})) {
11315: if ($ignorecachednull) {
11316: return $env{$cache_str} unless ($env{$cache_str} eq '');
11317: } else {
11318: return $env{$cache_str};
11319: }
11320: }
1.242 www 11321: # no filename provided? try from environment
1.1172.2.54 raeburn 11322: unless ($thisfn) {
1.620 albertel 11323: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11324: return $env{$cache_str}=&symbclean($env{'request.symb'});
11325: }
11326: $thisfn=$env{'request.filename'};
1.44 www 11327: }
1.569 albertel 11328: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11329: # is that filename actually a symb? Verify, clean, and return
11330: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11331: if (&symbverify($thisfn,$1)) {
1.620 albertel 11332: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11333: }
1.242 www 11334: }
1.44 www 11335: $thisfn=declutter($thisfn);
1.31 www 11336: my %hash;
1.37 www 11337: my %bighash;
11338: my $syval='';
1.620 albertel 11339: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11340: my $targetfn = $thisfn;
1.609 banghart 11341: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11342: $targetfn = 'adm/wrapper/'.$thisfn;
11343: }
1.687 albertel 11344: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11345: $targetfn=$1;
11346: }
1.620 albertel 11347: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11348: &GDBM_READER(),0640)) {
1.481 raeburn 11349: $syval=$hash{$targetfn};
1.37 www 11350: untie(%hash);
11351: }
11352: # ---------------------------------------------------------- There was an entry
11353: if ($syval) {
1.601 albertel 11354: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11355: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11356: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11357: #return $env{$cache_str}='';
1.601 albertel 11358: #}
11359: #$syval.=$1;
11360: #}
1.37 www 11361: } else {
11362: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11363: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11364: &GDBM_READER(),0640)) {
1.37 www 11365: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11366: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11367: unless ($ids) {
11368: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11369: }
11370: unless ($ids) {
11371: # alias?
11372: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11373: }
1.37 www 11374: if ($ids) {
11375: # ------------------------------------------------------------------- Has ID(s)
11376: my @possibilities=split(/\,/,$ids);
1.39 www 11377: if ($#possibilities==0) {
11378: # ----------------------------------------------- There is only one possibility
1.37 www 11379: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11380: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11381: $resid,$thisfn);
1.1172.2.66 raeburn 11382: if (ref($possibles) eq 'HASH') {
11383: $possibles->{$syval} = 1;
11384: }
11385: if ($checkforblock) {
11386: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11387: if (@blockers) {
11388: $syval = '';
11389: return;
11390: }
11391: }
11392: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11393: # ------------------------------------------ There is more than one possibility
11394: my $realpossible=0;
1.800 albertel 11395: foreach my $id (@possibilities) {
11396: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11397: my $canaccess;
11398: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11399: $canaccess = 1;
11400: } else {
11401: $canaccess = &allowed('bre',$file);
11402: }
11403: if ($canaccess) {
11404: my ($mapid,$resid)=split(/\./,$id);
11405: if ($bighash{'map_type_'.$mapid} ne 'page') {
11406: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11407: $resid,$thisfn);
11408: if (ref($possibles) eq 'HASH') {
11409: $possibles->{$syval} = 1;
11410: }
11411: if ($checkforblock) {
11412: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11413: unless (@blockers > 0) {
11414: $syval = $poss_syval;
11415: $realpossible++;
11416: }
11417: } else {
11418: $syval = $poss_syval;
11419: $realpossible++;
11420: }
11421: }
1.39 www 11422: }
1.191 harris41 11423: }
1.39 www 11424: if ($realpossible!=1) { $syval=''; }
1.249 www 11425: } else {
11426: $syval='';
1.37 www 11427: }
11428: }
1.1172.2.66 raeburn 11429: untie(%bighash);
1.481 raeburn 11430: }
1.31 www 11431: }
1.62 www 11432: if ($syval) {
1.620 albertel 11433: return $env{$cache_str}=$syval;
1.62 www 11434: }
1.31 www 11435: }
1.949 raeburn 11436: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11437: return $env{$cache_str}='';
1.31 www 11438: }
11439:
11440: # ---------------------------------------------------------- Return random seed
11441:
1.32 www 11442: sub numval {
11443: my $txt=shift;
11444: $txt=~tr/A-J/0-9/;
11445: $txt=~tr/a-j/0-9/;
11446: $txt=~tr/K-T/0-9/;
11447: $txt=~tr/k-t/0-9/;
11448: $txt=~tr/U-Z/0-5/;
11449: $txt=~tr/u-z/0-5/;
11450: $txt=~s/\D//g;
1.564 albertel 11451: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11452: return int($txt);
1.368 albertel 11453: }
11454:
1.484 albertel 11455: sub numval2 {
11456: my $txt=shift;
11457: $txt=~tr/A-J/0-9/;
11458: $txt=~tr/a-j/0-9/;
11459: $txt=~tr/K-T/0-9/;
11460: $txt=~tr/k-t/0-9/;
11461: $txt=~tr/U-Z/0-5/;
11462: $txt=~tr/u-z/0-5/;
11463: $txt=~s/\D//g;
11464: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11465: my $total;
11466: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11467: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11468: return int($total);
11469: }
11470:
1.575 albertel 11471: sub numval3 {
11472: use integer;
11473: my $txt=shift;
11474: $txt=~tr/A-J/0-9/;
11475: $txt=~tr/a-j/0-9/;
11476: $txt=~tr/K-T/0-9/;
11477: $txt=~tr/k-t/0-9/;
11478: $txt=~tr/U-Z/0-5/;
11479: $txt=~tr/u-z/0-5/;
11480: $txt=~s/\D//g;
11481: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11482: my $total;
11483: foreach my $val (@txts) { $total+=$val; }
11484: if ($_64bit) { $total=(($total<<32)>>32); }
11485: return $total;
11486: }
11487:
1.675 albertel 11488: sub digest {
11489: my ($data)=@_;
11490: my $digest=&Digest::MD5::md5($data);
11491: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11492: my ($e,$f);
11493: {
11494: use integer;
11495: $e=($a+$b);
11496: $f=($c+$d);
11497: if ($_64bit) {
11498: $e=(($e<<32)>>32);
11499: $f=(($f<<32)>>32);
11500: }
11501: }
11502: if (wantarray) {
11503: return ($e,$f);
11504: } else {
11505: my $g;
11506: {
11507: use integer;
11508: $g=($e+$f);
11509: if ($_64bit) {
11510: $g=(($g<<32)>>32);
11511: }
11512: }
11513: return $g;
11514: }
11515: }
11516:
1.368 albertel 11517: sub latest_rnd_algorithm_id {
1.675 albertel 11518: return '64bit5';
1.366 albertel 11519: }
1.32 www 11520:
1.503 albertel 11521: sub get_rand_alg {
11522: my ($courseid)=@_;
1.790 albertel 11523: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11524: if ($courseid) {
1.620 albertel 11525: return $env{"course.$courseid.rndseed"};
1.503 albertel 11526: }
11527: return &latest_rnd_algorithm_id();
11528: }
11529:
1.562 albertel 11530: sub validCODE {
11531: my ($CODE)=@_;
11532: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11533: return 0;
11534: }
11535:
1.491 albertel 11536: sub getCODE {
1.620 albertel 11537: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11538: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11539: defined($Apache::lonhomework::parsing_a_task) ) &&
11540: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11541: return $Apache::lonhomework::history{'resource.CODE'};
11542: }
11543: return undef;
11544: }
1.1133 foxr 11545: #
11546: # Determines the random seed for a specific context:
11547: #
11548: # parameters:
11549: # symb - in course context the symb for the seed.
11550: # course_id - The course id of the form domain_coursenum.
11551: # domain - Domain for the user.
11552: # course - Course for the user.
11553: # cenv - environment of the course.
11554: #
11555: # NOTE:
11556: # All parameters are picked out of the environment if missing
11557: # or not defined.
11558: # If a symb cannot be determined the current time is used instead.
11559: #
11560: # For a given well defined symb, courside, domain, username,
11561: # and course environment, the seed is reproducible.
11562: #
1.31 www 11563: sub rndseed {
1.1133 foxr 11564: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11565: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11566: if (!defined($symb)) {
1.366 albertel 11567: unless ($symb=$wsymb) { return time; }
11568: }
1.1146 foxr 11569: if (!defined $courseid) {
11570: $courseid=$wcourseid;
11571: }
11572: if (!defined $domain) { $domain=$wdomain; }
11573: if (!defined $username) { $username=$wusername }
1.1133 foxr 11574:
11575: my $which;
11576: if (defined($cenv->{'rndseed'})) {
11577: $which = $cenv->{'rndseed'};
11578: } else {
11579: $which =&get_rand_alg($courseid);
11580: }
1.491 albertel 11581: if (defined(&getCODE())) {
1.675 albertel 11582: if ($which eq '64bit5') {
11583: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11584: } elsif ($which eq '64bit4') {
1.575 albertel 11585: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11586: } else {
11587: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11588: }
1.675 albertel 11589: } elsif ($which eq '64bit5') {
11590: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11591: } elsif ($which eq '64bit4') {
11592: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11593: } elsif ($which eq '64bit3') {
11594: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11595: } elsif ($which eq '64bit2') {
11596: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11597: } elsif ($which eq '64bit') {
11598: return &rndseed_64bit($symb,$courseid,$domain,$username);
11599: }
11600: return &rndseed_32bit($symb,$courseid,$domain,$username);
11601: }
11602:
11603: sub rndseed_32bit {
11604: my ($symb,$courseid,$domain,$username)=@_;
11605: {
11606: use integer;
11607: my $symbchck=unpack("%32C*",$symb) << 27;
11608: my $symbseed=numval($symb) << 22;
11609: my $namechck=unpack("%32C*",$username) << 17;
11610: my $nameseed=numval($username) << 12;
11611: my $domainseed=unpack("%32C*",$domain) << 7;
11612: my $courseseed=unpack("%32C*",$courseid);
11613: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11614: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11615: #&logthis("rndseed :$num:$symb");
1.564 albertel 11616: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11617: return $num;
11618: }
11619: }
11620:
11621: sub rndseed_64bit {
11622: my ($symb,$courseid,$domain,$username)=@_;
11623: {
11624: use integer;
11625: my $symbchck=unpack("%32S*",$symb) << 21;
11626: my $symbseed=numval($symb) << 10;
11627: my $namechck=unpack("%32S*",$username);
11628:
11629: my $nameseed=numval($username) << 21;
11630: my $domainseed=unpack("%32S*",$domain) << 10;
11631: my $courseseed=unpack("%32S*",$courseid);
11632:
11633: my $num1=$symbchck+$symbseed+$namechck;
11634: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11635: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11636: #&logthis("rndseed :$num:$symb");
1.564 albertel 11637: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11638: return "$num1,$num2";
1.155 albertel 11639: }
1.366 albertel 11640: }
11641:
1.443 albertel 11642: sub rndseed_64bit2 {
11643: my ($symb,$courseid,$domain,$username)=@_;
11644: {
11645: use integer;
11646: # strings need to be an even # of cahracters long, it it is odd the
11647: # last characters gets thrown away
11648: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11649: my $symbseed=numval($symb) << 10;
11650: my $namechck=unpack("%32S*",$username.' ');
11651:
11652: my $nameseed=numval($username) << 21;
1.501 albertel 11653: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11654: my $courseseed=unpack("%32S*",$courseid.' ');
11655:
11656: my $num1=$symbchck+$symbseed+$namechck;
11657: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11658: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11659: #&logthis("rndseed :$num:$symb");
1.803 albertel 11660: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11661: return "$num1,$num2";
11662: }
11663: }
11664:
11665: sub rndseed_64bit3 {
11666: my ($symb,$courseid,$domain,$username)=@_;
11667: {
11668: use integer;
11669: # strings need to be an even # of cahracters long, it it is odd the
11670: # last characters gets thrown away
11671: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11672: my $symbseed=numval2($symb) << 10;
11673: my $namechck=unpack("%32S*",$username.' ');
11674:
11675: my $nameseed=numval2($username) << 21;
1.443 albertel 11676: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11677: my $courseseed=unpack("%32S*",$courseid.' ');
11678:
11679: my $num1=$symbchck+$symbseed+$namechck;
11680: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11681: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11682: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11683: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11684:
1.503 albertel 11685: return "$num1:$num2";
1.443 albertel 11686: }
11687: }
11688:
1.575 albertel 11689: sub rndseed_64bit4 {
11690: my ($symb,$courseid,$domain,$username)=@_;
11691: {
11692: use integer;
11693: # strings need to be an even # of cahracters long, it it is odd the
11694: # last characters gets thrown away
11695: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11696: my $symbseed=numval3($symb) << 10;
11697: my $namechck=unpack("%32S*",$username.' ');
11698:
11699: my $nameseed=numval3($username) << 21;
11700: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11701: my $courseseed=unpack("%32S*",$courseid.' ');
11702:
11703: my $num1=$symbchck+$symbseed+$namechck;
11704: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11705: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11706: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11707: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11708:
1.575 albertel 11709: return "$num1:$num2";
11710: }
11711: }
11712:
1.675 albertel 11713: sub rndseed_64bit5 {
11714: my ($symb,$courseid,$domain,$username)=@_;
11715: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11716: return "$num1:$num2";
11717: }
11718:
1.366 albertel 11719: sub rndseed_CODE_64bit {
11720: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11721: {
1.366 albertel 11722: use integer;
1.443 albertel 11723: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11724: my $symbseed=numval2($symb);
1.491 albertel 11725: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11726: my $CODEseed=numval(&getCODE());
1.443 albertel 11727: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11728: my $num1=$symbseed+$CODEchck;
11729: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11730: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11731: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11732: if ($_64bit) { $num1=(($num1<<32)>>32); }
11733: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11734: return "$num1:$num2";
1.366 albertel 11735: }
11736: }
11737:
1.575 albertel 11738: sub rndseed_CODE_64bit4 {
11739: my ($symb,$courseid,$domain,$username)=@_;
11740: {
11741: use integer;
11742: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11743: my $symbseed=numval3($symb);
11744: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11745: my $CODEseed=numval3(&getCODE());
11746: my $courseseed=unpack("%32S*",$courseid.' ');
11747: my $num1=$symbseed+$CODEchck;
11748: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11749: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11750: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11751: if ($_64bit) { $num1=(($num1<<32)>>32); }
11752: if ($_64bit) { $num2=(($num2<<32)>>32); }
11753: return "$num1:$num2";
11754: }
11755: }
11756:
1.675 albertel 11757: sub rndseed_CODE_64bit5 {
11758: my ($symb,$courseid,$domain,$username)=@_;
11759: my $code = &getCODE();
11760: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11761: return "$num1:$num2";
11762: }
11763:
1.366 albertel 11764: sub setup_random_from_rndseed {
11765: my ($rndseed)=@_;
1.503 albertel 11766: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11767: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11768: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11769: &Math::Random::random_set_seed_from_phrase($rndseed);
11770: } else {
11771: &Math::Random::random_set_seed($num1,$num2);
11772: }
1.366 albertel 11773: } else {
11774: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11775: }
1.36 albertel 11776: }
11777:
1.474 albertel 11778: sub latest_receipt_algorithm_id {
1.835 albertel 11779: return 'receipt3';
1.474 albertel 11780: }
11781:
1.480 www 11782: sub recunique {
11783: my $fucourseid=shift;
11784: my $unique;
1.835 albertel 11785: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11786: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11787: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11788: } else {
11789: $unique=$perlvar{'lonReceipt'};
11790: }
11791: return unpack("%32C*",$unique);
11792: }
11793:
11794: sub recprefix {
11795: my $fucourseid=shift;
11796: my $prefix;
1.835 albertel 11797: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11798: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11799: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11800: } else {
11801: $prefix=$perlvar{'lonHostID'};
11802: }
11803: return unpack("%32C*",$prefix);
11804: }
11805:
1.76 www 11806: sub ireceipt {
1.474 albertel 11807: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11808:
11809: my $return =&recprefix($fucourseid).'-';
11810:
11811: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11812: $env{'request.state'} eq 'construct') {
11813: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11814: return $return;
11815: }
11816:
1.76 www 11817: my $cuname=unpack("%32C*",$funame);
11818: my $cudom=unpack("%32C*",$fudom);
11819: my $cucourseid=unpack("%32C*",$fucourseid);
11820: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11821: my $cunique=&recunique($fucourseid);
1.474 albertel 11822: my $cpart=unpack("%32S*",$part);
1.835 albertel 11823: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11824:
1.790 albertel 11825: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11826:
11827: $return.= ($cunique%$cuname+
11828: $cunique%$cudom+
11829: $cusymb%$cuname+
11830: $cusymb%$cudom+
11831: $cucourseid%$cuname+
11832: $cucourseid%$cudom+
11833: $cpart%$cuname+
11834: $cpart%$cudom);
11835: } else {
11836: $return.= ($cunique%$cuname+
11837: $cunique%$cudom+
11838: $cusymb%$cuname+
11839: $cusymb%$cudom+
11840: $cucourseid%$cuname+
11841: $cucourseid%$cudom);
11842: }
11843: return $return;
1.76 www 11844: }
11845:
11846: sub receipt {
1.474 albertel 11847: my ($part)=@_;
1.790 albertel 11848: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11849: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11850: }
1.260 ng 11851:
1.790 albertel 11852: sub whichuser {
11853: my ($passedsymb)=@_;
11854: my ($symb,$courseid,$domain,$name,$publicuser);
11855: if (defined($env{'form.grade_symb'})) {
11856: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11857: my $allowed=&allowed('vgr',$tmp_courseid);
11858: if (!$allowed &&
11859: exists($env{'request.course.sec'}) &&
11860: $env{'request.course.sec'} !~ /^\s*$/) {
11861: $allowed=&allowed('vgr',$tmp_courseid.
11862: '/'.$env{'request.course.sec'});
11863: }
11864: if ($allowed) {
11865: ($symb)=&get_env_multiple('form.grade_symb');
11866: $courseid=$tmp_courseid;
11867: ($domain)=&get_env_multiple('form.grade_domain');
11868: ($name)=&get_env_multiple('form.grade_username');
11869: return ($symb,$courseid,$domain,$name,$publicuser);
11870: }
11871: }
11872: if (!$passedsymb) {
11873: $symb=&symbread();
11874: } else {
11875: $symb=$passedsymb;
11876: }
11877: $courseid=$env{'request.course.id'};
11878: $domain=$env{'user.domain'};
11879: $name=$env{'user.name'};
11880: if ($name eq 'public' && $domain eq 'public') {
11881: if (!defined($env{'form.username'})) {
11882: $env{'form.username'}.=time.rand(10000000);
11883: }
11884: $name.=$env{'form.username'};
11885: }
11886: return ($symb,$courseid,$domain,$name,$publicuser);
11887:
11888: }
11889:
1.36 albertel 11890: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11891: # returns either the contents of the file or
11892: # -1 if the file doesn't exist
1.481 raeburn 11893: #
11894: # if the target is a file that was uploaded via DOCS,
11895: # a check will be made to see if a current copy exists on the local server,
11896: # if it does this will be served, otherwise a copy will be retrieved from
11897: # the home server for the course and stored in /home/httpd/html/userfiles on
11898: # the local server.
1.472 albertel 11899:
1.36 albertel 11900: sub getfile {
1.538 albertel 11901: my ($file) = @_;
1.609 banghart 11902: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11903: &repcopy($file);
11904: return &readfile($file);
11905: }
11906:
11907: sub repcopy_userfile {
11908: my ($file)=@_;
1.1142 raeburn 11909: my $londocroot = $perlvar{'lonDocRoot'};
11910: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11911: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11912: my ($cdom,$cnum,$filename) =
1.811 albertel 11913: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11914: my $uri="/uploaded/$cdom/$cnum/$filename";
11915: if (-e "$file") {
1.828 www 11916: # we already have a local copy, check it out
1.538 albertel 11917: my @fileinfo = stat($file);
1.828 www 11918: my $rtncode;
11919: my $info;
1.538 albertel 11920: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11921: if ($lwpresp ne 'ok') {
1.828 www 11922: # there is no such file anymore, even though we had a local copy
1.482 albertel 11923: if ($rtncode eq '404') {
1.538 albertel 11924: unlink($file);
1.482 albertel 11925: }
11926: return -1;
11927: }
11928: if ($info < $fileinfo[9]) {
1.828 www 11929: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11930: return 'ok';
1.828 www 11931: } else {
11932: # the file is outdated, get rid of it
11933: unlink($file);
1.482 albertel 11934: }
1.828 www 11935: }
11936: # one way or the other, at this point, we don't have the file
11937: # construct the correct path for the file
11938: my @parts = ($cdom,$cnum);
11939: if ($filename =~ m|^(.+)/[^/]+$|) {
11940: push @parts, split(/\//,$1);
11941: }
11942: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11943: foreach my $part (@parts) {
11944: $path .= '/'.$part;
11945: if (!-e $path) {
11946: mkdir($path,0770);
1.482 albertel 11947: }
11948: }
1.828 www 11949: # now the path exists for sure
11950: # get a user agent
11951: my $ua=new LWP::UserAgent;
11952: my $transferfile=$file.'.in.transfer';
11953: # FIXME: this should flock
11954: if (-e $transferfile) { return 'ok'; }
11955: my $request;
11956: $uri=~s/^\///;
1.980 raeburn 11957: my $homeserver = &homeserver($cnum,$cdom);
11958: my $protocol = $protocol{$homeserver};
11959: $protocol = 'http' if ($protocol ne 'https');
11960: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11961: my $response=$ua->request($request,$transferfile);
11962: # did it work?
11963: if ($response->is_error()) {
11964: unlink($transferfile);
11965: &logthis("Userfile repcopy failed for $uri");
11966: return -1;
11967: }
11968: # worked, rename the transfer file
11969: rename($transferfile,$file);
1.607 raeburn 11970: return 'ok';
1.481 raeburn 11971: }
11972:
1.517 albertel 11973: sub tokenwrapper {
11974: my $uri=shift;
1.980 raeburn 11975: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11976: $uri=~s|^/||;
1.620 albertel 11977: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11978: my $token=$1;
1.552 albertel 11979: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11980: if ($udom && $uname && $file) {
11981: $file=~s|(\?\.*)*$||;
1.949 raeburn 11982: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11983: my $homeserver = &homeserver($uname,$udom);
11984: my $protocol = $protocol{$homeserver};
11985: $protocol = 'http' if ($protocol ne 'https');
11986: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11987: (($uri=~/\?/)?'&':'?').'token='.$token.
11988: '&tokenissued='.$perlvar{'lonHostID'};
11989: } else {
11990: return '/adm/notfound.html';
11991: }
11992: }
11993:
1.828 www 11994: # call with reqtype HEAD: get last modification time
11995: # call with reqtype GET: get the file contents
11996: # Do not call this with reqtype GET for large files! It loads everything into memory
11997: #
1.481 raeburn 11998: sub getuploaded {
11999: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12000: $uri=~s/^\///;
1.980 raeburn 12001: my $homeserver = &homeserver($cnum,$cdom);
12002: my $protocol = $protocol{$homeserver};
12003: $protocol = 'http' if ($protocol ne 'https');
12004: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12005: my $ua=new LWP::UserAgent;
12006: my $request=new HTTP::Request($reqtype,$uri);
12007: my $response=$ua->request($request);
12008: $$rtncode = $response->code;
1.482 albertel 12009: if (! $response->is_success()) {
12010: return 'failed';
12011: }
12012: if ($reqtype eq 'HEAD') {
1.486 www 12013: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12014: } elsif ($reqtype eq 'GET') {
12015: $$info = $response->content;
1.472 albertel 12016: }
1.482 albertel 12017: return 'ok';
1.36 albertel 12018: }
12019:
1.481 raeburn 12020: sub readfile {
12021: my $file = shift;
12022: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12023: my $fh;
12024: open($fh,"<$file");
12025: my $a='';
1.800 albertel 12026: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12027: return $a;
12028: }
12029:
1.36 albertel 12030: sub filelocation {
1.590 banghart 12031: my ($dir,$file) = @_;
12032: my $location;
12033: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12034:
12035: if ($file =~ m-^/adm/-) {
12036: $file=~s-^/adm/wrapper/-/-;
12037: $file=~s-^/adm/coursedocs/showdoc/-/-;
12038: }
1.882 albertel 12039:
1.1139 www 12040: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12041: $location = $file;
1.609 banghart 12042: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12043: my ($udom,$uname,$filename)=
1.811 albertel 12044: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12045: my $home=&homeserver($uname,$udom);
12046: my $is_me=0;
12047: my @ids=¤t_machine_ids();
12048: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12049: if ($is_me) {
1.1117 foxr 12050: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12051: } else {
12052: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12053: $udom.'/'.$uname.'/'.$filename;
12054: }
1.882 albertel 12055: } elsif ($file =~ m-^/adm/-) {
12056: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12057: } else {
12058: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12059: $file=~s:^/(res|priv)/:/:;
12060: my $space=$1;
1.590 banghart 12061: if ( !( $file =~ m:^/:) ) {
12062: $location = $dir. '/'.$file;
12063: } else {
1.1142 raeburn 12064: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12065: }
1.59 albertel 12066: }
1.590 banghart 12067: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12068: while ($location=~m{/\.\./}) {
12069: if ($location =~ m{/[^/]+/\.\./}) {
12070: $location=~ s{/[^/]+/\.\./}{/}g;
12071: } else {
12072: $location=~ s{/\.\./}{/}g;
12073: }
12074: } #remove dir/..
1.590 banghart 12075: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12076: return $location;
1.46 www 12077: }
1.36 albertel 12078:
1.46 www 12079: sub hreflocation {
12080: my ($dir,$file)=@_;
1.980 raeburn 12081: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12082: $file=filelocation($dir,$file);
1.700 albertel 12083: } elsif ($file=~m-^/adm/-) {
12084: $file=~s-^/adm/wrapper/-/-;
12085: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12086: }
12087: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12088: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12089: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12090: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12091: {/uploaded/$1/$2/}x;
1.46 www 12092: }
1.913 albertel 12093: if ($file=~ m{^/userfiles/}) {
12094: $file =~ s{^/userfiles/}{/uploaded/};
12095: }
1.462 albertel 12096: return $file;
1.465 albertel 12097: }
12098:
1.1139 www 12099:
12100:
12101:
12102:
1.465 albertel 12103: sub current_machine_domains {
1.853 albertel 12104: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12105: }
12106:
12107: sub machine_domains {
12108: my ($hostname) = @_;
1.465 albertel 12109: my @domains;
1.838 albertel 12110: my %hostname = &all_hostnames();
1.465 albertel 12111: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12112: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12113: if ($hostname eq $name) {
1.844 albertel 12114: push(@domains,&host_domain($id));
1.465 albertel 12115: }
12116: }
12117: return @domains;
12118: }
12119:
12120: sub current_machine_ids {
1.853 albertel 12121: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12122: }
12123:
12124: sub machine_ids {
12125: my ($hostname) = @_;
12126: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12127: my @ids;
1.888 albertel 12128: my %name_to_host = &all_names();
1.889 albertel 12129: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12130: return @{ $name_to_host{$hostname} };
12131: }
12132: return;
1.31 www 12133: }
12134:
1.824 raeburn 12135: sub additional_machine_domains {
12136: my @domains;
12137: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12138: while( my $line = <$fh>) {
12139: $line =~ s/\s//g;
12140: push(@domains,$line);
12141: }
12142: return @domains;
12143: }
12144:
12145: sub default_login_domain {
12146: my $domain = $perlvar{'lonDefDomain'};
12147: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12148: foreach my $posdom (¤t_machine_domains(),
12149: &additional_machine_domains()) {
12150: if (lc($posdom) eq lc($testdomain)) {
12151: $domain=$posdom;
12152: last;
12153: }
12154: }
12155: return $domain;
12156: }
12157:
1.31 www 12158: # ------------------------------------------------------------- Declutters URLs
12159:
12160: sub declutter {
12161: my $thisfn=shift;
1.569 albertel 12162: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12163: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12164: $thisfn=~s{^/home/httpd/html}{};
12165: }
1.31 www 12166: $thisfn=~s/^\///;
1.697 albertel 12167: $thisfn=~s|^adm/wrapper/||;
12168: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12169: $thisfn=~s/^res\///;
1.1172 bisitz 12170: $thisfn=~s/^priv\///;
1.1032 raeburn 12171: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12172: $thisfn=~s/\?.+$//;
12173: }
1.268 www 12174: return $thisfn;
12175: }
12176:
12177: # ------------------------------------------------------------- Clutter up URLs
12178:
12179: sub clutter {
12180: my $thisfn='/'.&declutter(shift);
1.887 albertel 12181: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12182: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12183: $thisfn='/res'.$thisfn;
12184: }
1.1031 raeburn 12185: if ($thisfn !~m|^/adm|) {
12186: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12187: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12188: } else {
12189: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12190: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12191: if ($embstyle eq 'ssi'
12192: || ($embstyle eq 'hdn')
12193: || ($embstyle eq 'rat')
12194: || ($embstyle eq 'prv')
12195: || ($embstyle eq 'ign')) {
12196: #do nothing with these
12197: } elsif (($embstyle eq 'img')
1.695 albertel 12198: || ($embstyle eq 'emb')
12199: || ($embstyle eq 'wrp')) {
12200: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12201: } elsif ($embstyle eq 'unk'
12202: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12203: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12204: } else {
1.718 www 12205: # &logthis("Got a blank emb style");
1.695 albertel 12206: }
1.694 albertel 12207: }
12208: }
1.31 www 12209: return $thisfn;
1.12 www 12210: }
12211:
1.787 albertel 12212: sub clutter_with_no_wrapper {
12213: my $uri = &clutter(shift);
12214: if ($uri =~ m-^/adm/-) {
12215: $uri =~ s-^/adm/wrapper/-/-;
12216: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12217: }
12218: return $uri;
12219: }
12220:
1.557 albertel 12221: sub freeze_escape {
12222: my ($value)=@_;
12223: if (ref($value)) {
12224: $value=&nfreeze($value);
12225: return '__FROZEN__'.&escape($value);
12226: }
12227: return &escape($value);
12228: }
12229:
1.11 www 12230:
1.557 albertel 12231: sub thaw_unescape {
12232: my ($value)=@_;
12233: if ($value =~ /^__FROZEN__/) {
12234: substr($value,0,10,undef);
12235: $value=&unescape($value);
12236: return &thaw($value);
12237: }
12238: return &unescape($value);
12239: }
12240:
1.436 albertel 12241: sub correct_line_ends {
12242: my ($result)=@_;
12243: $$result =~s/\r\n/\n/mg;
12244: $$result =~s/\r/\n/mg;
1.415 albertel 12245: }
1.1 albertel 12246: # ================================================================ Main Program
12247:
1.184 www 12248: sub goodbye {
1.204 albertel 12249: &logthis("Starting Shut down");
1.443 albertel 12250: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12251: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12252: #converted
1.599 albertel 12253: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12254: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12255: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12256: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12257: #1.1 only
1.870 albertel 12258: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12259: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12260: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12261: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12262: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12263: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12264: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12265: &flushcourselogs();
12266: &logthis("Shutting down");
12267: }
12268:
1.852 albertel 12269: sub get_dns {
1.1172.2.17 raeburn 12270: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12271: if (!$ignore_cache) {
12272: my ($content,$cached)=
12273: &Apache::lonnet::is_cached_new('dns',$url);
12274: if ($cached) {
1.1172.2.17 raeburn 12275: &$func($content,$hashref);
1.869 albertel 12276: return;
12277: }
12278: }
12279:
12280: my %alldns;
1.852 albertel 12281: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12282: foreach my $dns (<$config>) {
12283: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12284: my $line = $1;
12285: my ($host,$protocol) = split(/:/,$line);
12286: if ($protocol ne 'https') {
12287: $protocol = 'http';
12288: }
12289: $alldns{$host} = $protocol;
1.869 albertel 12290: }
12291: while (%alldns) {
1.1172.2.52 raeburn 12292: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12293: my $ua=new LWP::UserAgent;
1.1134 raeburn 12294: $ua->timeout(30);
1.979 raeburn 12295: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12296: my $response=$ua->request($request);
1.979 raeburn 12297: delete($alldns{$dns});
1.852 albertel 12298: next if ($response->is_error());
12299: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12300: unless ($nocache) {
1.1172.2.23 raeburn 12301: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12302: }
12303: &$func(\@content,$hashref);
1.869 albertel 12304: return;
1.852 albertel 12305: }
12306: close($config);
1.871 albertel 12307: my $which = (split('/',$url))[3];
12308: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12309: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12310: my @content = <$config>;
1.1172.2.17 raeburn 12311: &$func(\@content,$hashref);
12312: return;
12313: }
12314:
12315: # ------------------------------------------------------Get DNS checksums file
12316: sub parse_dns_checksums_tab {
12317: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12318: my $lonhost = $perlvar{'lonHostID'};
12319: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12320: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12321: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12322: my $webconfdir = '/etc/httpd/conf';
12323: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12324: $webconfdir = '/etc/apache2';
12325: } elsif ($distro =~ /^sles(\d+)$/) {
12326: if ($1 >= 10) {
12327: $webconfdir = '/etc/apache2';
12328: }
12329: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12330: if ($1 >= 10.0) {
12331: $webconfdir = '/etc/apache2';
12332: }
12333: }
1.1172.2.17 raeburn 12334: my ($release,$timestamp) = split(/\-/,$loncaparev);
12335: my (%chksum,%revnum);
12336: if (ref($lines) eq 'ARRAY') {
12337: chomp(@{$lines});
1.1172.2.34 raeburn 12338: my $version = shift(@{$lines});
12339: if ($version eq $release) {
1.1172.2.17 raeburn 12340: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12341: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12342: if ($file =~ m{^/etc/httpd/conf}) {
12343: if ($webconfdir eq '/etc/apache2') {
12344: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12345: }
12346: }
1.1172.2.34 raeburn 12347: $chksum{$file} = $shasum;
12348: $revnum{$file} = $version;
1.1172.2.17 raeburn 12349: }
12350: if (ref($hashref) eq 'HASH') {
12351: %{$hashref} = (
12352: sums => \%chksum,
12353: versions => \%revnum,
12354: );
12355: }
12356: }
12357: }
1.869 albertel 12358: return;
1.852 albertel 12359: }
1.1172.2.17 raeburn 12360:
12361: sub fetch_dns_checksums {
12362: my %checksums;
1.1172.2.34 raeburn 12363: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12364: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12365: my ($release,$timestamp) = split(/\-/,$loncaparev);
12366: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12367: \%checksums);
12368: return \%checksums;
12369: }
12370:
1.327 albertel 12371: # ------------------------------------------------------------ Read domain file
12372: {
1.852 albertel 12373: my $loaded;
1.846 albertel 12374: my %domain;
12375:
1.852 albertel 12376: sub parse_domain_tab {
12377: my ($lines) = @_;
12378: foreach my $line (@$lines) {
12379: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12380:
1.846 albertel 12381: chomp($line);
1.852 albertel 12382: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12383: my %this_domain;
12384: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12385: 'lang_def', 'city', 'longi', 'lati',
12386: 'primary') {
12387: $this_domain{$field} = shift(@elements);
12388: }
12389: $domain{$name} = \%this_domain;
1.852 albertel 12390: }
12391: }
1.864 albertel 12392:
12393: sub reset_domain_info {
12394: undef($loaded);
12395: undef(%domain);
12396: }
12397:
1.852 albertel 12398: sub load_domain_tab {
1.1172.2.70 raeburn 12399: my ($ignore_cache,$nocache) = @_;
12400: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12401: my $fh;
12402: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12403: my @lines = <$fh>;
12404: &parse_domain_tab(\@lines);
1.448 albertel 12405: }
1.852 albertel 12406: close($fh);
12407: $loaded = 1;
1.327 albertel 12408: }
1.846 albertel 12409:
12410: sub domain {
1.852 albertel 12411: &load_domain_tab() if (!$loaded);
12412:
1.846 albertel 12413: my ($name,$what) = @_;
12414: return if ( !exists($domain{$name}) );
12415:
12416: if (!$what) {
12417: return $domain{$name}{'description'};
12418: }
12419: return $domain{$name}{$what};
12420: }
1.974 raeburn 12421:
12422: sub domain_info {
12423: &load_domain_tab() if (!$loaded);
12424: return %domain;
12425: }
12426:
1.327 albertel 12427: }
12428:
12429:
1.1 albertel 12430: # ------------------------------------------------------------- Read hosts file
12431: {
1.838 albertel 12432: my %hostname;
1.844 albertel 12433: my %hostdom;
1.845 albertel 12434: my %libserv;
1.852 albertel 12435: my $loaded;
1.888 albertel 12436: my %name_to_host;
1.1074 raeburn 12437: my %internetdom;
1.1107 raeburn 12438: my %LC_dns_serv;
1.852 albertel 12439:
12440: sub parse_hosts_tab {
12441: my ($file) = @_;
12442: foreach my $configline (@$file) {
12443: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12444: chomp($configline);
12445: if ($configline =~ /^\^/) {
12446: if ($configline =~ /^\^([\w.\-]+)/) {
12447: $LC_dns_serv{$1} = 1;
12448: }
12449: next;
12450: }
1.1074 raeburn 12451: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12452: $name=~s/\s//g;
12453: if ($id && $domain && $role && $name) {
12454: $hostname{$id}=$name;
1.888 albertel 12455: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12456: $hostdom{$id}=$domain;
12457: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12458: if (defined($protocol)) {
12459: if ($protocol eq 'https') {
12460: $protocol{$id} = $protocol;
12461: } else {
12462: $protocol{$id} = 'http';
12463: }
1.968 raeburn 12464: } else {
1.969 raeburn 12465: $protocol{$id} = 'http';
1.968 raeburn 12466: }
1.1074 raeburn 12467: if (defined($intdom)) {
12468: $internetdom{$id} = $intdom;
12469: }
1.852 albertel 12470: }
12471: }
12472: }
1.864 albertel 12473:
12474: sub reset_hosts_info {
1.897 albertel 12475: &purge_remembered();
1.864 albertel 12476: &reset_domain_info();
12477: &reset_hosts_ip_info();
1.892 albertel 12478: undef(%name_to_host);
1.864 albertel 12479: undef(%hostname);
12480: undef(%hostdom);
12481: undef(%libserv);
12482: undef($loaded);
12483: }
1.1 albertel 12484:
1.852 albertel 12485: sub load_hosts_tab {
1.1172.2.70 raeburn 12486: my ($ignore_cache,$nocache) = @_;
12487: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12488: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12489: my @config = <$config>;
12490: &parse_hosts_tab(\@config);
12491: close($config);
12492: $loaded=1;
1.1 albertel 12493: }
1.852 albertel 12494:
1.838 albertel 12495: sub hostname {
1.852 albertel 12496: &load_hosts_tab() if (!$loaded);
12497:
1.838 albertel 12498: my ($lonid) = @_;
12499: return $hostname{$lonid};
12500: }
1.845 albertel 12501:
1.838 albertel 12502: sub all_hostnames {
1.852 albertel 12503: &load_hosts_tab() if (!$loaded);
12504:
1.838 albertel 12505: return %hostname;
12506: }
1.845 albertel 12507:
1.888 albertel 12508: sub all_names {
1.1172.2.70 raeburn 12509: my ($ignore_cache,$nocache) = @_;
12510: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12511:
12512: return %name_to_host;
12513: }
12514:
1.974 raeburn 12515: sub all_host_domain {
12516: &load_hosts_tab() if (!$loaded);
12517: return %hostdom;
12518: }
12519:
1.845 albertel 12520: sub is_library {
1.852 albertel 12521: &load_hosts_tab() if (!$loaded);
12522:
1.845 albertel 12523: return exists($libserv{$_[0]});
12524: }
12525:
12526: sub all_library {
1.852 albertel 12527: &load_hosts_tab() if (!$loaded);
12528:
1.845 albertel 12529: return %libserv;
12530: }
12531:
1.1062 droeschl 12532: sub unique_library {
12533: #2x reverse removes all hostnames that appear more than once
12534: my %unique = reverse &all_library();
12535: return reverse %unique;
12536: }
12537:
1.841 albertel 12538: sub get_servers {
1.852 albertel 12539: &load_hosts_tab() if (!$loaded);
12540:
1.841 albertel 12541: my ($domain,$type) = @_;
12542: my %possible_hosts = ($type eq 'library') ? %libserv
12543: : %hostname;
12544: my %result;
1.842 albertel 12545: if (ref($domain) eq 'ARRAY') {
12546: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12547: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12548: $result{$host} = $hostname;
12549: }
12550: }
12551: } else {
12552: while ( my ($host,$hostname) = each(%possible_hosts)) {
12553: if ($hostdom{$host} eq $domain) {
12554: $result{$host} = $hostname;
12555: }
1.841 albertel 12556: }
12557: }
12558: return %result;
12559: }
1.845 albertel 12560:
1.1062 droeschl 12561: sub get_unique_servers {
12562: my %unique = reverse &get_servers(@_);
12563: return reverse %unique;
12564: }
12565:
1.844 albertel 12566: sub host_domain {
1.852 albertel 12567: &load_hosts_tab() if (!$loaded);
12568:
1.844 albertel 12569: my ($lonid) = @_;
12570: return $hostdom{$lonid};
12571: }
12572:
1.841 albertel 12573: sub all_domains {
1.852 albertel 12574: &load_hosts_tab() if (!$loaded);
12575:
1.841 albertel 12576: my %seen;
12577: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12578: return @uniq;
12579: }
1.1074 raeburn 12580:
12581: sub internet_dom {
12582: &load_hosts_tab() if (!$loaded);
12583:
12584: my ($lonid) = @_;
12585: return $internetdom{$lonid};
12586: }
1.1107 raeburn 12587:
12588: sub is_LC_dns {
12589: &load_hosts_tab() if (!$loaded);
12590:
12591: my ($hostname) = @_;
12592: return exists($LC_dns_serv{$hostname});
12593: }
12594:
1.1 albertel 12595: }
12596:
1.847 albertel 12597: {
12598: my %iphost;
1.856 albertel 12599: my %name_to_ip;
12600: my %lonid_to_ip;
1.869 albertel 12601:
1.847 albertel 12602: sub get_hosts_from_ip {
12603: my ($ip) = @_;
12604: my %iphosts = &get_iphost();
12605: if (ref($iphosts{$ip})) {
12606: return @{$iphosts{$ip}};
12607: }
12608: return;
1.839 albertel 12609: }
1.864 albertel 12610:
12611: sub reset_hosts_ip_info {
12612: undef(%iphost);
12613: undef(%name_to_ip);
12614: undef(%lonid_to_ip);
12615: }
1.856 albertel 12616:
12617: sub get_host_ip {
12618: my ($lonid) = @_;
12619: if (exists($lonid_to_ip{$lonid})) {
12620: return $lonid_to_ip{$lonid};
12621: }
12622: my $name=&hostname($lonid);
12623: my $ip = gethostbyname($name);
12624: return if (!$ip || length($ip) ne 4);
12625: $ip=inet_ntoa($ip);
12626: $name_to_ip{$name} = $ip;
12627: $lonid_to_ip{$lonid} = $ip;
12628: return $ip;
12629: }
1.847 albertel 12630:
12631: sub get_iphost {
1.1172.2.70 raeburn 12632: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12633:
1.869 albertel 12634: if (!$ignore_cache) {
12635: if (%iphost) {
12636: return %iphost;
12637: }
12638: my ($ip_info,$cached)=
12639: &Apache::lonnet::is_cached_new('iphost','iphost');
12640: if ($cached) {
12641: %iphost = %{$ip_info->[0]};
12642: %name_to_ip = %{$ip_info->[1]};
12643: %lonid_to_ip = %{$ip_info->[2]};
12644: return %iphost;
12645: }
12646: }
1.894 albertel 12647:
12648: # get yesterday's info for fallback
12649: my %old_name_to_ip;
12650: my ($ip_info,$cached)=
12651: &Apache::lonnet::is_cached_new('iphost','iphost');
12652: if ($cached) {
12653: %old_name_to_ip = %{$ip_info->[1]};
12654: }
12655:
1.1172.2.70 raeburn 12656: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12657: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12658: my $ip;
12659: if (!exists($name_to_ip{$name})) {
12660: $ip = gethostbyname($name);
12661: if (!$ip || length($ip) ne 4) {
1.894 albertel 12662: if (defined($old_name_to_ip{$name})) {
12663: $ip = $old_name_to_ip{$name};
12664: &logthis("Can't find $name defaulting to old $ip");
12665: } else {
12666: &logthis("Name $name no IP found");
12667: next;
12668: }
12669: } else {
12670: $ip=inet_ntoa($ip);
1.847 albertel 12671: }
12672: $name_to_ip{$name} = $ip;
12673: } else {
12674: $ip = $name_to_ip{$name};
1.653 albertel 12675: }
1.888 albertel 12676: foreach my $id (@{ $name_to_host{$name} }) {
12677: $lonid_to_ip{$id} = $ip;
12678: }
12679: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12680: }
1.1172.2.70 raeburn 12681: unless ($nocache) {
12682: &do_cache_new('iphost','iphost',
12683: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12684: 48*60*60);
12685: }
1.869 albertel 12686:
1.847 albertel 12687: return %iphost;
1.598 albertel 12688: }
12689:
1.992 raeburn 12690: #
12691: # Given a DNS returns the loncapa host name for that DNS
12692: #
12693: sub host_from_dns {
12694: my ($dns) = @_;
12695: my @hosts;
12696: my $ip;
12697:
1.993 raeburn 12698: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12699: $ip = $name_to_ip{$dns};
12700: }
12701: if (!$ip) {
12702: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12703: if (length($ip) == 4) {
12704: $ip = &IO::Socket::inet_ntoa($ip);
12705: }
12706: }
12707: if ($ip) {
12708: @hosts = get_hosts_from_ip($ip);
12709: return $hosts[0];
12710: }
12711: return undef;
1.986 foxr 12712: }
1.992 raeburn 12713:
1.1074 raeburn 12714: sub get_internet_names {
12715: my ($lonid) = @_;
12716: return if ($lonid eq '');
12717: my ($idnref,$cached)=
12718: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12719: if ($cached) {
12720: return $idnref;
12721: }
12722: my $ip = &get_host_ip($lonid);
12723: my @hosts = &get_hosts_from_ip($ip);
12724: my %iphost = &get_iphost();
12725: my (@idns,%seen);
12726: foreach my $id (@hosts) {
12727: my $dom = &host_domain($id);
12728: my $prim_id = &domain($dom,'primary');
12729: my $prim_ip = &get_host_ip($prim_id);
12730: next if ($seen{$prim_ip});
12731: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12732: foreach my $id (@{$iphost{$prim_ip}}) {
12733: my $intdom = &internet_dom($id);
12734: unless (grep(/^\Q$intdom\E$/,@idns)) {
12735: push(@idns,$intdom);
12736: }
12737: }
12738: }
12739: $seen{$prim_ip} = 1;
12740: }
1.1172.2.23 raeburn 12741: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12742: }
12743:
1.986 foxr 12744: }
12745:
1.1079 raeburn 12746: sub all_loncaparevs {
1.1172.2.39 raeburn 12747: 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 12748: }
12749:
1.1172.2.27 raeburn 12750: # ------------------------------------------------------- Read loncaparev table
12751: {
12752: sub load_loncaparevs {
12753: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12754: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12755: while (my $configline=<$config>) {
12756: chomp($configline);
12757: my ($hostid,$loncaparev)=split(/:/,$configline);
12758: $loncaparevs{$hostid}=$loncaparev;
12759: }
12760: close($config);
12761: }
12762: }
12763: }
12764: }
12765:
12766: # ----------------------------------------------------- Read serverhostID table
12767: {
12768: sub load_serverhomeIDs {
12769: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12770: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12771: while (my $configline=<$config>) {
12772: chomp($configline);
12773: my ($name,$id)=split(/:/,$configline);
12774: $serverhomeIDs{$name}=$id;
12775: }
12776: close($config);
12777: }
12778: }
12779: }
12780: }
12781:
12782:
1.862 albertel 12783: BEGIN {
12784:
12785: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12786: unless ($readit) {
12787: {
12788: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12789: %perlvar = (%perlvar,%{$configvars});
12790: }
12791:
12792:
1.1 albertel 12793: # ------------------------------------------------------ Read spare server file
12794: {
1.448 albertel 12795: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12796:
12797: while (my $configline=<$config>) {
12798: chomp($configline);
1.284 matthew 12799: if ($configline) {
1.784 albertel 12800: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12801: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12802: push(@{ $spareid{$type} }, $host);
1.1 albertel 12803: }
12804: }
1.448 albertel 12805: close($config);
1.1 albertel 12806: }
1.11 www 12807: # ------------------------------------------------------------ Read permissions
12808: {
1.448 albertel 12809: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12810:
12811: while (my $configline=<$config>) {
1.448 albertel 12812: chomp($configline);
12813: if ($configline) {
12814: my ($role,$perm)=split(/ /,$configline);
12815: if ($perm ne '') { $pr{$role}=$perm; }
12816: }
1.11 www 12817: }
1.448 albertel 12818: close($config);
1.11 www 12819: }
12820:
12821: # -------------------------------------------- Read plain texts for permissions
12822: {
1.448 albertel 12823: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12824:
12825: while (my $configline=<$config>) {
1.448 albertel 12826: chomp($configline);
12827: if ($configline) {
1.742 raeburn 12828: my ($short,@plain)=split(/:/,$configline);
12829: %{$prp{$short}} = ();
12830: if (@plain > 0) {
12831: $prp{$short}{'std'} = $plain[0];
12832: for (my $i=1; $i<@plain; $i++) {
12833: $prp{$short}{'alt'.$i} = $plain[$i];
12834: }
12835: }
1.448 albertel 12836: }
1.135 www 12837: }
1.448 albertel 12838: close($config);
1.135 www 12839: }
12840:
12841: # ---------------------------------------------------------- Read package table
12842: {
1.448 albertel 12843: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12844:
12845: while (my $configline=<$config>) {
1.483 albertel 12846: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12847: chomp($configline);
12848: my ($short,$plain)=split(/:/,$configline);
12849: my ($pack,$name)=split(/\&/,$short);
12850: if ($plain ne '') {
12851: $packagetab{$pack.'&'.$name.'&name'}=$name;
12852: $packagetab{$short}=$plain;
12853: }
1.11 www 12854: }
1.448 albertel 12855: close($config);
1.329 matthew 12856: }
12857:
1.1172.2.27 raeburn 12858: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12859:
1.1172.2.27 raeburn 12860: &load_loncaparevs();
12861:
12862: # ------------------------------------------------------- Read serverhostID table
12863:
12864: &load_serverhomeIDs();
1.1074 raeburn 12865:
1.1172.2.27 raeburn 12866: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12867: {
12868: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12869: if (-e $file) {
12870: my $parser = HTML::LCParser->new($file);
12871: while (my $token = $parser->get_token()) {
12872: if ($token->[0] eq 'S') {
12873: my $item = $token->[1];
12874: my $name = $token->[2]{'name'};
12875: my $value = $token->[2]{'value'};
12876: if ($item ne '' && $name ne '' && $value ne '') {
12877: my $release = $parser->get_text();
12878: $release =~ s/(^\s*|\s*$ )//gx;
12879: $needsrelease{$item.':'.$name.':'.$value} = $release;
12880: }
12881: }
12882: }
12883: }
1.1073 raeburn 12884: }
12885:
1.1138 raeburn 12886: # ---------------------------------------------------------- Read managers table
12887: {
12888: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12889: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12890: while (my $configline=<$config>) {
12891: chomp($configline);
12892: next if ($configline =~ /^\#/);
12893: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12894: $managerstab{$configline} = 1;
12895: }
12896: }
12897: close($config);
12898: }
12899: }
12900: }
12901:
1.329 matthew 12902: # ------------- set up temporary directory
12903: {
1.1117 foxr 12904: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12905:
1.11 www 12906: }
12907:
1.794 albertel 12908: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12909: 'compress_threshold'=> 20_000,
12910: });
1.185 www 12911:
1.281 www 12912: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12913: $dumpcount=0;
1.958 www 12914: $locknum=0;
1.22 www 12915:
1.163 harris41 12916: &logtouch();
1.672 albertel 12917: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12918: $readit=1;
1.564 albertel 12919: {
12920: use integer;
12921: my $test=(2**32)+1;
1.568 albertel 12922: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12923: &logthis(" Detected 64bit platform ($_64bit)");
12924: }
1.195 www 12925: }
1.1 albertel 12926: }
1.179 www 12927:
1.1 albertel 12928: 1;
1.191 harris41 12929: __END__
12930:
1.243 albertel 12931: =pod
12932:
1.191 harris41 12933: =head1 NAME
12934:
1.243 albertel 12935: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12936:
12937: =head1 SYNOPSIS
12938:
1.243 albertel 12939: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12940:
12941: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12942:
1.243 albertel 12943: Common parameters:
12944:
12945: =over 4
12946:
12947: =item *
12948:
12949: $uname : an internal username (if $cname expecting a course Id specifically)
12950:
12951: =item *
12952:
12953: $udom : a domain (if $cdom expecting a course's domain specifically)
12954:
12955: =item *
12956:
12957: $symb : a resource instance identifier
12958:
12959: =item *
12960:
12961: $namespace : the name of a .db file that contains the data needed or
12962: being set.
12963:
12964: =back
12965:
1.394 bowersj2 12966: =head1 OVERVIEW
1.191 harris41 12967:
1.394 bowersj2 12968: lonnet provides subroutines which interact with the
12969: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12970: about classes, users, and resources.
1.243 albertel 12971:
12972: For many of these objects you can also use this to store data about
12973: them or modify them in various ways.
1.191 harris41 12974:
1.394 bowersj2 12975: =head2 Symbs
1.191 harris41 12976:
1.394 bowersj2 12977: To identify a specific instance of a resource, LON-CAPA uses symbols
12978: or "symbs"X<symb>. These identifiers are built from the URL of the
12979: map, the resource number of the resource in the map, and the URL of
12980: the resource itself. The latter is somewhat redundant, but might help
12981: if maps change.
12982:
12983: An example is
12984:
12985: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12986:
12987: The respective map entry is
12988:
12989: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12990: title="Problem 2">
12991: </resource>
12992:
12993: Symbs are used by the random number generator, as well as to store and
12994: restore data specific to a certain instance of for example a problem.
12995:
12996: =head2 Storing And Retrieving Data
12997:
12998: X<store()>X<cstore()>X<restore()>Three of the most important functions
12999: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13000: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13001: is is the non-critical message twin of cstore. These functions are for
13002: handlers to store a perl hash to a user's permanent data space in an
13003: easy manner, and to retrieve it again on another call. It is expected
13004: that a handler would use this once at the beginning to retrieve data,
13005: and then again once at the end to send only the new data back.
13006:
13007: The data is stored in the user's data directory on the user's
13008: homeserver under the ID of the course.
13009:
13010: The hash that is returned by restore will have all of the previous
13011: value for all of the elements of the hash.
13012:
13013: Example:
13014:
13015: #creating a hash
13016: my %hash;
13017: $hash{'foo'}='bar';
13018:
13019: #storing it
13020: &Apache::lonnet::cstore(\%hash);
13021:
13022: #changing a value
13023: $hash{'foo'}='notbar';
13024:
13025: #adding a new value
13026: $hash{'bar'}='foo';
13027: &Apache::lonnet::cstore(\%hash);
13028:
13029: #retrieving the hash
13030: my %history=&Apache::lonnet::restore();
13031:
13032: #print the hash
13033: foreach my $key (sort(keys(%history))) {
13034: print("\%history{$key} = $history{$key}");
13035: }
13036:
13037: Will print out:
1.191 harris41 13038:
1.394 bowersj2 13039: %history{1:foo} = bar
13040: %history{1:keys} = foo:timestamp
13041: %history{1:timestamp} = 990455579
13042: %history{2:bar} = foo
13043: %history{2:foo} = notbar
13044: %history{2:keys} = foo:bar:timestamp
13045: %history{2:timestamp} = 990455580
13046: %history{bar} = foo
13047: %history{foo} = notbar
13048: %history{timestamp} = 990455580
13049: %history{version} = 2
13050:
13051: Note that the special hash entries C<keys>, C<version> and
13052: C<timestamp> were added to the hash. C<version> will be equal to the
13053: total number of versions of the data that have been stored. The
13054: C<timestamp> attribute will be the UNIX time the hash was
13055: stored. C<keys> is available in every historical section to list which
13056: keys were added or changed at a specific historical revision of a
13057: hash.
13058:
13059: B<Warning>: do not store the hash that restore returns directly. This
13060: will cause a mess since it will restore the historical keys as if the
13061: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13062:
1.394 bowersj2 13063: Calling convention:
1.191 harris41 13064:
1.1172.2.27 raeburn 13065: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13066: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13067:
1.394 bowersj2 13068: For more detailed information, see lonnet specific documentation.
1.191 harris41 13069:
1.394 bowersj2 13070: =head1 RETURN MESSAGES
1.191 harris41 13071:
1.394 bowersj2 13072: =over 4
1.191 harris41 13073:
1.394 bowersj2 13074: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13075:
1.394 bowersj2 13076: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13077: when the connection is brought back up
1.191 harris41 13078:
1.394 bowersj2 13079: =item * B<con_failed>: unable to contact remote host and unable to save message
13080: for later delivery
1.191 harris41 13081:
1.967 bisitz 13082: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13083:
1.394 bowersj2 13084: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13085: that was requested
1.191 harris41 13086:
1.243 albertel 13087: =back
1.191 harris41 13088:
1.243 albertel 13089: =head1 PUBLIC SUBROUTINES
1.191 harris41 13090:
1.243 albertel 13091: =head2 Session Environment Functions
1.191 harris41 13092:
1.243 albertel 13093: =over 4
1.191 harris41 13094:
1.394 bowersj2 13095: =item *
13096: X<appenv()>
1.949 raeburn 13097: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13098: the user envirnoment file, and will be restored for each access this
1.620 albertel 13099: user makes during this session, also modifies the %env for the current
1.949 raeburn 13100: process. Optional rolesarrayref - if defined contains a reference to an array
13101: of roles which are exempt from the restriction on modifying user.role entries
13102: in the user's environment.db and in %env.
1.191 harris41 13103:
13104: =item *
1.394 bowersj2 13105: X<delenv()>
1.987 raeburn 13106: B<delenv($delthis,$regexp)>: removes all items from the session
13107: environment file that begin with $delthis. If the
13108: optional second arg - $regexp - is true, $delthis is treated as a
13109: regular expression, otherwise \Q$delthis\E is used.
13110: The values are also deleted from the current processes %env.
1.191 harris41 13111:
1.795 albertel 13112: =item * get_env_multiple($name)
13113:
13114: gets $name from the %env hash, it seemlessly handles the cases where multiple
13115: values may be defined and end up as an array ref.
13116:
13117: returns an array of values
13118:
1.243 albertel 13119: =back
13120:
13121: =head2 User Information
1.191 harris41 13122:
1.243 albertel 13123: =over 4
1.191 harris41 13124:
13125: =item *
1.394 bowersj2 13126: X<queryauthenticate()>
13127: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13128: authentication scheme
13129:
13130: =item *
1.394 bowersj2 13131: X<authenticate()>
1.1073 raeburn 13132: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13133: authenticate user from domain's lib servers (first use the current
13134: one). C<$upass> should be the users password.
1.1073 raeburn 13135: $checkdefauth is optional (value is 1 if a check should be made to
13136: authenticate user using default authentication method, and allow
13137: account creation if username does not have account in the domain).
13138: $clientcancheckhost is optional (value is 1 if checking whether the
13139: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13140:
13141: =item *
1.394 bowersj2 13142: X<homeserver()>
13143: B<homeserver($uname,$udom)>: find the server which has
13144: the user's directory and files (there must be only one), this caches
13145: the answer, and also caches if there is a borken connection.
1.191 harris41 13146:
13147: =item *
1.394 bowersj2 13148: X<idget()>
13149: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13150: (IDs are a unique resource in a domain, there must be only 1 ID per
13151: username, and only 1 username per ID in a specific domain) (returns
13152: hash: id=>name,id=>name)
1.191 harris41 13153:
13154: =item *
1.394 bowersj2 13155: X<idrget()>
13156: B<idrget($udom,@unames)>: find the IDs behind a list of
13157: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13158:
13159: =item *
1.394 bowersj2 13160: X<idput()>
13161: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13162:
13163: =item *
1.394 bowersj2 13164: X<rolesinit()>
1.1169 droeschl 13165: B<rolesinit($udom,$username)>: get user privileges.
13166: returns user role, first access and timer interval hashes
1.243 albertel 13167:
13168: =item *
1.1171 droeschl 13169: X<privileged()>
13170: B<privileged($username,$domain)>: returns a true if user has a
13171: privileged and active role (i.e. su or dc), false otherwise.
13172:
13173: =item *
1.551 albertel 13174: X<getsection()>
13175: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13176: course $cname, return section name/number or '' for "not in course"
13177: and '-1' for "no section"
13178:
13179: =item *
1.394 bowersj2 13180: X<userenvironment()>
13181: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13182: passed in @what from the requested user's environment, returns a hash
13183:
1.858 raeburn 13184: =item *
13185: X<userlog_query()>
1.859 albertel 13186: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13187: activity.log file. %filters defines filters applied when parsing the
13188: log file. These can be start or end timestamps, or the type of action
13189: - log to look for Login or Logout events, check for Checkin or
13190: Checkout, role for role selection. The response is in the form
13191: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13192: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13193:
1.243 albertel 13194: =back
13195:
13196: =head2 User Roles
13197:
13198: =over 4
13199:
13200: =item *
13201:
1.1172.2.65 raeburn 13202: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13203: returns codes for allowed actions.
13204:
13205: The first argument is required, all others are optional.
13206:
13207: $priv is the privilege being checked.
13208: $uri contains additional information about what is being checked for access (e.g.,
13209: URL, course ID etc.).
13210: $symb is the unique resource instance identifier in a course; if needed,
13211: but not provided, it will be retrieved via a call to &symbread().
13212: $role is the role for which a priv is being checked (only used if priv is evb).
13213: $clientip is the user's IP address (only used when checking for access to portfolio
13214: files).
13215: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13216: prevents recursive calls to &allowed.
13217:
1.243 albertel 13218: F: full access
13219: U,I,K: authentication modes (cxx only)
13220: '': forbidden
13221: 1: user needs to choose course
13222: 2: browse allowed
1.766 albertel 13223: A: passphrase authentication needed
1.1172.2.65 raeburn 13224: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13225:
13226: =item *
13227:
1.1172.2.13 raeburn 13228: constructaccess($url,$setpriv) : check for access to construction space URL
13229:
13230: See if the owner domain and name in the URL match those in the
13231: expected environment. If so, return three element list
13232: ($ownername,$ownerdomain,$ownerhome).
13233:
13234: Otherwise return the null string.
13235:
13236: If second argument 'setpriv' is true, it assigns the privileges,
13237: and returns the same three element list, unless the owner has
13238: blocked "ad hoc" Domain Coordinator access to the Author Space,
13239: in which case the null string is returned.
13240:
13241: =item *
13242:
1.1172.2.84 raeburn 13243: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13244: define a custom role rolename set privileges in format of lonTabs/roles.tab
13245: for system, domain, and course level. $uname and $udom are optional (current
13246: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13247:
13248: =item *
13249:
1.988 raeburn 13250: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13251: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13252: $type is Course (default) or Community.
1.988 raeburn 13253: If $forcedefault evaluates to true, text returned will be default
13254: text for $type. Otherwise, if this is a course, the text returned
13255: will be a custom name for the role (if defined in the course's
13256: environment). If no custom name is defined the default is returned.
13257:
1.832 raeburn 13258: =item *
13259:
1.1172.2.23 raeburn 13260: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13261: All arguments are optional. Returns a hash of a roles, either for
13262: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13263: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13264: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13265: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13266: For each key, value is set to colon-separated start and end times for
13267: the role. If no username and domain are specified, will default to
1.934 raeburn 13268: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13269: of role statuses (active, future or previous), roles
13270: (e.g., cc,in, st etc.) and domains of the roles which can be used
13271: to restrict the list of roles reported. If no array ref is
13272: provided for types, will default to return only active roles.
1.834 albertel 13273:
1.1172.2.13 raeburn 13274: =item *
13275:
13276: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13277: user: $uname:$udom has a role in the course: $cdom_$cnum.
13278:
13279: Additional optional arguments are: $type (if role checking is to be restricted
13280: to certain user status types -- previous (expired roles), active (currently
13281: available roles) or future (roles available in the future), and
13282: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13283: have active Domain Coordinator role in course's domain or in additional
13284: domains (specified in 'Domains to check for privileged users' in course
13285: environment -- set via: Course Settings -> Classlists and staff listing).
13286:
13287: =item *
13288:
13289: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13290: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13291: $possdomains and $possroles are optional array refs -- to domains to check and
13292: roles to check. If $possdomains is not specified, a dump will be done of the
13293: users' roles.db to check for a dc or su role in any domain. This can be
13294: time consuming if &privileged is called repeatedly (e.g., when displaying a
13295: classlist), so in such cases, supplying a $possdomains array is preferred, as
13296: this then allows &privileged_by_domain() to be used, which caches the identity
13297: of privileged users, eliminating the need for repeated calls to &dump().
13298:
13299: =item *
13300:
13301: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13302: where the outer hash keys are domains specified in the $possdomains array ref,
13303: next inner hash keys are privileged roles specified in the $roles array ref,
13304: and the innermost hash contains key = value pairs for username:domain = end:start
13305: for active or future "privileged" users with that role in that domain. To avoid
13306: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13307: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13308:
1.243 albertel 13309: =back
13310:
13311: =head2 User Modification
13312:
13313: =over 4
13314:
13315: =item *
13316:
1.957 raeburn 13317: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13318: user for the level given by URL. Optional start and end dates (leave empty
13319: string or zero for "no date")
1.191 harris41 13320:
13321: =item *
13322:
1.243 albertel 13323: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13324: change a users, password, possible return values are: ok,
13325: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13326: refused
1.191 harris41 13327:
13328: =item *
13329:
1.243 albertel 13330: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13331:
13332: =item *
13333:
1.1058 raeburn 13334: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13335: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13336:
13337: will update user information (firstname,middlename,lastname,generation,
13338: permanentemail), and if forceid is true, student/employee ID also.
13339: A user's institutional affiliation(s) can also be updated.
13340: User information fields will not be overwritten with empty entries
13341: unless the field is included in the $candelete array reference.
13342: This array is included when a single user is modified via "Manage Users",
13343: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13344:
13345: =item *
13346:
1.286 matthew 13347: modifystudent
13348:
1.957 raeburn 13349: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13350: The course id is resolved based on the current user's environment.
13351: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13352: associated with a course.
13353:
1.297 matthew 13354: This call is essentially a wrapper for lonnet::modifyuser and
13355: lonnet::modify_student_enrollment
1.286 matthew 13356:
13357: Inputs:
13358:
13359: =over 4
13360:
1.957 raeburn 13361: =item B<$udom> Student's loncapa domain
1.286 matthew 13362:
1.957 raeburn 13363: =item B<$uname> Student's loncapa login name
1.286 matthew 13364:
1.964 bisitz 13365: =item B<$uid> Student/Employee ID
1.286 matthew 13366:
1.957 raeburn 13367: =item B<$umode> Student's authentication mode
1.286 matthew 13368:
1.957 raeburn 13369: =item B<$upass> Student's password
1.286 matthew 13370:
1.957 raeburn 13371: =item B<$first> Student's first name
1.286 matthew 13372:
1.957 raeburn 13373: =item B<$middle> Student's middle name
1.286 matthew 13374:
1.957 raeburn 13375: =item B<$last> Student's last name
1.286 matthew 13376:
1.957 raeburn 13377: =item B<$gene> Student's generation
1.286 matthew 13378:
1.957 raeburn 13379: =item B<$usec> Student's section in course
1.286 matthew 13380:
13381: =item B<$end> Unix time of the roles expiration
13382:
13383: =item B<$start> Unix time of the roles start date
13384:
13385: =item B<$forceid> If defined, allow $uid to be changed
13386:
13387: =item B<$desiredhome> server to use as home server for student
13388:
1.957 raeburn 13389: =item B<$email> Student's permanent e-mail address
13390:
13391: =item B<$type> Type of enrollment (auto or manual)
13392:
1.963 raeburn 13393: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13394:
13395: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13396:
1.963 raeburn 13397: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13398:
1.963 raeburn 13399: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13400:
1.1172.2.19 raeburn 13401: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13402:
13403: =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 13404:
1.286 matthew 13405: =back
1.297 matthew 13406:
13407: =item *
13408:
13409: modify_student_enrollment
13410:
1.1172.2.31 raeburn 13411: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13412: 'role.request.course' must be defined for this function to proceed.
13413:
13414: Inputs:
13415:
13416: =over 4
13417:
1.1172.2.31 raeburn 13418: =item $udom, student's domain
1.297 matthew 13419:
1.1172.2.31 raeburn 13420: =item $uname, student's name
1.297 matthew 13421:
1.1172.2.31 raeburn 13422: =item $uid, student's user id
1.297 matthew 13423:
1.1172.2.31 raeburn 13424: =item $first, student's first name
1.297 matthew 13425:
13426: =item $middle
13427:
13428: =item $last
13429:
13430: =item $gene
13431:
13432: =item $usec
13433:
13434: =item $end
13435:
13436: =item $start
13437:
1.957 raeburn 13438: =item $type
13439:
13440: =item $locktype
13441:
13442: =item $cid
13443:
13444: =item $selfenroll
13445:
13446: =item $context
13447:
1.1172.2.19 raeburn 13448: =item $credits, number of credits student will earn from this class
13449:
1.1172.2.76 raeburn 13450: =item $instsec, institutional course section code for student
13451:
1.297 matthew 13452: =back
13453:
1.191 harris41 13454:
13455: =item *
13456:
1.243 albertel 13457: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13458: custom role; give a custom role to a user for the level given by URL. Specify
13459: name and domain of role author, and role name
1.191 harris41 13460:
13461: =item *
13462:
1.243 albertel 13463: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13464:
13465: =item *
13466:
1.243 albertel 13467: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13468:
13469: =back
13470:
13471: =head2 Course Infomation
13472:
13473: =over 4
1.191 harris41 13474:
13475: =item *
13476:
1.1118 foxr 13477: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13478: specified course id, including all environment settings for the
13479: course, the description of the course will be in the hash under the
13480: key 'description'
1.191 harris41 13481:
1.1118 foxr 13482: $options is an optional parameter that if supplied is a hash reference that controls
13483: what how this function works. It has the following key/values:
13484:
13485: =over 4
13486:
13487: =item freshen_cache
13488:
13489: If defined, and the environment cache for the course is valid, it is
13490: returned in the returned hash.
13491:
13492: =item one_time
13493:
13494: If defined, the last cache time is set to _now_
13495:
13496: =item user
13497:
13498: If defined, the supplied username is used instead of the current user.
13499:
13500:
13501: =back
13502:
1.191 harris41 13503: =item *
13504:
1.624 albertel 13505: resdata($name,$domain,$type,@which) : request for current parameter
13506: setting for a specific $type, where $type is either 'course' or 'user',
13507: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13508: answers for 10 minutes.
1.243 albertel 13509:
1.877 foxr 13510: =item *
13511:
13512: get_courseresdata($courseid, $domain) : dump the entire course resource
13513: data base, returning a hash that is keyed by the resource name and has
13514: values that are the resource value. I believe that the timestamps and
13515: versions are also returned.
13516:
1.1172.2.31 raeburn 13517: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13518: supplemental content area. This routine caches the number of files for
13519: 10 minutes.
13520:
1.243 albertel 13521: =back
13522:
13523: =head2 Course Modification
13524:
13525: =over 4
1.191 harris41 13526:
13527: =item *
13528:
1.243 albertel 13529: writecoursepref($courseid,%prefs) : write preferences (environment
13530: database) for a course
1.191 harris41 13531:
13532: =item *
13533:
1.1011 raeburn 13534: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13535:
13536: =item *
13537:
1.1038 raeburn 13538: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13539:
1.1167 droeschl 13540: =item *
13541:
13542: is_course($courseid), is_course($cdom, $cnum)
13543:
13544: Accepts either a combined $courseid (in the form of domain_courseid) or the
13545: two component version $cdom, $cnum. It checks if the specified course exists.
13546:
13547: Returns:
13548: undef if the course doesn't exist, otherwise
13549: in scalar context the combined courseid.
13550: in list context the two components of the course identifier, domain and
13551: courseid.
13552:
1.243 albertel 13553: =back
13554:
13555: =head2 Resource Subroutines
13556:
13557: =over 4
1.191 harris41 13558:
13559: =item *
13560:
1.243 albertel 13561: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13562:
13563: =item *
13564:
1.243 albertel 13565: repcopy($filename) : subscribes to the requested file, and attempts to
13566: replicate from the owning library server, Might return
1.607 raeburn 13567: 'unavailable', 'not_found', 'forbidden', 'ok', or
13568: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13569: resource. Expects the local filesystem pathname
13570: (/home/httpd/html/res/....)
13571:
13572: =back
13573:
13574: =head2 Resource Information
13575:
13576: =over 4
1.191 harris41 13577:
13578: =item *
13579:
1.1172.2.28 raeburn 13580: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13581: and returns the value of a variety of different possible values,
13582: $varname should be a request string, and the other parameters can be
13583: used to specify who and what one is asking about. Ordinarily, $cid
13584: does not need to be specified, as it is retrived from
13585: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13586: within lonuserstate::loadmap() when initializing a course, before
13587: $env{'request.course.id'} has been set, so it needs to be provided
13588: in that one case.
1.243 albertel 13589:
13590: Possible values for $varname are environment.lastname (or other item
13591: from the envirnment hash), user.name (or someother aspect about the
13592: user), resource.0.maxtries (or some other part and parameter of a
13593: resource)
1.204 albertel 13594:
13595: =item *
13596:
1.243 albertel 13597: directcondval($number) : get current value of a condition; reads from a state
13598: string
1.204 albertel 13599:
13600: =item *
13601:
1.243 albertel 13602: condval($condidx) : value of condition index based on state
1.204 albertel 13603:
13604: =item *
13605:
1.243 albertel 13606: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13607: resource's metadata, $what should be either a specific key, or either
13608: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13609: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13610:
13611: this function automatically caches all requests
1.191 harris41 13612:
13613: =item *
13614:
1.243 albertel 13615: metadata_query($query,$custom,$customshow) : make a metadata query against the
13616: network of library servers; returns file handle of where SQL and regex results
13617: will be stored for query
1.191 harris41 13618:
13619: =item *
13620:
1.1172.2.66 raeburn 13621: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13622: return symbolic list entry (all arguments optional).
13623:
13624: Args: filename is the filename (including path) for the file for which a symb
13625: is required; donotrecurse, if true will prevent calls to allowed() being made
13626: to check access status if more than one resource was found in the bighash
13627: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13628: a randompick); ignorecachednull, if true will prevent a symb of '' being
13629: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13630: cause possible symbs to be checked to determine if they are subject to content
13631: blocking, if so they will not be included as possible symbs; possibles is a
13632: ref to a hash, which, as a side effect, will be populated with all possible
13633: symbs (content blocking not tested).
13634:
1.243 albertel 13635: returns the data handle
1.191 harris41 13636:
13637: =item *
13638:
1.1172.2.17 raeburn 13639: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13640: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13641: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13642: on failure, user must be in a course, as it assumes the existence of
13643: the course initial hash, and uses $env('request.course.id'}. The third
13644: arg is an optional reference to a scalar. If this arg is passed in the
13645: call to symbverify, it will be set to 1 if the symb has been set to be
13646: encrypted; otherwise it will be null.
1.243 albertel 13647:
1.191 harris41 13648: =item *
13649:
1.243 albertel 13650: symbclean($symb) : removes versions numbers from a symb, returns the
13651: cleaned symb
1.191 harris41 13652:
13653: =item *
13654:
1.243 albertel 13655: is_on_map($uri) : checks if the $uri is somewhere on the current
13656: course map, user must be in a course for it to work.
1.191 harris41 13657:
13658: =item *
13659:
1.243 albertel 13660: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13661:
13662: =item *
13663:
1.243 albertel 13664: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13665: a random seed, all arguments are optional, if they aren't sent it uses the
13666: environment to derive them. Note: if symb isn't sent and it can't get one
13667: from &symbread it will use the current time as its return value
1.191 harris41 13668:
13669: =item *
13670:
1.243 albertel 13671: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13672: unfakeable, receipt
1.191 harris41 13673:
13674: =item *
13675:
1.620 albertel 13676: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13677:
13678: =item *
13679:
1.243 albertel 13680: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13681:
13682: =item *
13683:
1.243 albertel 13684: 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 13685:
13686: =item *
13687:
1.243 albertel 13688: 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 13689:
13690: =item *
13691:
1.243 albertel 13692: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13693:
13694: =item *
13695:
1.243 albertel 13696: devalidate($symb) : devalidate temporary spreadsheet calculations,
13697: forcing spreadsheet to reevaluate the resource scores next time.
13698:
1.1172.2.13 raeburn 13699: =item *
13700:
13701: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13702: when viewing in course context.
13703:
13704: input: six args -- filename (decluttered), course number, course domain,
13705: url, symb (if registered) and group (if this is a
13706: group item -- e.g., bulletin board, group page etc.).
13707:
13708: output: array of five scalars --
13709: $cfile -- url for file editing if editable on current server
13710: $home -- homeserver of resource (i.e., for author if published,
13711: or course if uploaded.).
13712: $switchserver -- 1 if server switch will be needed.
13713: $forceedit -- 1 if icon/link should be to go to edit mode
13714: $forceview -- 1 if icon/link should be to go to view mode
13715:
13716: =item *
13717:
13718: is_course_upload($file,$cnum,$cdom)
13719:
13720: Used in course context to determine if current file was uploaded to
13721: the course (i.e., would be found in /userfiles/docs on the course's
13722: homeserver.
13723:
13724: input: 3 args -- filename (decluttered), course number and course domain.
13725: output: boolean -- 1 if file was uploaded.
13726:
1.243 albertel 13727: =back
13728:
13729: =head2 Storing/Retreiving Data
13730:
13731: =over 4
1.191 harris41 13732:
13733: =item *
13734:
1.1172.2.64 raeburn 13735: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13736: permanently for this url; hashref needs to be given and should be a \%hashname;
13737: the remaining args aren't required and if they aren't passed or are '' they will
13738: be derived from the env (with the exception of $laststore, which is an
13739: optional arg used when a user's submission is stored in grading).
13740: $laststore is $version=$timestamp, where $version is the most recent version
13741: number retrieved for the corresponding $symb in the $namespace db file, and
13742: $timestamp is the timestamp for that transaction (UNIX time).
13743: $laststore is currently only passed when cstore() is called by
13744: structuretags::finalize_storage().
1.191 harris41 13745:
13746: =item *
13747:
1.1172.2.64 raeburn 13748: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13749: but uses critical subroutine
1.191 harris41 13750:
13751: =item *
13752:
1.243 albertel 13753: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13754: all args are optional
1.191 harris41 13755:
13756: =item *
13757:
1.717 albertel 13758: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13759: dumps the complete (or key matching regexp) namespace into a hash
13760: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13761: normally &store()ed into
13762:
13763: $range should be either an integer '100' (give me the first 100
13764: matching records)
13765: or be two integers sperated by a - with no spaces
13766: '30-50' (give me the 30th through the 50th matching
13767: records)
13768:
13769:
13770: =item *
13771:
1.1172.2.59 raeburn 13772: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13773: replaces a &store() version of data with a replacement set of data
13774: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13775: reference. If $tolog is true, the transaction is logged in the courselog
13776: with an action=PUTSTORE.
1.717 albertel 13777:
13778: =item *
13779:
1.243 albertel 13780: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13781: works very similar to store/cstore, but all data is stored in a
13782: temporary location and can be reset using tmpreset, $storehash should
13783: be a hash reference, returns nothing on success
1.191 harris41 13784:
13785: =item *
13786:
1.243 albertel 13787: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13788: similar to restore, but all data is stored in a temporary location and
13789: can be reset using tmpreset. Returns a hash of values on success,
13790: error string otherwise.
1.191 harris41 13791:
13792: =item *
13793:
1.243 albertel 13794: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13795: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13796:
13797: =item *
13798:
1.243 albertel 13799: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13800: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13801:
13802: =item *
13803:
1.243 albertel 13804: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13805: namesp ($udom and $uname are optional)
1.191 harris41 13806:
13807: =item *
13808:
1.702 albertel 13809: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13810: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13811: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13812:
1.702 albertel 13813: $range should be either an integer '100' (give me the first 100
13814: matching records)
13815: or be two integers sperated by a - with no spaces
13816: '30-50' (give me the 30th through the 50th matching
13817: records)
1.449 matthew 13818: =item *
13819:
13820: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13821: $store can be a scalar, an array reference, or if the amount to be
13822: incremented is > 1, a hash reference.
13823:
13824: ($udom and $uname are optional)
1.191 harris41 13825:
13826: =item *
13827:
1.243 albertel 13828: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13829: ($udom and $uname are optional)
1.191 harris41 13830:
13831: =item *
13832:
1.243 albertel 13833: cput($namespace,$storehash,$udom,$uname) : critical put
13834: ($udom and $uname are optional)
1.191 harris41 13835:
13836: =item *
13837:
1.748 albertel 13838: newput($namespace,$storehash,$udom,$uname) :
13839:
13840: Attempts to store the items in the $storehash, but only if they don't
13841: currently exist, if this succeeds you can be certain that you have
13842: successfully created a new key value pair in the $namespace db.
13843:
13844:
13845: Args:
13846: $namespace: name of database to store values to
13847: $storehash: hashref to store to the db
13848: $udom: (optional) domain of user containing the db
13849: $uname: (optional) name of user caontaining the db
13850:
13851: Returns:
13852: 'ok' -> succeeded in storing all keys of $storehash
13853: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13854: least <key> already existed in the db (other
13855: requested keys may also already exist)
1.967 bisitz 13856: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13857: 'con_lost' -> unable to contact request server
13858: 'refused' -> action was not allowed by remote machine
13859:
13860:
13861: =item *
13862:
1.243 albertel 13863: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13864: reference filled in from namesp (encrypts the return communication)
13865: ($udom and $uname are optional)
1.191 harris41 13866:
13867: =item *
13868:
1.243 albertel 13869: log($udom,$name,$home,$message) : write to permanent log for user; use
13870: critical subroutine
13871:
1.806 raeburn 13872: =item *
13873:
1.860 raeburn 13874: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13875: array reference filled in from namespace found in domain level on either
13876: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13877:
13878: =item *
13879:
1.860 raeburn 13880: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13881: domain level either on specified domain server ($uhome) or primary domain
13882: server ($udom and $uhome are optional)
1.806 raeburn 13883:
1.943 raeburn 13884: =item *
13885:
1.1172.2.35 raeburn 13886: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13887: for: authentication, language, quotas, timezone, date locale, and portal URL in
13888: the target domain.
13889:
13890: May also include additional key => value pairs for the following groups:
13891:
13892: =over
13893:
13894: =item
13895: disk quotas (MB allocated by default to portfolios and authoring spaces).
13896:
13897: =over
13898:
13899: =item defaultquota, authorquota
13900:
13901: =back
13902:
13903: =item
13904: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13905: portfolio for users).
13906:
13907: =over
13908:
13909: =item
13910: aboutme, blog, webdav, portfolio
13911:
13912: =back
13913:
13914: =item
13915: requestcourses: ability to request courses, and how requests are processed.
13916:
13917: =over
13918:
13919: =item
1.1172.2.37 raeburn 13920: official, unofficial, community, textbook
1.1172.2.35 raeburn 13921:
13922: =back
13923:
13924: =item
13925: inststatus: types of institutional affiliation, and order in which they are displayed.
13926:
13927: =over
13928:
13929: =item
1.1172.2.44 raeburn 13930: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13931:
13932: =back
13933:
13934: =item
13935: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13936: for course's uploaded content.
13937:
13938: =over
13939:
13940: =item
1.1172.2.68 raeburn 13941: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13942: communityquota, textbookquota
1.1172.2.35 raeburn 13943:
13944: =back
13945:
13946: =item
13947: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13948: on your servers.
13949:
13950: =over
13951:
13952: =item
13953: remotesessions, hostedsessions
13954:
13955: =back
13956:
13957: =back
13958:
13959: In cases where a domain coordinator has never used the "Set Domain Configuration"
13960: utility to create a configuration.db file on a domain's primary library server
13961: only the following domain defaults: auth_def, auth_arg_def, lang_def
13962: -- corresponding values are authentication type (internal, krb4, krb5,
13963: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13964: will be available. Values are retrieved from cache (if current), unless the
13965: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13966: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13967:
13968: Typical usage:
1.943 raeburn 13969:
1.1172.2.35 raeburn 13970: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13971:
1.243 albertel 13972: =back
13973:
13974: =head2 Network Status Functions
13975:
13976: =over 4
1.191 harris41 13977:
13978: =item *
13979:
1.1137 raeburn 13980: dirlist() : return directory list based on URI (first arg).
13981:
13982: Inputs: 1 required, 5 optional.
13983:
13984: =over
13985:
13986: =item
13987: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13988:
13989: =item
13990: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13991:
13992: =item
13993: $username - username of user/course to be listed. Extracted from $uri if absent.
13994:
13995: =item
13996: $getpropath - boolean: 1 if prepend path using &propath().
13997:
13998: =item
13999: $getuserdir - boolean: 1 if prepend path for "userfiles".
14000:
14001: =item
14002: $alternateRoot - path to prepend in place of path from $uri.
14003:
14004: =back
14005:
14006: Returns: Array of up to two items.
14007:
14008: =over
14009:
14010: a reference to an array of files/subdirectories
14011:
14012: =over
14013:
14014: Each element in the array of files/subdirectories is a & separated list of
14015: item name and the result of running stat on the item. If dirlist was requested
14016: for a file instead of a directory, the item name will be ''. For a directory
14017: listing, if the item is a metadata file, the element will end &N&M
14018: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14019: default copyright set (1).
14020:
14021: =back
14022:
14023: a scalar containing error condition (if encountered).
14024:
14025: =over
14026:
14027: =item
14028: no_host (no homeserver identified for $username:$domain).
14029:
14030: =item
14031: no_such_host (server contacted for listing not identified as valid host).
14032:
14033: =item
14034: con_lost (connection to remote server failed).
14035:
14036: =item
14037: refused (invalid $username:$domain received on lond side).
14038:
14039: =item
14040: no_such_dir (directory at specified path on lond side does not exist).
14041:
14042: =item
14043: empty (directory at specified path on lond side is empty).
14044:
14045: =over
14046:
14047: This is currently not encountered because the &ls3, &ls2,
14048: &ls (_handler) routines on the lond side do not filter out
14049: . and .. from a directory listing.
14050:
14051: =back
14052:
14053: =back
14054:
14055: =back
1.191 harris41 14056:
14057: =item *
14058:
1.243 albertel 14059: spareserver() : find server with least workload from spare.tab
14060:
1.986 foxr 14061:
14062: =item *
14063:
14064: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14065: if there is no corresponding loncapa host.
14066:
1.243 albertel 14067: =back
14068:
1.986 foxr 14069:
1.243 albertel 14070: =head2 Apache Request
14071:
14072: =over 4
1.191 harris41 14073:
14074: =item *
14075:
1.243 albertel 14076: ssi($url,%hash) : server side include, does a complete request cycle on url to
14077: localhost, posts hash
14078:
14079: =back
14080:
14081: =head2 Data to String to Data
14082:
14083: =over 4
1.191 harris41 14084:
14085: =item *
14086:
1.243 albertel 14087: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14088: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14089:
14090: =item *
14091:
1.243 albertel 14092: hashref2str($hashref) : convert a hashref into a string complete with
14093: escaping and '=' and '&' separators, supports elements that are
14094: arrayrefs and hashrefs
1.191 harris41 14095:
14096: =item *
14097:
1.243 albertel 14098: arrayref2str($arrayref) : convert an arrayref into a string complete
14099: with escaping and '&' separators, supports elements that are arrayrefs
14100: and hashrefs
1.191 harris41 14101:
14102: =item *
14103:
1.243 albertel 14104: str2hash($string) : convert string to hash using unescaping and
14105: splitting on '=' and '&', supports elements that are arrayrefs and
14106: hashrefs
1.191 harris41 14107:
14108: =item *
14109:
1.243 albertel 14110: str2array($string) : convert string to hash using unescaping and
14111: splitting on '&', supports elements that are arrayrefs and hashrefs
14112:
14113: =back
14114:
14115: =head2 Logging Routines
14116:
14117:
14118: These routines allow one to make log messages in the lonnet.log and
14119: lonnet.perm logfiles.
1.191 harris41 14120:
1.1119 foxr 14121: =over 4
14122:
1.191 harris41 14123: =item *
14124:
1.243 albertel 14125: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14126:
14127: =item *
14128:
1.243 albertel 14129: logthis() : append message to the normal lonnet.log file, it gets
14130: preiodically rolled over and deleted.
1.191 harris41 14131:
14132: =item *
14133:
1.243 albertel 14134: logperm() : append a permanent message to lonnet.perm.log, this log
14135: file never gets deleted by any automated portion of the system, only
14136: messages of critical importance should go in here.
14137:
1.1119 foxr 14138:
1.243 albertel 14139: =back
14140:
14141: =head2 General File Helper Routines
14142:
14143: =over 4
1.191 harris41 14144:
14145: =item *
14146:
1.481 raeburn 14147: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14148: (a) files in /uploaded
14149: (i) If a local copy of the file exists -
14150: compares modification date of local copy with last-modified date for
14151: definitive version stored on home server for course. If local copy is
14152: stale, requests a new version from the home server and stores it.
14153: If the original has been removed from the home server, then local copy
14154: is unlinked.
14155: (ii) If local copy does not exist -
14156: requests the file from the home server and stores it.
14157:
14158: If $caller is 'uploadrep':
14159: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14160: for request for files originally uploaded via DOCS.
14161: - returns 'ok' if fresh local copy now available, -1 otherwise.
14162:
14163: Otherwise:
14164: This indicates a call from the content generation phase of the request.
14165: - returns the entire contents of the file or -1.
14166:
14167: (b) files in /res
14168: - returns the entire contents of a file or -1;
14169: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14170:
1.712 albertel 14171:
14172: =item *
14173:
14174: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14175: reference
14176:
14177: returns either a stat() list of data about the file or an empty list
14178: if the file doesn't exist or couldn't find out about it (connection
14179: problems or user unknown)
14180:
1.191 harris41 14181: =item *
14182:
1.243 albertel 14183: filelocation($dir,$file) : returns file system location of a file
14184: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14185: directory that relative $file lookups are to looked in ($dir of /a/dir
14186: and a file of ../bob will become /a/bob)
1.191 harris41 14187:
14188: =item *
14189:
14190: hreflocation($dir,$file) : returns file system location or a URL; same as
14191: filelocation except for hrefs
14192:
14193: =item *
14194:
1.1172.2.49 raeburn 14195: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14196: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14197:
1.243 albertel 14198: =back
14199:
1.608 albertel 14200: =head2 Usererfile file routines (/uploaded*)
14201:
14202: =over 4
14203:
14204: =item *
14205:
14206: userfileupload(): main rotine for putting a file in a user or course's
14207: filespace, arguments are,
14208:
1.620 albertel 14209: formname - required - this is the name of the element in $env where the
1.608 albertel 14210: filename, and the contents of the file to create/modifed exist
1.620 albertel 14211: the filename is in $env{'form.'.$formname.'.filename'} and the
14212: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14213: context - if coursedoc, store the file in the course of the active role
14214: of the current user;
14215: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14216: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14217: subdir - required - subdirectory to put the file in under ../userfiles/
14218: if undefined, it will be placed in "unknown"
14219:
14220: (This routine calls clean_filename() to remove any dangerous
14221: characters from the filename, and then calls finuserfileupload() to
14222: complete the transaction)
14223:
14224: returns either the url of the uploaded file (/uploaded/....) if successful
14225: and /adm/notfound.html if unsuccessful
14226:
14227: =item *
14228:
14229: clean_filename(): routine for cleaing a filename up for storage in
14230: userfile space, argument is:
14231:
14232: filename - proposed filename
14233:
14234: returns: the new clean filename
14235:
14236: =item *
14237:
1.1090 raeburn 14238: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14239: userspace, probably shouldn't be called directly
14240:
14241: docuname: username or courseid of destination for the file
14242: docudom: domain of user/course of destination for the file
14243: formname: same as for userfileupload()
1.1090 raeburn 14244: fname: filename (including subdirectories) for the file
14245: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14246: allfiles: reference to hash used to store objects found by parser
14247: codebase: reference to hash used for codebases of java objects found by parser
14248: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14249: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14250: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14251: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14252: context: if 'overwrite', will move the uploaded file from its temporary location to
14253: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14254: mimetype: reference to scalar to accommodate mime type determined
14255: from File::MMagic if $parser = parse.
1.608 albertel 14256:
14257: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14258: and /adm/notfound.html if unsuccessful (or an error message if context
14259: was 'overwrite').
14260:
1.608 albertel 14261:
14262: =item *
14263:
14264: renameuserfile(): renames an existing userfile to a new name
14265:
14266: Args:
14267: docuname: username or courseid of destination for the file
14268: docudom: domain of user/course of destination for the file
14269: old: current file name (including any subdirs under userfiles)
14270: new: desired file name (including any subdirs under userfiles)
14271:
14272: =item *
14273:
14274: mkdiruserfile(): creates a directory is a userfiles dir
14275:
14276: Args:
14277: docuname: username or courseid of destination for the file
14278: docudom: domain of user/course of destination for the file
14279: dir: dir to create (including any subdirs under userfiles)
14280:
14281: =item *
14282:
14283: removeuserfile(): removes a file that exists in userfiles
14284:
14285: Args:
14286: docuname: username or courseid of destination for the file
14287: docudom: domain of user/course of destination for the file
14288: fname: filname to delete (including any subdirs under userfiles)
14289:
14290: =item *
14291:
14292: removeuploadedurl(): convience function for removeuserfile()
14293:
14294: Args:
14295: url: a full /uploaded/... url to delete
14296:
1.747 albertel 14297: =item *
14298:
14299: get_portfile_permissions():
14300: Args:
14301: domain: domain of user or course contain the portfolio files
14302: user: name of user or num of course contain the portfolio files
14303: Returns:
14304: hashref of a dump of the proper file_permissions.db
14305:
14306:
14307: =item *
14308:
14309: get_access_controls():
14310:
14311: Args:
14312: current_permissions: the hash ref returned from get_portfile_permissions()
14313: group: (optional) the group you want the files associated with
14314: file: (optional) the file you want access info on
14315:
14316: Returns:
1.749 raeburn 14317: a hash (keys are file names) of hashes containing
14318: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14319: values are XML containing access control settings (see below)
1.747 albertel 14320:
14321: Internal notes:
14322:
1.749 raeburn 14323: access controls are stored in file_permissions.db as key=value pairs.
14324: key -> path to file/file_name\0uniqueID:scope_end_start
14325: where scope -> public,guest,course,group,domains or users.
14326: end -> UNIX time for end of access (0 -> no end date)
14327: start -> UNIX time for start of access
14328:
14329: value -> XML description of access control
14330: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14331: <start></start>
14332: <end></end>
14333:
14334: <password></password> for scope type = guest
14335:
14336: <domain></domain> for scope type = course or group
14337: <number></number>
14338: <roles id="">
14339: <role></role>
14340: <access></access>
14341: <section></section>
14342: <group></group>
14343: </roles>
14344:
14345: <dom></dom> for scope type = domains
14346:
14347: <users> for scope type = users
14348: <user>
14349: <uname></uname>
14350: <udom></udom>
14351: </user>
14352: </users>
14353: </scope>
14354:
14355: Access data is also aggregated for each file in an additional key=value pair:
14356: key -> path to file/file_name\0accesscontrol
14357: value -> reference to hash
14358: hash contains key = value pairs
14359: where key = uniqueID:scope_end_start
14360: value = UNIX time record was last updated
14361:
14362: Used to improve speed of look-ups of access controls for each file.
14363:
14364: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14365:
1.1172.2.13 raeburn 14366: =item *
14367:
1.749 raeburn 14368: modify_access_controls():
14369:
14370: Modifies access controls for a portfolio file
14371: Args
14372: 1. file name
14373: 2. reference to hash of required changes,
14374: 3. domain
14375: 4. username
14376: where domain,username are the domain of the portfolio owner
14377: (either a user or a course)
14378:
14379: Returns:
14380: 1. result of additions or updates ('ok' or 'error', with error message).
14381: 2. result of deletions ('ok' or 'error', with error message).
14382: 3. reference to hash of any new or updated access controls.
14383: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14384: key = integer (inbound ID)
1.1172.2.13 raeburn 14385: value = uniqueID
14386:
14387: =item *
14388:
14389: get_timebased_id():
14390:
14391: Attempts to get a unique timestamp-based suffix for use with items added to a
14392: course via the Course Editor (e.g., folders, composite pages,
14393: group bulletin boards).
14394:
14395: Args: (first three required; six others optional)
14396:
14397: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14398: docssequence, or name of group
14399:
14400: 2. keyid (alphanumeric): name of temporary locking key in hash,
14401: e.g., num, boardids
14402:
14403: 3. namespace: name of gdbm file used to store suffixes already assigned;
14404: file will be named nohist_namespace.db
14405:
14406: 4. cdom: domain of course; default is current course domain from %env
14407:
14408: 5. cnum: course number; default is current course number from %env
14409:
14410: 6. idtype: set to concat if an additional digit is to be appended to the
14411: unix timestamp to form the suffix, if the plain timestamp is already
14412: in use. Default is to not do this, but simply increment the unix
14413: timestamp by 1 until a unique key is obtained.
14414:
14415: 7. who: holder of locking key; defaults to user:domain for user.
14416:
14417: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14418: retrying); default is 3.
14419:
14420: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14421:
14422: Returns:
14423:
14424: 1. suffix obtained (numeric)
14425:
14426: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14427:
14428: 3. error: contains (localized) error message if an error occurred.
14429:
1.747 albertel 14430:
1.608 albertel 14431: =back
14432:
1.243 albertel 14433: =head2 HTTP Helper Routines
14434:
14435: =over 4
14436:
1.191 harris41 14437: =item *
14438:
14439: escape() : unpack non-word characters into CGI-compatible hex codes
14440:
14441: =item *
14442:
14443: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14444:
1.243 albertel 14445: =back
14446:
14447: =head1 PRIVATE SUBROUTINES
14448:
14449: =head2 Underlying communication routines (Shouldn't call)
14450:
14451: =over 4
14452:
14453: =item *
14454:
14455: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14456:
14457: =item *
14458:
14459: reply() : uses subreply to send a message to remote machine, logs all failures
14460:
14461: =item *
14462:
14463: critical() : passes a critical message to another server; if cannot
14464: get through then place message in connection buffer directory and
14465: returns con_delayed, if incapable of saving message, returns
14466: con_failed
14467:
14468: =item *
14469:
14470: reconlonc() : tries to reconnect lonc client processes.
14471:
14472: =back
14473:
14474: =head2 Resource Access Logging
14475:
14476: =over 4
14477:
14478: =item *
14479:
14480: flushcourselogs() : flush (save) buffer logs and access logs
14481:
14482: =item *
14483:
14484: courselog($what) : save message for course in hash
14485:
14486: =item *
14487:
14488: courseacclog($what) : save message for course using &courselog(). Perform
14489: special processing for specific resource types (problems, exams, quizzes, etc).
14490:
1.191 harris41 14491: =item *
14492:
14493: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14494: as a PerlChildExitHandler
1.243 albertel 14495:
14496: =back
14497:
14498: =head2 Other
14499:
14500: =over 4
14501:
14502: =item *
14503:
14504: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14505:
14506: =back
14507:
14508: =cut
1.877 foxr 14509:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>