Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.41
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.41! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.40 2014/02/24 03:09:05 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
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') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
847: if ($uint_dom) {
848: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
849: $try_server));
850: }
851: ($spare_server, $lowest_load) =
852: &compare_server_load($try_server, $spare_server, $lowest_load);
853: }
1.1083 raeburn 854: }
1.784 albertel 855:
1.1123 raeburn 856: my $found_server = ($spare_server ne '' && $lowest_load < 100);
857:
858: if (!$found_server) {
859: if (ref($spareshash->{'default'}) eq 'ARRAY') {
860: foreach my $try_server (@{ $spareshash->{'default'} }) {
861: if ($uint_dom) {
862: next unless (&spare_can_host($udom,$uint_dom,
863: $remotesessions,$try_server));
864: }
865: ($spare_server, $lowest_load) =
866: &compare_server_load($try_server, $spare_server, $lowest_load);
867: }
868: }
869: }
1.784 albertel 870: }
871:
872: if (!$want_server_name) {
1.968 raeburn 873: my $protocol = 'http';
874: if ($protocol{$spare_server} eq 'https') {
875: $protocol = $protocol{$spare_server};
876: }
1.1001 raeburn 877: if (defined($spare_server)) {
878: my $hostname = &hostname($spare_server);
1.1083 raeburn 879: if (defined($hostname)) {
1.1001 raeburn 880: $spare_server = $protocol.'://'.$hostname;
881: }
882: }
1.784 albertel 883: }
884: return $spare_server;
885: }
886:
887: sub compare_server_load {
1.1172.2.41! raeburn 888: my ($try_server, $spare_server, $lowest_load, $required) = @_;
! 889:
! 890: if ($required) {
! 891: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
! 892: my $remoterev = &get_server_loncaparev(undef,$try_server);
! 893: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
! 894: if (($major eq '' && $minor eq '') ||
! 895: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
! 896: return ($spare_server,$lowest_load);
! 897: }
! 898: }
1.784 albertel 899:
900: my $loadans = &reply('load', $try_server);
901: my $userloadans = &reply('userload',$try_server);
902:
903: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 904: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 905: }
906:
907: my $load;
908: if ($loadans =~ /\d/) {
909: if ($userloadans =~ /\d/) {
910: #both are numbers, pick the bigger one
911: $load = ($loadans > $userloadans) ? $loadans
912: : $userloadans;
1.411 albertel 913: } else {
1.784 albertel 914: $load = $loadans;
1.411 albertel 915: }
1.784 albertel 916: } else {
917: $load = $userloadans;
918: }
919:
920: if (($load =~ /\d/) && ($load < $lowest_load)) {
921: $spare_server = $try_server;
922: $lowest_load = $load;
1.370 albertel 923: }
1.784 albertel 924: return ($spare_server,$lowest_load);
1.202 matthew 925: }
1.914 albertel 926:
927: # --------------------------- ask offload servers if user already has a session
928: sub find_existing_session {
929: my ($udom,$uname) = @_;
1.1123 raeburn 930: my $spareshash = &this_host_spares($udom);
931: if (ref($spareshash) eq 'HASH') {
932: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'primary'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
937: if (ref($spareshash->{'default'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'default'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
1.914 albertel 942: }
943: return;
944: }
945:
946: # -------------------------------- ask if server already has a session for user
947: sub has_user_session {
948: my ($lonid,$udom,$uname) = @_;
949: my $result = &reply(join(':','userhassession',
950: map {&escape($_)} ($udom,$uname)),$lonid);
951: return 1 if ($result eq 'ok');
952:
953: return 0;
954: }
955:
1.1076 raeburn 956: # --------- determine least loaded server in a user's domain which allows login
957:
958: sub choose_server {
1.1172.2.41! raeburn 959: my ($udom,$checkloginvia,$required)) = @_;
1.1076 raeburn 960: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 961: my %servers = &get_servers($udom);
1.1076 raeburn 962: my $lowest_load = 30000;
1.1151 raeburn 963: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 964: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 965: my $loginvia;
966: if ($checkloginvia) {
967: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 968: if ($loginvia) {
969: my ($server,$path) = split(/:/,$loginvia);
970: ($login_host, $lowest_load) =
1.1172.2.41! raeburn 971: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 972: if ($login_host eq $server) {
973: $portal_path = $path;
1.1151 raeburn 974: $isredirect = 1;
1.1116 raeburn 975: }
976: } else {
977: ($login_host, $lowest_load) =
1.1172.2.41! raeburn 978: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 979: if ($login_host eq $lonhost) {
980: $portal_path = '';
1.1151 raeburn 981: $isredirect = '';
1.1116 raeburn 982: }
983: }
984: } else {
1.1076 raeburn 985: ($login_host, $lowest_load) =
1.1172.2.41! raeburn 986: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 987: }
988: }
989: if ($login_host ne '') {
1.1116 raeburn 990: $hostname = &hostname($login_host);
1.1076 raeburn 991: }
1.1151 raeburn 992: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 993: }
994:
1.202 matthew 995: # --------------------------------------------- Try to change a user's password
996:
997: sub changepass {
1.799 raeburn 998: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 999: $currentpass = &escape($currentpass);
1000: $newpass = &escape($newpass);
1.1030 raeburn 1001: my $lonhost = $perlvar{'lonHostID'};
1002: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1003: $server);
1004: if (! $answer) {
1005: &logthis("No reply on password change request to $server ".
1006: "by $uname in domain $udom.");
1007: } elsif ($answer =~ "^ok") {
1008: &logthis("$uname in $udom successfully changed their password ".
1009: "on $server.");
1010: } elsif ($answer =~ "^pwchange_failure") {
1011: &logthis("$uname in $udom was unable to change their password ".
1012: "on $server. The action was blocked by either lcpasswd ".
1013: "or pwchange");
1014: } elsif ($answer =~ "^non_authorized") {
1015: &logthis("$uname in $udom did not get their password correct when ".
1016: "attempting to change it on $server.");
1017: } elsif ($answer =~ "^auth_mode_error") {
1018: &logthis("$uname in $udom attempted to change their password despite ".
1019: "not being locally or internally authenticated on $server.");
1020: } elsif ($answer =~ "^unknown_user") {
1021: &logthis("$uname in $udom attempted to change their password ".
1022: "on $server but were unable to because $server is not ".
1023: "their home server.");
1024: } elsif ($answer =~ "^refused") {
1025: &logthis("$server refused to change $uname in $udom password because ".
1026: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1027: } elsif ($answer =~ "invalid_client") {
1028: &logthis("$server refused to change $uname in $udom password because ".
1029: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1030: }
1031: return $answer;
1.1 albertel 1032: }
1033:
1.169 harris41 1034: # ----------------------- Try to determine user's current authentication scheme
1035:
1036: sub queryauthenticate {
1037: my ($uname,$udom)=@_;
1.456 albertel 1038: my $uhome=&homeserver($uname,$udom);
1039: if (!$uhome) {
1040: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1041: return 'no_host';
1042: }
1043: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1044: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1045: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1046: }
1.456 albertel 1047: return $answer;
1.169 harris41 1048: }
1049:
1.1 albertel 1050: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1051:
1.1 albertel 1052: sub authenticate {
1.1073 raeburn 1053: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1054: $upass=&escape($upass);
1055: $uname= &LONCAPA::clean_username($uname);
1.836 www 1056: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1057: my $newhome;
1.836 www 1058: if ((!$uhome) || ($uhome eq 'no_host')) {
1059: # Maybe the machine was offline and only re-appeared again recently?
1060: &reconlonc();
1061: # One more
1.952 raeburn 1062: $uhome=&homeserver($uname,$udom,1);
1063: if (($uhome eq 'no_host') && $checkdefauth) {
1064: if (defined(&domain($udom,'primary'))) {
1065: $newhome=&domain($udom,'primary');
1066: }
1067: if ($newhome ne '') {
1068: $uhome = $newhome;
1069: }
1070: }
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1073: return 'no_host';
1074: }
1.1 albertel 1075: }
1.1073 raeburn 1076: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1077: if ($answer eq 'authorized') {
1.952 raeburn 1078: if ($newhome) {
1079: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1080: return 'no_account_on_host';
1081: } else {
1082: &logthis("User $uname at $udom authorized by $uhome");
1083: return $uhome;
1084: }
1.471 albertel 1085: }
1086: if ($answer eq 'non_authorized') {
1087: &logthis("User $uname at $udom rejected by $uhome");
1088: return 'no_host';
1.9 www 1089: }
1.471 albertel 1090: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1091: return 'no_host';
1092: }
1093:
1.1073 raeburn 1094: sub can_host_session {
1.1074 raeburn 1095: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1096: my $canhost = 1;
1.1074 raeburn 1097: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1098: if (ref($remotesessions) eq 'HASH') {
1099: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1100: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1101: $canhost = 0;
1102: } else {
1103: $canhost = 1;
1104: }
1105: }
1106: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1107: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1108: $canhost = 1;
1109: } else {
1110: $canhost = 0;
1111: }
1112: }
1113: if ($canhost) {
1114: if ($remotesessions->{'version'} ne '') {
1115: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1116: if ($reqmajor ne '' && $reqminor ne '') {
1117: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1118: my $major = $1;
1119: my $minor = $2;
1120: if (($major < $reqmajor ) ||
1121: (($major == $reqmajor) && ($minor < $reqminor))) {
1122: $canhost = 0;
1123: }
1124: } else {
1125: $canhost = 0;
1126: }
1127: }
1128: }
1129: }
1130: }
1131: if ($canhost) {
1132: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1133: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1134: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1135: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1136: if (($uint_dom ne '') &&
1137: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1138: $canhost = 0;
1139: } else {
1140: $canhost = 1;
1141: }
1142: }
1143: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1144: if (($uint_dom ne '') &&
1145: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1146: $canhost = 1;
1147: } else {
1148: $canhost = 0;
1149: }
1150: }
1151: }
1152: }
1153: return $canhost;
1154: }
1155:
1.1083 raeburn 1156: sub spare_can_host {
1157: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1158: my $canhost=1;
1159: my @intdoms;
1160: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1161: if (ref($internet_names) eq 'ARRAY') {
1162: @intdoms = @{$internet_names};
1163: }
1164: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1165: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1166: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1167: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1168: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1169: $canhost = &can_host_session($udom,$try_server,$remoterev,
1170: $remotesessions,
1171: $defdomdefaults{'hostedsessions'});
1172: }
1173: return $canhost;
1174: }
1175:
1.1123 raeburn 1176: sub this_host_spares {
1177: my ($dom) = @_;
1.1126 raeburn 1178: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1179: my @hosts = ¤t_machine_ids();
1180: foreach my $lonhost (@hosts) {
1181: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1182: $dom_in_use = $dom;
1183: $lonhost_in_use = $lonhost;
1.1123 raeburn 1184: last;
1185: }
1186: }
1.1126 raeburn 1187: if ($dom_in_use ne '') {
1188: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1189: }
1190: if (ref($result) ne 'HASH') {
1191: $lonhost_in_use = $perlvar{'lonHostID'};
1192: $dom_in_use = &host_domain($lonhost_in_use);
1193: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1194: if (ref($result) ne 'HASH') {
1195: $result = \%spareid;
1196: }
1197: }
1198: return $result;
1199: }
1200:
1201: sub spares_for_offload {
1202: my ($dom_in_use,$lonhost_in_use) = @_;
1203: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1204: if (defined($cached)) {
1205: return $result;
1206: } else {
1.1126 raeburn 1207: my $cachetime = 60*60*24;
1208: my %domconfig =
1209: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1210: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1211: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1212: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1213: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1214: }
1215: }
1216: }
1217: }
1.1126 raeburn 1218: return;
1.1123 raeburn 1219: }
1220:
1.1129 raeburn 1221: sub get_lonbalancer_config {
1222: my ($servers) = @_;
1223: my ($currbalancer,$currtargets);
1224: if (ref($servers) eq 'HASH') {
1225: foreach my $server (keys(%{$servers})) {
1226: my %what = (
1227: spareid => 1,
1228: perlvar => 1,
1229: );
1230: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1231: if ($result eq 'ok') {
1232: if (ref($returnhash) eq 'HASH') {
1233: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1234: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1235: $currbalancer = $server;
1236: $currtargets = {};
1237: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1238: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1239: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1240: }
1241: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1242: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1243: }
1244: }
1245: last;
1246: }
1247: }
1248: }
1249: }
1250: }
1251: }
1252: return ($currbalancer,$currtargets);
1253: }
1254:
1255: sub check_loadbalancing {
1256: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1257: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1258: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1259: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1260: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1261: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1262: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1263: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1264: my $serverhomedom = &host_domain($lonhost);
1265:
1266: my $cachetime = 60*60*24;
1267:
1268: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1269: $dom_in_use = $udom;
1270: $homeintdom = 1;
1271: } else {
1272: $dom_in_use = $serverhomedom;
1273: }
1274: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1275: unless (defined($cached)) {
1276: my %domconfig =
1277: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1278: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1279: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1280: }
1281: }
1282: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1283: ($is_balancer,$currtargets,$currrules) =
1284: &check_balancer_result($result,@hosts);
1.1129 raeburn 1285: if ($is_balancer) {
1286: if (ref($currrules) eq 'HASH') {
1287: if ($homeintdom) {
1288: if ($uname ne '') {
1289: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1290: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1291: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1292: $rule_in_effect = $currrules->{'_LC_author'};
1293: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1294: $rule_in_effect = $currrules->{'_LC_adv'}
1295: }
1296: }
1297: if ($rule_in_effect eq '') {
1298: my %userenv = &userenvironment($udom,$uname,'inststatus');
1299: if ($userenv{'inststatus'} ne '') {
1300: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1301: my ($othertitle,$usertypes,$types) =
1302: &Apache::loncommon::sorted_inst_types($udom);
1303: if (ref($types) eq 'ARRAY') {
1304: foreach my $type (@{$types}) {
1305: if (grep(/^\Q$type\E$/,@statuses)) {
1306: if (exists($currrules->{$type})) {
1307: $rule_in_effect = $currrules->{$type};
1308: }
1309: }
1310: }
1311: }
1312: } else {
1313: if (exists($currrules->{'default'})) {
1314: $rule_in_effect = $currrules->{'default'};
1315: }
1316: }
1317: }
1318: } else {
1319: if (exists($currrules->{'default'})) {
1320: $rule_in_effect = $currrules->{'default'};
1321: }
1322: }
1323: } else {
1324: if ($currrules->{'_LC_external'} ne '') {
1325: $rule_in_effect = $currrules->{'_LC_external'};
1326: }
1327: }
1328: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1329: $uname,$udom);
1330: }
1331: }
1332: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1333: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1334: unless (defined($cached)) {
1335: my %domconfig =
1336: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1337: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1338: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1339: }
1340: }
1341: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1342: ($is_balancer,$currtargets,$currrules) =
1343: &check_balancer_result($result,@hosts);
1344: if ($is_balancer) {
1.1129 raeburn 1345: if (ref($currrules) eq 'HASH') {
1346: if ($currrules->{'_LC_internetdom'} ne '') {
1347: $rule_in_effect = $currrules->{'_LC_internetdom'};
1348: }
1349: }
1350: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1351: $uname,$udom);
1352: }
1353: } else {
1354: if ($perlvar{'lonBalancer'} eq 'yes') {
1355: $is_balancer = 1;
1356: $offloadto = &this_host_spares($dom_in_use);
1357: }
1358: }
1359: } else {
1360: if ($perlvar{'lonBalancer'} eq 'yes') {
1361: $is_balancer = 1;
1362: $offloadto = &this_host_spares($dom_in_use);
1363: }
1364: }
1.1172.2.5 raeburn 1365: if ($is_balancer) {
1366: my $lowest_load = 30000;
1367: if (ref($offloadto) eq 'HASH') {
1368: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1369: foreach my $try_server (@{$offloadto->{'primary'}}) {
1370: ($otherserver,$lowest_load) =
1371: &compare_server_load($try_server,$otherserver,$lowest_load);
1372: }
1.1129 raeburn 1373: }
1.1172.2.5 raeburn 1374: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1375:
1.1172.2.5 raeburn 1376: if (!$found_server) {
1377: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1378: foreach my $try_server (@{$offloadto->{'default'}}) {
1379: ($otherserver,$lowest_load) =
1380: &compare_server_load($try_server,$otherserver,$lowest_load);
1381: }
1382: }
1383: }
1384: } elsif (ref($offloadto) eq 'ARRAY') {
1385: if (@{$offloadto} == 1) {
1386: $otherserver = $offloadto->[0];
1387: } elsif (@{$offloadto} > 1) {
1388: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1389: ($otherserver,$lowest_load) =
1390: &compare_server_load($try_server,$otherserver,$lowest_load);
1391: }
1392: }
1393: }
1.1172.2.5 raeburn 1394: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1395: $is_balancer = 0;
1396: if ($uname ne '' && $udom ne '') {
1397: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1398:
1399: &appenv({'user.loadbalexempt' => $lonhost,
1400: 'user.loadbalcheck.time' => time});
1401: }
1.1129 raeburn 1402: }
1403: }
1404: }
1405: return ($is_balancer,$otherserver);
1406: }
1407:
1.1172.2.12 raeburn 1408: sub check_balancer_result {
1409: my ($result,@hosts) = @_;
1410: my ($is_balancer,$currtargets,$currrules);
1411: if (ref($result) eq 'HASH') {
1412: if ($result->{'lonhost'} ne '') {
1413: my $currbalancer = $result->{'lonhost'};
1414: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1415: $is_balancer = 1;
1416: $currtargets = $result->{'targets'};
1417: $currrules = $result->{'rules'};
1418: }
1419: } else {
1420: foreach my $key (keys(%{$result})) {
1421: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1422: (ref($result->{$key}) eq 'HASH')) {
1423: $is_balancer = 1;
1424: $currrules = $result->{$key}{'rules'};
1425: $currtargets = $result->{$key}{'targets'};
1426: last;
1427: }
1428: }
1429: }
1430: }
1431: return ($is_balancer,$currtargets,$currrules);
1432: }
1433:
1.1129 raeburn 1434: sub get_loadbalancer_targets {
1435: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1436: my $offloadto;
1.1172.2.4 raeburn 1437: if ($rule_in_effect eq 'none') {
1438: return [$perlvar{'lonHostID'}];
1439: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1440: $offloadto = $currtargets;
1441: } else {
1442: if ($rule_in_effect eq 'homeserver') {
1443: my $homeserver = &homeserver($uname,$udom);
1444: if ($homeserver ne 'no_host') {
1445: $offloadto = [$homeserver];
1446: }
1447: } elsif ($rule_in_effect eq 'externalbalancer') {
1448: my %domconfig =
1449: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1450: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1451: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1452: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1453: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1454: }
1455: }
1456: } else {
1.1172.2.7 raeburn 1457: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1458: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1459: if (&hostname($remotebalancer) ne '') {
1460: $offloadto = [$remotebalancer];
1461: }
1462: }
1463: } elsif (&hostname($rule_in_effect) ne '') {
1464: $offloadto = [$rule_in_effect];
1465: }
1466: }
1467: return $offloadto;
1468: }
1469:
1.1127 raeburn 1470: sub internet_dom_servers {
1471: my ($dom) = @_;
1472: my (%uniqservers,%servers);
1473: my $primaryserver = &hostname(&domain($dom,'primary'));
1474: my @machinedoms = &machine_domains($primaryserver);
1475: foreach my $mdom (@machinedoms) {
1476: my %currservers = %servers;
1477: my %server = &get_servers($mdom);
1478: %servers = (%currservers,%server);
1479: }
1480: my %by_hostname;
1481: foreach my $id (keys(%servers)) {
1482: push(@{$by_hostname{$servers{$id}}},$id);
1483: }
1484: foreach my $hostname (sort(keys(%by_hostname))) {
1485: if (@{$by_hostname{$hostname}} > 1) {
1486: my $match = 0;
1487: foreach my $id (@{$by_hostname{$hostname}}) {
1488: if (&host_domain($id) eq $dom) {
1489: $uniqservers{$id} = $hostname;
1490: $match = 1;
1491: }
1492: }
1493: unless ($match) {
1494: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1495: }
1496: } else {
1497: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1498: }
1499: }
1500: return %uniqservers;
1501: }
1502:
1.1 albertel 1503: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1504:
1.599 albertel 1505: my %homecache;
1.1 albertel 1506: sub homeserver {
1.230 stredwic 1507: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1508: my $index="$uname:$udom";
1.426 albertel 1509:
1.599 albertel 1510: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1511:
1512: my %servers = &get_servers($udom,'library');
1513: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1514: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1515: exists($badServerCache{$tryserver}));
1.841 albertel 1516:
1517: my $answer=reply("home:$udom:$uname",$tryserver);
1518: if ($answer eq 'found') {
1519: delete($badServerCache{$tryserver});
1520: return $homecache{$index}=$tryserver;
1521: } elsif ($answer eq 'no_host') {
1522: $badServerCache{$tryserver}=1;
1523: }
1.1 albertel 1524: }
1525: return 'no_host';
1.70 www 1526: }
1527:
1528: # ------------------------------------- Find the usernames behind a list of IDs
1529:
1530: sub idget {
1531: my ($udom,@ids)=@_;
1532: my %returnhash=();
1533:
1.841 albertel 1534: my %servers = &get_servers($udom,'library');
1535: foreach my $tryserver (keys(%servers)) {
1536: my $idlist=join('&',@ids);
1537: $idlist=~tr/A-Z/a-z/;
1538: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1539: my @answer=();
1540: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1541: @answer=split(/\&/,$reply);
1542: } ;
1543: my $i;
1544: for ($i=0;$i<=$#ids;$i++) {
1545: if ($answer[$i]) {
1546: $returnhash{$ids[$i]}=$answer[$i];
1547: }
1548: }
1549: }
1.70 www 1550: return %returnhash;
1551: }
1552:
1553: # ------------------------------------- Find the IDs behind a list of usernames
1554:
1555: sub idrget {
1556: my ($udom,@unames)=@_;
1557: my %returnhash=();
1.800 albertel 1558: foreach my $uname (@unames) {
1559: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1560: }
1.70 www 1561: return %returnhash;
1562: }
1563:
1564: # ------------------------------- Store away a list of names and associated IDs
1565:
1566: sub idput {
1567: my ($udom,%ids)=@_;
1568: my %servers=();
1.800 albertel 1569: foreach my $uname (keys(%ids)) {
1570: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1571: my $uhom=&homeserver($uname,$udom);
1.70 www 1572: if ($uhom ne 'no_host') {
1.800 albertel 1573: my $id=&escape($ids{$uname});
1.70 www 1574: $id=~tr/A-Z/a-z/;
1.800 albertel 1575: my $esc_unam=&escape($uname);
1.70 www 1576: if ($servers{$uhom}) {
1.800 albertel 1577: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1578: } else {
1.800 albertel 1579: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1580: }
1581: }
1.191 harris41 1582: }
1.800 albertel 1583: foreach my $server (keys(%servers)) {
1584: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1585: }
1.344 www 1586: }
1587:
1.1172.2.30 raeburn 1588: # ---------------------------------------- Delete unwanted IDs from ids.db file
1589:
1590: sub iddel {
1591: my ($udom,$idshashref,$uhome)=@_;
1592: my %result=();
1593: unless (ref($idshashref) eq 'HASH') {
1594: return %result;
1595: }
1596: my %servers=();
1597: while (my ($id,$uname) = each(%{$idshashref})) {
1598: my $uhom;
1599: if ($uhome) {
1600: $uhom = $uhome;
1601: } else {
1602: $uhom=&homeserver($uname,$udom);
1603: }
1604: if ($uhom ne 'no_host') {
1605: if ($servers{$uhom}) {
1606: $servers{$uhom}.='&'.&escape($id);
1607: } else {
1608: $servers{$uhom}=&escape($id);
1609: }
1610: }
1611: }
1612: foreach my $server (keys(%servers)) {
1613: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1614: }
1615: return %result;
1616: }
1617:
1.1023 raeburn 1618: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1619: sub dump_dom {
1.1165 droeschl 1620: my ($namespace, $udom, $regexp) = @_;
1621:
1622: $udom ||= $env{'user.domain'};
1623:
1624: return () unless $udom;
1625:
1626: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1627: }
1628:
1.1023 raeburn 1629: # ------------------------------------------ get items from domain db files
1.806 raeburn 1630:
1631: sub get_dom {
1.860 raeburn 1632: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1633: my $items='';
1634: foreach my $item (@$storearr) {
1635: $items.=&escape($item).'&';
1636: }
1637: $items=~s/\&$//;
1.860 raeburn 1638: if (!$udom) {
1639: $udom=$env{'user.domain'};
1640: if (defined(&domain($udom,'primary'))) {
1641: $uhome=&domain($udom,'primary');
1642: } else {
1.874 albertel 1643: undef($uhome);
1.860 raeburn 1644: }
1645: } else {
1646: if (!$uhome) {
1647: if (defined(&domain($udom,'primary'))) {
1648: $uhome=&domain($udom,'primary');
1649: }
1650: }
1651: }
1652: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1653: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1654: my %returnhash;
1.875 albertel 1655: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1656: return %returnhash;
1657: }
1.806 raeburn 1658: my @pairs=split(/\&/,$rep);
1659: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1660: return @pairs;
1661: }
1662: my $i=0;
1663: foreach my $item (@$storearr) {
1664: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1665: $i++;
1666: }
1667: return %returnhash;
1668: } else {
1.880 banghart 1669: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1670: }
1671: }
1672:
1673: # -------------------------------------------- put items in domain db files
1674:
1675: sub put_dom {
1.860 raeburn 1676: my ($namespace,$storehash,$udom,$uhome)=@_;
1677: if (!$udom) {
1678: $udom=$env{'user.domain'};
1679: if (defined(&domain($udom,'primary'))) {
1680: $uhome=&domain($udom,'primary');
1681: } else {
1.874 albertel 1682: undef($uhome);
1.860 raeburn 1683: }
1684: } else {
1685: if (!$uhome) {
1686: if (defined(&domain($udom,'primary'))) {
1687: $uhome=&domain($udom,'primary');
1688: }
1689: }
1690: }
1691: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1692: my $items='';
1693: foreach my $item (keys(%$storehash)) {
1694: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1695: }
1696: $items=~s/\&$//;
1697: return &reply("putdom:$udom:$namespace:$items",$uhome);
1698: } else {
1.860 raeburn 1699: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1700: }
1701: }
1702:
1.1023 raeburn 1703: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1704: sub newput_dom {
1.1023 raeburn 1705: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1706: my $result;
1707: if (!$udom) {
1708: $udom=$env{'user.domain'};
1709: }
1.1023 raeburn 1710: if ($udom) {
1711: my $uname = &get_domainconfiguser($udom);
1712: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1713: }
1714: return $result;
1715: }
1716:
1.1023 raeburn 1717: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1718: sub del_dom {
1.1023 raeburn 1719: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1720: if (ref($storearr) eq 'ARRAY') {
1721: if (!$udom) {
1722: $udom=$env{'user.domain'};
1723: }
1.1023 raeburn 1724: if ($udom) {
1725: my $uname = &get_domainconfiguser($udom);
1726: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1727: }
1728: }
1729: }
1730:
1.1023 raeburn 1731: # ----------------------------------construct domainconfig user for a domain
1732: sub get_domainconfiguser {
1733: my ($udom) = @_;
1734: return $udom.'-domainconfig';
1735: }
1736:
1.837 raeburn 1737: sub retrieve_inst_usertypes {
1738: my ($udom) = @_;
1739: my (%returnhash,@order);
1.989 raeburn 1740: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1741: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1742: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1743: %returnhash = %{$domdefs{'inststatustypes'}};
1744: @order = @{$domdefs{'inststatusorder'}};
1745: } else {
1746: if (defined(&domain($udom,'primary'))) {
1747: my $uhome=&domain($udom,'primary');
1748: my $rep=&reply("inst_usertypes:$udom",$uhome);
1749: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1750: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1751: return (\%returnhash,\@order);
1752: }
1753: my ($hashitems,$orderitems) = split(/:/,$rep);
1754: my @pairs=split(/\&/,$hashitems);
1755: foreach my $item (@pairs) {
1756: my ($key,$value)=split(/=/,$item,2);
1757: $key = &unescape($key);
1758: next if ($key =~ /^error: 2 /);
1759: $returnhash{$key}=&thaw_unescape($value);
1760: }
1761: my @esc_order = split(/\&/,$orderitems);
1762: foreach my $item (@esc_order) {
1763: push(@order,&unescape($item));
1764: }
1765: } else {
1766: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1767: }
1768: }
1769: return (\%returnhash,\@order);
1770: }
1771:
1.868 raeburn 1772: sub is_domainimage {
1773: my ($url) = @_;
1774: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1775: if (&domain($1) ne '') {
1776: return '1';
1777: }
1778: }
1779: return;
1780: }
1781:
1.899 raeburn 1782: sub inst_directory_query {
1783: my ($srch) = @_;
1784: my $udom = $srch->{'srchdomain'};
1785: my %results;
1786: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1787: my $outcome;
1.899 raeburn 1788: if ($homeserver ne '') {
1.904 albertel 1789: my $queryid=&reply("querysend:instdirsearch:".
1790: &escape($srch->{'srchby'}).':'.
1791: &escape($srch->{'srchterm'}).':'.
1792: &escape($srch->{'srchtype'}),$homeserver);
1793: my $host=&hostname($homeserver);
1794: if ($queryid !~/^\Q$host\E\_/) {
1795: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1796: return;
1797: }
1798: my $response = &get_query_reply($queryid);
1799: my $maxtries = 5;
1800: my $tries = 1;
1801: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1802: $response = &get_query_reply($queryid);
1803: $tries ++;
1804: }
1805:
1806: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1807: if ($response eq 'unavailable') {
1808: $outcome = $response;
1809: } else {
1810: $outcome = 'ok';
1811: my @matches = split(/\n/,$response);
1812: foreach my $match (@matches) {
1813: my ($key,$value) = split(/=/,$match);
1814: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1815: }
1.899 raeburn 1816: }
1817: }
1818: }
1.909 raeburn 1819: return ($outcome,%results);
1.899 raeburn 1820: }
1821:
1822: sub usersearch {
1823: my ($srch) = @_;
1824: my $dom = $srch->{'srchdomain'};
1825: my %results;
1826: my %libserv = &all_library();
1827: my $query = 'usersearch';
1828: foreach my $tryserver (keys(%libserv)) {
1829: if (&host_domain($tryserver) eq $dom) {
1830: my $host=&hostname($tryserver);
1831: my $queryid=
1.911 raeburn 1832: &reply("querysend:".&escape($query).':'.
1833: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1834: &escape($srch->{'srchtype'}).':'.
1835: &escape($srch->{'srchterm'}),$tryserver);
1836: if ($queryid !~/^\Q$host\E\_/) {
1837: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1838: next;
1.899 raeburn 1839: }
1840: my $reply = &get_query_reply($queryid);
1841: my $maxtries = 1;
1842: my $tries = 1;
1843: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1844: $reply = &get_query_reply($queryid);
1845: $tries ++;
1846: }
1847: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1848: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1849: } else {
1.911 raeburn 1850: my @matches;
1851: if ($reply =~ /\n/) {
1852: @matches = split(/\n/,$reply);
1853: } else {
1854: @matches = split(/\&/,$reply);
1855: }
1.899 raeburn 1856: foreach my $match (@matches) {
1857: my ($uname,$udom,%userhash);
1.911 raeburn 1858: foreach my $entry (split(/:/,$match)) {
1859: my ($key,$value) =
1860: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1861: $userhash{$key} = $value;
1862: if ($key eq 'username') {
1863: $uname = $value;
1864: } elsif ($key eq 'domain') {
1865: $udom = $value;
1.911 raeburn 1866: }
1.899 raeburn 1867: }
1868: $results{$uname.':'.$udom} = \%userhash;
1869: }
1870: }
1871: }
1872: }
1873: return %results;
1874: }
1875:
1.912 raeburn 1876: sub get_instuser {
1877: my ($udom,$uname,$id) = @_;
1878: my $homeserver = &domain($udom,'primary');
1879: my ($outcome,%results);
1880: if ($homeserver ne '') {
1881: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1882: &escape($id).':'.&escape($udom),$homeserver);
1883: my $host=&hostname($homeserver);
1884: if ($queryid !~/^\Q$host\E\_/) {
1885: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1886: return;
1887: }
1888: my $response = &get_query_reply($queryid);
1889: my $maxtries = 5;
1890: my $tries = 1;
1891: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1892: $response = &get_query_reply($queryid);
1893: $tries ++;
1894: }
1895: if (!&error($response) && $response ne 'refused') {
1896: if ($response eq 'unavailable') {
1897: $outcome = $response;
1898: } else {
1899: $outcome = 'ok';
1900: my @matches = split(/\n/,$response);
1901: foreach my $match (@matches) {
1902: my ($key,$value) = split(/=/,$match);
1903: $results{&unescape($key)} = &thaw_unescape($value);
1904: }
1905: }
1906: }
1907: }
1908: my %userinfo;
1909: if (ref($results{$uname}) eq 'HASH') {
1910: %userinfo = %{$results{$uname}};
1911: }
1912: return ($outcome,%userinfo);
1913: }
1914:
1915: sub inst_rulecheck {
1.923 raeburn 1916: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1917: my %returnhash;
1918: if ($udom ne '') {
1919: if (ref($rules) eq 'ARRAY') {
1920: @{$rules} = map {&escape($_);} (@{$rules});
1921: my $rulestr = join(':',@{$rules});
1922: my $homeserver=&domain($udom,'primary');
1923: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1924: my $response;
1925: if ($item eq 'username') {
1926: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1927: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1928: $homeserver));
1.923 raeburn 1929: } elsif ($item eq 'id') {
1930: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1931: ':'.&escape($id).':'.$rulestr,
1932: $homeserver));
1.945 raeburn 1933: } elsif ($item eq 'selfcreate') {
1934: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1935: &escape($udom).':'.&escape($uname).
1936: ':'.$rulestr,$homeserver));
1.923 raeburn 1937: }
1.912 raeburn 1938: if ($response ne 'refused') {
1939: my @pairs=split(/\&/,$response);
1940: foreach my $item (@pairs) {
1941: my ($key,$value)=split(/=/,$item,2);
1942: $key = &unescape($key);
1943: next if ($key =~ /^error: 2 /);
1944: $returnhash{$key}=&thaw_unescape($value);
1945: }
1946: }
1947: }
1948: }
1949: }
1950: return %returnhash;
1951: }
1952:
1953: sub inst_userrules {
1.923 raeburn 1954: my ($udom,$check) = @_;
1.912 raeburn 1955: my (%ruleshash,@ruleorder);
1956: if ($udom ne '') {
1957: my $homeserver=&domain($udom,'primary');
1958: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1959: my $response;
1960: if ($check eq 'id') {
1961: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1962: $homeserver);
1.943 raeburn 1963: } elsif ($check eq 'email') {
1964: $response=&reply('instemailrules:'.&escape($udom),
1965: $homeserver);
1.923 raeburn 1966: } else {
1967: $response=&reply('instuserrules:'.&escape($udom),
1968: $homeserver);
1969: }
1.912 raeburn 1970: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1971: ($response ne 'unknown_cmd') &&
1.912 raeburn 1972: ($response ne 'no_such_host')) {
1973: my ($hashitems,$orderitems) = split(/:/,$response);
1974: my @pairs=split(/\&/,$hashitems);
1975: foreach my $item (@pairs) {
1976: my ($key,$value)=split(/=/,$item,2);
1977: $key = &unescape($key);
1978: next if ($key =~ /^error: 2 /);
1979: $ruleshash{$key}=&thaw_unescape($value);
1980: }
1981: my @esc_order = split(/\&/,$orderitems);
1982: foreach my $item (@esc_order) {
1983: push(@ruleorder,&unescape($item));
1984: }
1985: }
1986: }
1987: }
1988: return (\%ruleshash,\@ruleorder);
1989: }
1990:
1.976 raeburn 1991: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1992:
1993: sub get_domain_defaults {
1.1172.2.35 raeburn 1994: my ($domain,$ignore_cache) = @_;
1995: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1996: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 1997: unless ($ignore_cache) {
1998: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1999: if (defined($cached)) {
2000: if (ref($result) eq 'HASH') {
2001: return %{$result};
2002: }
1.943 raeburn 2003: }
2004: }
2005: my %domdefaults;
2006: my %domconfig =
1.989 raeburn 2007: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2008: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2009: 'coursedefaults','usersessions',
2010: 'requestauthor'],$domain);
1.1172.2.41! raeburn 2011: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2012: if (ref($domconfig{'defaults'}) eq 'HASH') {
2013: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2014: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2015: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2016: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2017: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2018: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2019: } else {
2020: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2021: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2022: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2023: }
1.976 raeburn 2024: if (ref($domconfig{'quotas'}) eq 'HASH') {
2025: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2026: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2027: } else {
2028: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2029: }
1.1172.2.6 raeburn 2030: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2031: foreach my $item (@usertools) {
2032: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2033: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2034: }
2035: }
1.1172.2.29 raeburn 2036: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2037: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2038: }
1.976 raeburn 2039: }
1.985 raeburn 2040: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2041: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2042: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2043: }
2044: }
1.1172.2.9 raeburn 2045: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2046: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2047: }
1.989 raeburn 2048: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2049: foreach my $item ('inststatustypes','inststatusorder') {
2050: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2051: }
2052: }
1.1047 raeburn 2053: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41! raeburn 2054: foreach my $type (@coursetypes) {
! 2055: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
! 2056: unless ($type eq 'community') {
! 2057: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
! 2058: }
! 2059: }
! 2060: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
! 2061: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
! 2062: }
1.1172.2.30 raeburn 2063: }
1.1047 raeburn 2064: }
1.1073 raeburn 2065: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2066: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2067: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2068: }
2069: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2070: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2071: }
2072: }
1.1172.2.41! raeburn 2073: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
! 2074: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
! 2075: my @settings = ('types','registered','enroll_dates','access_dates','section',
! 2076: 'approval','limit');
! 2077: foreach my $type (@coursetypes) {
! 2078: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
! 2079: my @mgrdc = ();
! 2080: foreach my $item (@settings) {
! 2081: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
! 2082: push(@mgrdc,$item);
! 2083: }
! 2084: }
! 2085: if (@mgrdc) {
! 2086: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
! 2087: }
! 2088: }
! 2089: }
! 2090: }
! 2091: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
! 2092: foreach my $type (@coursetypes) {
! 2093: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
! 2094: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
! 2095: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
! 2096: }
! 2097: }
! 2098: }
! 2099: }
! 2100: }
1.1172.2.23 raeburn 2101: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2102: return %domdefaults;
2103: }
2104:
1.344 www 2105: # --------------------------------------------------- Assign a key to a student
2106:
2107: sub assign_access_key {
1.364 www 2108: #
2109: # a valid key looks like uname:udom#comments
2110: # comments are being appended
2111: #
1.498 www 2112: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2113: $kdom=
1.620 albertel 2114: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2115: $knum=
1.620 albertel 2116: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2117: $cdom=
1.620 albertel 2118: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2119: $cnum=
1.620 albertel 2120: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2121: $udom=$env{'user.name'} unless (defined($udom));
2122: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2123: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2124: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2125: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2126: # assigned to this person
2127: # - this should not happen,
1.345 www 2128: # unless something went wrong
2129: # the first time around
2130: # ready to assign
1.364 www 2131: $logentry=$1.'; '.$logentry;
1.496 www 2132: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2133: $kdom,$knum) eq 'ok') {
1.345 www 2134: # key now belongs to user
1.346 www 2135: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2136: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2137: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2138: return 'ok';
2139: } else {
2140: return
2141: 'error: Count not permanently assign key, will need to be re-entered later.';
2142: }
2143: } else {
2144: return 'error: Could not assign key, try again later.';
2145: }
1.364 www 2146: } elsif (!$existing{$ckey}) {
1.345 www 2147: # the key does not exist
2148: return 'error: The key does not exist';
2149: } else {
2150: # the key is somebody else's
2151: return 'error: The key is already in use';
2152: }
1.344 www 2153: }
2154:
1.364 www 2155: # ------------------------------------------ put an additional comment on a key
2156:
2157: sub comment_access_key {
2158: #
2159: # a valid key looks like uname:udom#comments
2160: # comments are being appended
2161: #
2162: my ($ckey,$cdom,$cnum,$logentry)=@_;
2163: $cdom=
1.620 albertel 2164: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2165: $cnum=
1.620 albertel 2166: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2167: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2168: if ($existing{$ckey}) {
2169: $existing{$ckey}.='; '.$logentry;
2170: # ready to assign
1.367 www 2171: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2172: $cdom,$cnum) eq 'ok') {
2173: return 'ok';
2174: } else {
2175: return 'error: Count not store comment.';
2176: }
2177: } else {
2178: # the key does not exist
2179: return 'error: The key does not exist';
2180: }
2181: }
2182:
1.344 www 2183: # ------------------------------------------------------ Generate a set of keys
2184:
2185: sub generate_access_keys {
1.364 www 2186: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2187: $cdom=
1.620 albertel 2188: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2189: $cnum=
1.620 albertel 2190: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2191: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2192: unless (($cdom) && ($cnum)) { return 0; }
2193: if ($number>10000) { return 0; }
2194: sleep(2); # make sure don't get same seed twice
2195: srand(time()^($$+($$<<15))); # from "Programming Perl"
2196: my $total=0;
2197: for (my $i=1;$i<=$number;$i++) {
2198: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2199: sprintf("%lx",int(100000*rand)).'-'.
2200: sprintf("%lx",int(100000*rand));
2201: $newkey=~s/1/g/g; # folks mix up 1 and l
2202: $newkey=~s/0/h/g; # and also 0 and O
2203: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2204: if ($existing{$newkey}) {
2205: $i--;
2206: } else {
1.364 www 2207: if (&put('accesskeys',
2208: { $newkey => '# generated '.localtime().
1.620 albertel 2209: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2210: '; '.$logentry },
2211: $cdom,$cnum) eq 'ok') {
1.344 www 2212: $total++;
2213: }
2214: }
2215: }
1.620 albertel 2216: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2217: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2218: return $total;
2219: }
2220:
2221: # ------------------------------------------------------- Validate an accesskey
2222:
2223: sub validate_access_key {
2224: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2225: $cdom=
1.620 albertel 2226: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2227: $cnum=
1.620 albertel 2228: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2229: $udom=$env{'user.domain'} unless (defined($udom));
2230: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2231: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2232: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2233: }
2234:
2235: # ------------------------------------- Find the section of student in a course
1.652 albertel 2236: sub devalidate_getsection_cache {
2237: my ($udom,$unam,$courseid)=@_;
2238: my $hashid="$udom:$unam:$courseid";
2239: &devalidate_cache_new('getsection',$hashid);
2240: }
1.298 matthew 2241:
1.815 albertel 2242: sub courseid_to_courseurl {
2243: my ($courseid) = @_;
2244: #already url style courseid
2245: return $courseid if ($courseid =~ m{^/});
2246:
2247: if (exists($env{'course.'.$courseid.'.num'})) {
2248: my $cnum = $env{'course.'.$courseid.'.num'};
2249: my $cdom = $env{'course.'.$courseid.'.domain'};
2250: return "/$cdom/$cnum";
2251: }
2252:
2253: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2254: if (exists($courseinfo{'num'})) {
2255: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2256: }
2257:
2258: return undef;
2259: }
2260:
1.298 matthew 2261: sub getsection {
2262: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2263: my $cachetime=1800;
1.551 albertel 2264:
2265: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2266: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2267: if (defined($cached)) { return $result; }
2268:
1.298 matthew 2269: my %Pending;
2270: my %Expired;
2271: #
2272: # Each role can either have not started yet (pending), be active,
2273: # or have expired.
2274: #
2275: # If there is an active role, we are done.
2276: #
2277: # If there is more than one role which has not started yet,
2278: # choose the one which will start sooner
2279: # If there is one role which has not started yet, return it.
2280: #
2281: # If there is more than one expired role, choose the one which ended last.
2282: # If there is a role which has expired, return it.
2283: #
1.815 albertel 2284: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2285: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2286: foreach my $key (keys(%roleshash)) {
1.479 albertel 2287: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2288: my $section=$1;
2289: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2290: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2291: my $now=time;
1.548 albertel 2292: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2293: $Expired{$end}=$section;
2294: next;
2295: }
1.548 albertel 2296: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2297: $Pending{$start}=$section;
2298: next;
2299: }
1.599 albertel 2300: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2301: }
2302: #
2303: # Presumedly there will be few matching roles from the above
2304: # loop and the sorting time will be negligible.
2305: if (scalar(keys(%Pending))) {
2306: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2307: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2308: }
2309: if (scalar(keys(%Expired))) {
2310: my @sorted = sort {$a <=> $b} keys(%Expired);
2311: my $time = pop(@sorted);
1.599 albertel 2312: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2313: }
1.599 albertel 2314: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2315: }
1.70 www 2316:
1.599 albertel 2317: sub save_cache {
2318: &purge_remembered();
1.722 albertel 2319: #&Apache::loncommon::validate_page();
1.620 albertel 2320: undef(%env);
1.780 albertel 2321: undef($env_loaded);
1.599 albertel 2322: }
1.452 albertel 2323:
1.599 albertel 2324: my $to_remember=-1;
2325: my %remembered;
2326: my %accessed;
2327: my $kicks=0;
2328: my $hits=0;
1.849 albertel 2329: sub make_key {
2330: my ($name,$id) = @_;
1.872 albertel 2331: if (length($id) > 65
2332: && length(&escape($id)) > 200) {
2333: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2334: }
1.849 albertel 2335: return &escape($name.':'.$id);
2336: }
2337:
1.599 albertel 2338: sub devalidate_cache_new {
2339: my ($name,$id,$debug) = @_;
2340: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2341: $id=&make_key($name,$id);
1.599 albertel 2342: $memcache->delete($id);
2343: delete($remembered{$id});
2344: delete($accessed{$id});
2345: }
2346:
2347: sub is_cached_new {
2348: my ($name,$id,$debug) = @_;
1.849 albertel 2349: $id=&make_key($name,$id);
1.599 albertel 2350: if (exists($remembered{$id})) {
1.1133 foxr 2351: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2352: $accessed{$id}=[&gettimeofday()];
2353: $hits++;
2354: return ($remembered{$id},1);
2355: }
2356: my $value = $memcache->get($id);
2357: if (!(defined($value))) {
2358: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2359: return (undef,undef);
1.416 albertel 2360: }
1.599 albertel 2361: if ($value eq '__undef__') {
2362: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2363: $value=undef;
2364: }
2365: &make_room($id,$value,$debug);
2366: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2367: return ($value,1);
2368: }
2369:
2370: sub do_cache_new {
2371: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2372: $id=&make_key($name,$id);
1.599 albertel 2373: my $setvalue=$value;
2374: if (!defined($setvalue)) {
2375: $setvalue='__undef__';
2376: }
1.623 albertel 2377: if (!defined($time) ) {
2378: $time=600;
2379: }
1.599 albertel 2380: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2381: my $result = $memcache->set($id,$setvalue,$time);
2382: if (! $result) {
1.872 albertel 2383: &logthis("caching of id -> $id failed");
1.910 albertel 2384: $memcache->disconnect_all();
1.872 albertel 2385: }
1.600 albertel 2386: # need to make a copy of $value
1.919 albertel 2387: &make_room($id,$value,$debug);
1.599 albertel 2388: return $value;
2389: }
2390:
2391: sub make_room {
2392: my ($id,$value,$debug)=@_;
1.919 albertel 2393:
2394: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2395: : $value;
1.599 albertel 2396: if ($to_remember<0) { return; }
2397: $accessed{$id}=[&gettimeofday()];
2398: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2399: my $to_kick;
2400: my $max_time=0;
2401: foreach my $other (keys(%accessed)) {
2402: if (&tv_interval($accessed{$other}) > $max_time) {
2403: $to_kick=$other;
2404: $max_time=&tv_interval($accessed{$other});
2405: }
2406: }
2407: delete($remembered{$to_kick});
2408: delete($accessed{$to_kick});
2409: $kicks++;
2410: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2411: return;
2412: }
2413:
1.599 albertel 2414: sub purge_remembered {
1.604 albertel 2415: #&logthis("Tossing ".scalar(keys(%remembered)));
2416: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2417: undef(%remembered);
2418: undef(%accessed);
1.428 albertel 2419: }
1.70 www 2420: # ------------------------------------- Read an entry from a user's environment
2421:
2422: sub userenvironment {
2423: my ($udom,$unam,@what)=@_;
1.976 raeburn 2424: my $items;
2425: foreach my $item (@what) {
2426: $items.=&escape($item).'&';
2427: }
2428: $items=~s/\&$//;
1.70 www 2429: my %returnhash=();
1.1009 raeburn 2430: my $uhome = &homeserver($unam,$udom);
2431: unless ($uhome eq 'no_host') {
2432: my @answer=split(/\&/,
2433: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2434: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2435: return %returnhash;
2436: }
1.1009 raeburn 2437: my $i;
2438: for ($i=0;$i<=$#what;$i++) {
2439: $returnhash{$what[$i]}=&unescape($answer[$i]);
2440: }
1.70 www 2441: }
2442: return %returnhash;
1.1 albertel 2443: }
2444:
1.617 albertel 2445: # ---------------------------------------------------------- Get a studentphoto
2446: sub studentphoto {
2447: my ($udom,$unam,$ext) = @_;
2448: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2449: if (defined($env{'request.course.id'})) {
1.708 raeburn 2450: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2451: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2452: return(&retrievestudentphoto($udom,$unam,$ext));
2453: } else {
2454: my ($result,$perm_reqd)=
1.707 albertel 2455: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2456: if ($result eq 'ok') {
2457: if (!($perm_reqd eq 'yes')) {
2458: return(&retrievestudentphoto($udom,$unam,$ext));
2459: }
2460: }
2461: }
2462: }
2463: } else {
2464: my ($result,$perm_reqd) =
1.707 albertel 2465: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2466: if ($result eq 'ok') {
2467: if (!($perm_reqd eq 'yes')) {
2468: return(&retrievestudentphoto($udom,$unam,$ext));
2469: }
2470: }
2471: }
2472: return '/adm/lonKaputt/lonlogo_broken.gif';
2473: }
2474:
2475: sub retrievestudentphoto {
2476: my ($udom,$unam,$ext,$type) = @_;
2477: my $home=&Apache::lonnet::homeserver($unam,$udom);
2478: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2479: if ($ret eq 'ok') {
2480: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2481: if ($type eq 'thumbnail') {
2482: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2483: }
2484: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2485: return $tokenurl;
2486: } else {
2487: if ($type eq 'thumbnail') {
2488: return '/adm/lonKaputt/genericstudent_tn.gif';
2489: } else {
2490: return '/adm/lonKaputt/lonlogo_broken.gif';
2491: }
1.617 albertel 2492: }
2493: }
2494:
1.263 www 2495: # -------------------------------------------------------------------- New chat
2496:
2497: sub chatsend {
1.724 raeburn 2498: my ($newentry,$anon,$group)=@_;
1.620 albertel 2499: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2500: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2501: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2502: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2503: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2504: &escape($newentry)).':'.$group,$chome);
1.292 www 2505: }
2506:
2507: # ------------------------------------------ Find current version of a resource
2508:
2509: sub getversion {
2510: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2511: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2512: return ¤tversion(&filelocation('',$fname));
2513: }
2514:
2515: sub currentversion {
2516: my $fname=shift;
2517: my $author=$fname;
2518: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2519: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2520: my $home=&homeserver($uname,$udom);
1.292 www 2521: if ($home eq 'no_host') {
2522: return -1;
2523: }
1.1112 www 2524: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2525: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2526: return -1;
2527: }
1.1112 www 2528: return $answer;
1.263 www 2529: }
2530:
1.1111 www 2531: #
2532: # Return special version number of resource if set by override, empty otherwise
2533: #
2534: sub usedversion {
2535: my $fname=shift;
2536: unless ($fname) { $fname=$env{'request.uri'}; }
2537: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2538: if ($urlversion) { return $urlversion; }
2539: return '';
2540: }
2541:
1.1 albertel 2542: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2543:
1.1 albertel 2544: sub subscribe {
2545: my $fname=shift;
1.761 raeburn 2546: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2547: $fname=~s/[\n\r]//g;
1.1 albertel 2548: my $author=$fname;
2549: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2550: my ($udom,$uname)=split(/\//,$author);
2551: my $home=homeserver($uname,$udom);
1.335 albertel 2552: if ($home eq 'no_host') {
2553: return 'not_found';
1.1 albertel 2554: }
2555: my $answer=reply("sub:$fname",$home);
1.64 www 2556: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2557: $answer.=' by '.$home;
2558: }
1.1 albertel 2559: return $answer;
2560: }
2561:
1.8 www 2562: # -------------------------------------------------------------- Replicate file
2563:
2564: sub repcopy {
2565: my $filename=shift;
1.23 www 2566: $filename=~s/\/+/\//g;
1.1142 raeburn 2567: my $londocroot = $perlvar{'lonDocRoot'};
2568: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2569: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2570: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2571: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2572: return &repcopy_userfile($filename);
2573: }
1.532 albertel 2574: $filename=~s/[\n\r]//g;
1.8 www 2575: my $transname="$filename.in.transfer";
1.828 www 2576: # FIXME: this should flock
1.607 raeburn 2577: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2578: my $remoteurl=subscribe($filename);
1.64 www 2579: if ($remoteurl =~ /^con_lost by/) {
2580: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2581: return 'unavailable';
1.8 www 2582: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2583: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2584: return 'not_found';
1.64 www 2585: } elsif ($remoteurl =~ /^rejected by/) {
2586: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2587: return 'forbidden';
1.20 www 2588: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2589: return 'ok';
1.8 www 2590: } else {
1.290 www 2591: my $author=$filename;
2592: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2593: my ($udom,$uname)=split(/\//,$author);
2594: my $home=homeserver($uname,$udom);
2595: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2596: my @parts=split(/\//,$filename);
2597: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2598: if ($path ne "$londocroot/res") {
1.8 www 2599: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2600: return 'bad_request';
1.8 www 2601: }
2602: my $count;
2603: for ($count=5;$count<$#parts;$count++) {
2604: $path.="/$parts[$count]";
2605: if ((-e $path)!=1) {
2606: mkdir($path,0777);
2607: }
2608: }
2609: my $ua=new LWP::UserAgent;
2610: my $request=new HTTP::Request('GET',"$remoteurl");
2611: my $response=$ua->request($request,$transname);
2612: if ($response->is_error()) {
2613: unlink($transname);
2614: my $message=$response->status_line;
1.672 albertel 2615: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2616: ." LWP get: $message: $filename</font>");
1.607 raeburn 2617: return 'unavailable';
1.8 www 2618: } else {
1.16 www 2619: if ($remoteurl!~/\.meta$/) {
2620: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2621: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2622: if ($mresponse->is_error()) {
2623: unlink($filename.'.meta');
2624: &logthis(
1.672 albertel 2625: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2626: }
2627: }
1.8 www 2628: rename($transname,$filename);
1.607 raeburn 2629: return 'ok';
1.8 www 2630: }
1.290 www 2631: }
1.8 www 2632: }
1.330 www 2633: }
2634:
2635: # ------------------------------------------------ Get server side include body
2636: sub ssi_body {
1.381 albertel 2637: my ($filelink,%form)=@_;
1.606 matthew 2638: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2639: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2640: }
1.953 www 2641: my $output='';
2642: my $response;
1.980 raeburn 2643: if ($filelink=~/^https?\:/) {
1.954 raeburn 2644: ($output,$response)=&externalssi($filelink);
1.953 www 2645: } else {
1.1004 droeschl 2646: $filelink .= $filelink=~/\?/ ? '&' : '?';
2647: $filelink .= 'inhibitmenu=yes';
1.953 www 2648: ($output,$response)=&ssi($filelink,%form);
2649: }
1.778 albertel 2650: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2651: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2652: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2653: if (wantarray) {
2654: return ($output, $response);
2655: } else {
2656: return $output;
2657: }
1.8 www 2658: }
2659:
1.15 www 2660: # --------------------------------------------------------- Server Side Include
2661:
1.782 albertel 2662: sub absolute_url {
2663: my ($host_name) = @_;
2664: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2665: if ($host_name eq '') {
2666: $host_name = $ENV{'SERVER_NAME'};
2667: }
2668: return $protocol.$host_name;
2669: }
2670:
1.942 foxr 2671: #
2672: # Server side include.
2673: # Parameters:
2674: # fn Possibly encrypted resource name/id.
2675: # form Hash that describes how the rendering should be done
2676: # and other things.
1.944 foxr 2677: # Returns:
1.950 raeburn 2678: # Scalar context: The content of the response.
2679: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2680: #
1.15 www 2681: sub ssi {
2682:
1.944 foxr 2683: my ($fn,%form)=@_;
1.15 www 2684: my $ua=new LWP::UserAgent;
1.23 www 2685: my $request;
1.711 albertel 2686:
2687: $form{'no_update_last_known'}=1;
1.895 albertel 2688: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2689: if (%form) {
1.782 albertel 2690: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2691: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2692: } else {
1.782 albertel 2693: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2694: }
2695:
1.15 www 2696: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2697: my $response= $ua->request($request);
1.944 foxr 2698: if (wantarray) {
1.1172.2.3 raeburn 2699: return ($response->content, $response);
1.944 foxr 2700: } else {
1.1172.2.3 raeburn 2701: return $response->content;
1.942 foxr 2702: }
1.324 www 2703: }
2704:
2705: sub externalssi {
2706: my ($url)=@_;
2707: my $ua=new LWP::UserAgent;
2708: my $request=new HTTP::Request('GET',$url);
2709: my $response=$ua->request($request);
1.954 raeburn 2710: if (wantarray) {
2711: return ($response->content, $response);
2712: } else {
2713: return $response->content;
2714: }
1.15 www 2715: }
1.254 www 2716:
1.492 albertel 2717: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2718:
2719: sub allowuploaded {
2720: my ($srcurl,$url)=@_;
2721: $url=&clutter(&declutter($url));
2722: my $dir=$url;
2723: $dir=~s/\/[^\/]+$//;
2724: my %httpref=();
2725: my $httpurl=&hreflocation('',$url);
2726: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2727: &Apache::lonnet::appenv(\%httpref);
1.254 www 2728: }
1.477 raeburn 2729:
1.1172.2.13 raeburn 2730: #
2731: # Determine if the current user should be able to edit a particular resource,
2732: # when viewing in course context.
2733: # (a) When viewing resource used to determine if "Edit" item is included in
2734: # Functions.
2735: # (b) When displaying folder contents in course editor, used to determine if
2736: # "Edit" link will be displayed alongside resource.
2737: #
2738: # input: six args -- filename (decluttered), course number, course domain,
2739: # url, symb (if registered) and group (if this is a group
2740: # item -- e.g., bulletin board, group page etc.).
2741: # output: array of five scalars --
2742: # $cfile -- url for file editing if editable on current server
2743: # $home -- homeserver of resource (i.e., for author if published,
2744: # or course if uploaded.).
2745: # $switchserver -- 1 if server switch will be needed.
2746: # $forceedit -- 1 if icon/link should be to go to edit mode
2747: # $forceview -- 1 if icon/link should be to go to view mode
2748: #
2749:
2750: sub can_edit_resource {
2751: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2752: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2753: #
2754: # For aboutme pages user can only edit his/her own.
2755: #
2756: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2757: my ($sdom,$sname) = ($1,$2);
2758: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2759: $home = $env{'user.home'};
2760: $cfile = $resurl;
2761: if ($env{'form.forceedit'}) {
2762: $forceview = 1;
2763: } else {
2764: $forceedit = 1;
2765: }
2766: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2767: } else {
2768: return;
2769: }
2770: }
2771:
2772: if ($env{'request.course.id'}) {
2773: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2774: if ($group ne '') {
2775: # if this is a group homepage or group bulletin board, check group privs
2776: my $allowed = 0;
2777: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2778: if ((&allowed('mdg',$env{'request.course.id'}.
2779: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2780: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2781: $allowed = 1;
2782: }
2783: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2784: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2785: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2786: $allowed = 1;
2787: }
2788: }
2789: if ($allowed) {
2790: $home=&homeserver($cnum,$cdom);
2791: if ($env{'form.forceedit'}) {
2792: $forceview = 1;
2793: } else {
2794: $forceedit = 1;
2795: }
2796: $cfile = $resurl;
2797: } else {
2798: return;
2799: }
2800: } else {
1.1172.2.15 raeburn 2801: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2802: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2803: return;
2804: }
2805: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2806: #
2807: # No edit allowed where CC has switched to student role.
2808: #
2809: return;
2810: }
2811: }
2812: }
2813:
2814: if ($file ne '') {
2815: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2816: if (&is_course_upload($file,$cnum,$cdom)) {
2817: $uploaded = 1;
2818: $incourse = 1;
2819: if ($file =~/\.(htm|html|css|js|txt)$/) {
2820: $cfile = &hreflocation('',$file);
2821: if ($env{'form.forceedit'}) {
2822: $forceview = 1;
2823: } else {
2824: $forceedit = 1;
2825: }
2826: }
2827: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2828: $incourse = 1;
2829: if ($env{'form.forceedit'}) {
2830: $forceview = 1;
2831: } else {
2832: $forceedit = 1;
2833: }
2834: $cfile = $resurl;
2835: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2836: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2837: $incourse = 1;
2838: if ($env{'form.forceedit'}) {
2839: $forceview = 1;
2840: } else {
2841: $forceedit = 1;
2842: }
2843: $cfile = $resurl;
2844: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2845: $incourse = 1;
2846: $cfile = $resurl.'/smpedit';
2847: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2848: $incourse = 1;
2849: if ($env{'form.forceedit'}) {
2850: $forceview = 1;
2851: } else {
2852: $forceedit = 1;
2853: }
2854: $cfile = $resurl;
1.1172.2.15 raeburn 2855: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2856: $incourse = 1;
2857: if ($env{'form.forceedit'}) {
2858: $forceview = 1;
2859: } else {
2860: $forceedit = 1;
2861: }
2862: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2863: }
2864: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2865: my $template = '/res/lib/templates/simpleproblem.problem';
2866: if (&is_on_map($template)) {
2867: $incourse = 1;
2868: $forceview = 1;
2869: $cfile = $template;
2870: }
2871: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2872: $incourse = 1;
2873: if ($env{'form.forceedit'}) {
2874: $forceview = 1;
2875: } else {
2876: $forceedit = 1;
2877: }
2878: $cfile = $resurl;
2879: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2880: $incourse = 1;
2881: $forceview = 1;
2882: if ($symb) {
2883: my ($map,$id,$res)=&decode_symb($symb);
2884: $env{'request.symb'} = $symb;
2885: $cfile = &clutter($res);
2886: } else {
2887: $cfile = $env{'form.suppurl'};
2888: $cfile =~ s{^http://}{};
2889: $cfile = '/adm/wrapper/ext/'.$cfile;
2890: }
1.1172.2.31 raeburn 2891: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2892: if ($env{'form.forceedit'}) {
2893: $forceview = 1;
2894: } else {
2895: $forceedit = 1;
2896: }
2897: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2898: }
2899: }
2900: if ($uploaded || $incourse) {
2901: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2902: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2903: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2904: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2905: # Check that the user has permission to edit this resource
2906: my $setpriv = 1;
2907: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2908: if (defined($cfudom)) {
2909: $home=&homeserver($cfuname,$cfudom);
2910: $cfile=$file;
2911: }
2912: }
2913: if (($cfile ne '') && (!$incourse || $uploaded) &&
2914: (($home ne '') && ($home ne 'no_host'))) {
2915: my @ids=¤t_machine_ids();
2916: unless (grep(/^\Q$home\E$/,@ids)) {
2917: $switchserver=1;
2918: }
2919: }
2920: }
2921: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2922: }
2923:
2924: sub is_course_upload {
2925: my ($file,$cnum,$cdom) = @_;
2926: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2927: $uploadpath =~ s{^\/}{};
2928: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2929: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2930: return 1;
2931: }
2932: return;
2933: }
2934:
2935: sub in_course {
2936: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2937: if ($hideprivileged) {
2938: my $skipuser;
1.1172.2.23 raeburn 2939: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2940: my @possdoms = ($cdom);
2941: if ($coursehash{'checkforpriv'}) {
2942: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2943: }
2944: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2945: $skipuser = 1;
2946: if ($coursehash{'nothideprivileged'}) {
2947: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2948: my $user;
2949: if ($item =~ /:/) {
2950: $user = $item;
2951: } else {
2952: $user = join(':',split(/[\@]/,$item));
2953: }
2954: if ($user eq $uname.':'.$udom) {
2955: undef($skipuser);
2956: last;
2957: }
2958: }
2959: }
2960: if ($skipuser) {
2961: return 0;
2962: }
2963: }
2964: }
2965: $type ||= 'any';
2966: if (!defined($cdom) || !defined($cnum)) {
2967: my $cid = $env{'request.course.id'};
2968: $cdom = $env{'course.'.$cid.'.domain'};
2969: $cnum = $env{'course.'.$cid.'.num'};
2970: }
2971: my $typesref;
2972: if (($type eq 'any') || ($type eq 'all')) {
2973: $typesref = ['active','previous','future'];
2974: } elsif ($type eq 'previous' || $type eq 'future') {
2975: $typesref = [$type];
2976: }
2977: my %roles = &get_my_roles($uname,$udom,'userroles',
2978: $typesref,undef,[$cdom]);
2979: my ($tmp) = keys(%roles);
2980: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2981: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2982: if (@course_roles > 0) {
2983: return 1;
2984: }
2985: return 0;
2986: }
2987:
1.478 albertel 2988: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2989: # input: action, courseID, current domain, intended
1.637 raeburn 2990: # path to file, source of file, instruction to parse file for objects,
2991: # ref to hash for embedded objects,
2992: # ref to hash for codebase of java objects.
1.1095 raeburn 2993: # reference to scalar to accommodate mime type determined
2994: # from File::MMagic if $parser = parse.
1.637 raeburn 2995: #
1.485 raeburn 2996: # output: url to file (if action was uploaddoc),
2997: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2998: #
1.478 albertel 2999: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3000: # course.
1.477 raeburn 3001: #
1.478 albertel 3002: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3003: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3004: # course's home server.
1.477 raeburn 3005: #
1.478 albertel 3006: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3007: # be copied from $source (current location) to
3008: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3009: # and will then be copied to
3010: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3011: # course's home server.
1.485 raeburn 3012: #
1.481 raeburn 3013: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3014: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3015: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3016: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3017: # in course's home server.
1.637 raeburn 3018: #
1.477 raeburn 3019:
3020: sub process_coursefile {
1.1095 raeburn 3021: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3022: $mimetype)=@_;
1.477 raeburn 3023: my $fetchresult;
1.638 albertel 3024: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3025: if ($action eq 'propagate') {
1.638 albertel 3026: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3027: $home);
1.481 raeburn 3028: } else {
1.477 raeburn 3029: my $fpath = '';
3030: my $fname = $file;
1.478 albertel 3031: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3032: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3033: my $filepath = &build_filepath($fpath);
1.481 raeburn 3034: if ($action eq 'copy') {
3035: if ($source eq '') {
3036: $fetchresult = 'no source file';
3037: return $fetchresult;
3038: } else {
3039: my $destination = $filepath.'/'.$fname;
3040: rename($source,$destination);
3041: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3042: $home);
1.481 raeburn 3043: }
3044: } elsif ($action eq 'uploaddoc') {
3045: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3046: print $fh $env{'form.'.$source};
1.481 raeburn 3047: close($fh);
1.637 raeburn 3048: if ($parser eq 'parse') {
1.1024 raeburn 3049: my $mm = new File::MMagic;
1.1095 raeburn 3050: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3051: if ($type eq 'text/html') {
1.1024 raeburn 3052: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3053: unless ($parse_result eq 'ok') {
3054: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3055: }
1.637 raeburn 3056: }
1.1095 raeburn 3057: if (ref($mimetype)) {
3058: $$mimetype = $type;
3059: }
1.637 raeburn 3060: }
1.477 raeburn 3061: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3062: $home);
1.481 raeburn 3063: if ($fetchresult eq 'ok') {
3064: return '/uploaded/'.$fpath.'/'.$fname;
3065: } else {
3066: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3067: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3068: return '/adm/notfound.html';
3069: }
1.477 raeburn 3070: }
3071: }
1.485 raeburn 3072: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3073: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3074: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3075: }
3076: return $fetchresult;
3077: }
3078:
1.637 raeburn 3079: sub build_filepath {
3080: my ($fpath) = @_;
3081: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3082: unless ($fpath eq '') {
3083: my @parts=split('/',$fpath);
3084: foreach my $part (@parts) {
3085: $filepath.= '/'.$part;
3086: if ((-e $filepath)!=1) {
3087: mkdir($filepath,0777);
3088: }
3089: }
3090: }
3091: return $filepath;
3092: }
3093:
3094: sub store_edited_file {
1.638 albertel 3095: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3096: my $file = $primary_url;
3097: $file =~ s#^/uploaded/$docudom/$docuname/##;
3098: my $fpath = '';
3099: my $fname = $file;
3100: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3101: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3102: my $filepath = &build_filepath($fpath);
3103: open(my $fh,'>'.$filepath.'/'.$fname);
3104: print $fh $content;
3105: close($fh);
1.638 albertel 3106: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3107: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3108: $home);
1.637 raeburn 3109: if ($$fetchresult eq 'ok') {
3110: return '/uploaded/'.$fpath.'/'.$fname;
3111: } else {
1.638 albertel 3112: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3113: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3114: return '/adm/notfound.html';
3115: }
3116: }
3117:
1.531 albertel 3118: sub clean_filename {
1.831 albertel 3119: my ($fname,$args)=@_;
1.315 www 3120: # Replace Windows backslashes by forward slashes
1.257 www 3121: $fname=~s/\\/\//g;
1.831 albertel 3122: if (!$args->{'keep_path'}) {
3123: # Get rid of everything but the actual filename
3124: $fname=~s/^.*\/([^\/]+)$/$1/;
3125: }
1.315 www 3126: # Replace spaces by underscores
3127: $fname=~s/\s+/\_/g;
3128: # Replace all other weird characters by nothing
1.831 albertel 3129: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3130: # Replace all .\d. sequences with _\d. so they no longer look like version
3131: # numbers
3132: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3133: return $fname;
3134: }
1.1051 raeburn 3135: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3136: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3137: # image with the same aspect ratio as the original, but with dimensions which do
3138: # not exceed $resizewidth and $resizeheight.
3139:
1.984 neumanie 3140: sub resizeImage {
1.1051 raeburn 3141: my ($img_path,$resizewidth,$resizeheight) = @_;
3142: my $ima = Image::Magick->new;
3143: my $resized;
3144: if (-e $img_path) {
3145: $ima->Read($img_path);
3146: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3147: my $width = $ima->Get('width');
3148: my $height = $ima->Get('height');
3149: if ($width > $resizewidth) {
3150: my $factor = $width/$resizewidth;
3151: my $newheight = $height/$factor;
3152: $ima->Scale(width=>$resizewidth,height=>$newheight);
3153: $resized = 1;
3154: }
3155: }
3156: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3157: my $width = $ima->Get('width');
3158: my $height = $ima->Get('height');
3159: if ($height > $resizeheight) {
3160: my $factor = $height/$resizeheight;
3161: my $newwidth = $width/$factor;
3162: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3163: $resized = 1;
3164: }
3165: }
3166: if ($resized) {
3167: $ima->Write($img_path);
3168: }
3169: }
3170: return;
1.977 amueller 3171: }
3172:
1.608 albertel 3173: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3174: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3175: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3176: # $context - possible values: coursedoc, existingfile, overwrite,
3177: # canceloverwrite, or ''.
3178: # if 'coursedoc': upload to the current course
3179: # if 'existingfile': write file to tmp/overwrites directory
3180: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3181: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3182: # $subdir - directory in userfile to store the file into
1.858 raeburn 3183: # $parser - instruction to parse file for objects ($parser = parse)
3184: # $allfiles - reference to hash for embedded objects
3185: # $codebase - reference to hash for codebase of java objects
3186: # $desuname - username for permanent storage of uploaded file
3187: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3188: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3189: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3190: # $resizewidth - width (pixels) to which to resize uploaded image
3191: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3192: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3193: # from File::MMagic.
1.858 raeburn 3194: #
1.686 albertel 3195: # output: url of file in userspace, or error: <message>
3196: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3197:
1.531 albertel 3198: sub userfileupload {
1.1090 raeburn 3199: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3200: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3201: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3202: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3203: $fname=&clean_filename($fname);
1.1090 raeburn 3204: # See if there is anything left
1.257 www 3205: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3206: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3207: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3208: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3209: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3210: my $now = time;
1.1090 raeburn 3211: my $filepath;
1.1095 raeburn 3212: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3213: $filepath = 'tmp/helprequests/'.$now;
3214: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3215: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3216: '_'.$env{'user.domain'}.'/pending';
3217: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3218: my ($docuname,$docudom);
3219: if ($destudom) {
3220: $docudom = $destudom;
3221: } else {
3222: $docudom = $env{'user.domain'};
3223: }
3224: if ($destuname) {
3225: $docuname = $destuname;
3226: } else {
3227: $docuname = $env{'user.name'};
3228: }
3229: if (exists($env{'form.group'})) {
3230: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3231: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3232: }
3233: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3234: if ($context eq 'canceloverwrite') {
3235: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3236: if (-e $tempfile) {
3237: my @info = stat($tempfile);
3238: if ($info[9] eq $env{'form.timestamp'}) {
3239: unlink($tempfile);
3240: }
3241: }
3242: return;
1.523 raeburn 3243: }
3244: }
1.1090 raeburn 3245: # Create the directory if not present
1.741 raeburn 3246: my @parts=split(/\//,$filepath);
3247: my $fullpath = $perlvar{'lonDaemons'};
3248: for (my $i=0;$i<@parts;$i++) {
3249: $fullpath .= '/'.$parts[$i];
3250: if ((-e $fullpath)!=1) {
3251: mkdir($fullpath,0777);
3252: }
3253: }
3254: open(my $fh,'>'.$fullpath.'/'.$fname);
3255: print $fh $env{'form.'.$formname};
3256: close($fh);
1.1090 raeburn 3257: if ($context eq 'existingfile') {
3258: my @info = stat($fullpath.'/'.$fname);
3259: return ($fullpath.'/'.$fname,$info[9]);
3260: } else {
3261: return $fullpath.'/'.$fname;
3262: }
1.523 raeburn 3263: }
1.995 raeburn 3264: if ($subdir eq 'scantron') {
3265: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3266: } else {
1.995 raeburn 3267: $fname="$subdir/$fname";
3268: }
1.1090 raeburn 3269: if ($context eq 'coursedoc') {
1.638 albertel 3270: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3271: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3272: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3273: return &finishuserfileupload($docuname,$docudom,
3274: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3275: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3276: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3277: } else {
1.1172.2.21 raeburn 3278: if ($env{'form.folder'}) {
3279: $fname=$env{'form.folder'}.'/'.$fname;
3280: }
1.638 albertel 3281: return &process_coursefile('uploaddoc',$docuname,$docudom,
3282: $fname,$formname,$parser,
1.1095 raeburn 3283: $allfiles,$codebase,$mimetype);
1.481 raeburn 3284: }
1.719 banghart 3285: } elsif (defined($destuname)) {
3286: my $docuname=$destuname;
3287: my $docudom=$destudom;
1.860 raeburn 3288: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3289: $parser,$allfiles,$codebase,
1.1051 raeburn 3290: $thumbwidth,$thumbheight,
1.1095 raeburn 3291: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3292: } else {
1.638 albertel 3293: my $docuname=$env{'user.name'};
3294: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3295: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3296: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3297: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3298: }
1.860 raeburn 3299: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3300: $parser,$allfiles,$codebase,
1.1051 raeburn 3301: $thumbwidth,$thumbheight,
1.1095 raeburn 3302: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3303: }
1.271 www 3304: }
3305:
3306: sub finishuserfileupload {
1.860 raeburn 3307: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3308: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3309: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3310: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3311:
1.860 raeburn 3312: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3313: $file=$fname;
3314: if ($fname=~m|/|) {
3315: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3316: $path.=$fnamepath.'/';
3317: }
1.259 www 3318: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3319: my $count;
3320: for ($count=4;$count<=$#parts;$count++) {
3321: $filepath.="/$parts[$count]";
3322: if ((-e $filepath)!=1) {
3323: mkdir($filepath,0777);
3324: }
3325: }
1.984 neumanie 3326:
1.258 www 3327: # Save the file
3328: {
1.701 albertel 3329: if (!open(FH,'>'.$filepath.'/'.$file)) {
3330: &logthis('Failed to create '.$filepath.'/'.$file);
3331: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3332: return '/adm/notfound.html';
3333: }
1.1090 raeburn 3334: if ($context eq 'overwrite') {
1.1117 foxr 3335: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3336: my $target = $filepath.'/'.$file;
3337: if (-e $source) {
3338: my @info = stat($source);
3339: if ($info[9] eq $env{'form.timestamp'}) {
3340: unless (&File::Copy::move($source,$target)) {
3341: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3342: return "Moving from $source failed";
3343: }
3344: } else {
3345: return "Temporary file: $source had unexpected date/time for last modification";
3346: }
3347: } else {
3348: return "Temporary file: $source missing";
3349: }
3350: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3351: &logthis('Failed to write to '.$filepath.'/'.$file);
3352: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3353: return '/adm/notfound.html';
3354: }
1.570 albertel 3355: close(FH);
1.1051 raeburn 3356: if ($resizewidth && $resizeheight) {
3357: my $mm = new File::MMagic;
3358: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3359: if ($mime_type =~ m{^image/}) {
3360: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3361: }
1.977 amueller 3362: }
1.258 www 3363: }
1.1152 raeburn 3364: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3365: if (ref($mimetype)) {
3366: if ($$mimetype eq '') {
3367: my $mm = new File::MMagic;
3368: my $type = $mm->checktype_filename($filepath.'/'.$file);
3369: $$mimetype = $type;
3370: }
3371: }
3372: }
1.637 raeburn 3373: if ($parser eq 'parse') {
1.1152 raeburn 3374: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3375: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3376: $allfiles,$codebase);
3377: unless ($parse_result eq 'ok') {
3378: &logthis('Failed to parse '.$filepath.$file.
3379: ' for embedded media: '.$parse_result);
3380: }
1.637 raeburn 3381: }
3382: }
1.860 raeburn 3383: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3384: my $input = $filepath.'/'.$file;
3385: my $output = $filepath.'/'.'tn-'.$file;
3386: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3387: system("convert -sample $thumbsize $input $output");
3388: if (-e $filepath.'/'.'tn-'.$file) {
3389: $fetchthumb = 1;
3390: }
3391: }
1.858 raeburn 3392:
1.259 www 3393: # Notify homeserver to grep it
3394: #
1.984 neumanie 3395: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3396: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3397: if ($fetchresult eq 'ok') {
1.860 raeburn 3398: if ($fetchthumb) {
3399: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3400: if ($thumbresult ne 'ok') {
3401: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3402: $docuhome.': '.$thumbresult);
3403: }
3404: }
1.259 www 3405: #
1.258 www 3406: # Return the URL to it
1.494 albertel 3407: return '/uploaded/'.$path.$file;
1.263 www 3408: } else {
1.494 albertel 3409: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3410: ': '.$fetchresult);
1.263 www 3411: return '/adm/notfound.html';
1.858 raeburn 3412: }
1.493 albertel 3413: }
3414:
1.637 raeburn 3415: sub extract_embedded_items {
1.961 raeburn 3416: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3417: my @state = ();
1.1164 raeburn 3418: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3419: my %javafiles = (
3420: codebase => '',
3421: code => '',
3422: archive => ''
3423: );
3424: my %mediafiles = (
3425: src => '',
3426: movie => '',
3427: );
1.648 raeburn 3428: my $p;
3429: if ($content) {
3430: $p = HTML::LCParser->new($content);
3431: } else {
1.961 raeburn 3432: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3433: }
1.641 albertel 3434: while (my $t=$p->get_token()) {
1.640 albertel 3435: if ($t->[0] eq 'S') {
3436: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3437: push(@state, $tagname);
1.648 raeburn 3438: if (lc($tagname) eq 'allow') {
3439: &add_filetype($allfiles,$attr->{'src'},'src');
3440: }
1.640 albertel 3441: if (lc($tagname) eq 'img') {
3442: &add_filetype($allfiles,$attr->{'src'},'src');
3443: }
1.886 albertel 3444: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3445: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3446: &add_filetype($allfiles,$attr->{'href'},'href');
3447: }
1.886 albertel 3448: }
1.645 raeburn 3449: if (lc($tagname) eq 'script') {
1.1164 raeburn 3450: my $src;
1.645 raeburn 3451: if ($attr->{'archive'} =~ /\.jar$/i) {
3452: &add_filetype($allfiles,$attr->{'archive'},'archive');
3453: } else {
1.1164 raeburn 3454: if ($attr->{'src'} ne '') {
3455: $src = $attr->{'src'};
3456: &add_filetype($allfiles,$src,'src');
3457: }
3458: }
3459: my $text = $p->get_trimmed_text();
3460: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3461: my @swfargs = split(/,/,$1);
3462: foreach my $item (@swfargs) {
3463: $item =~ s/["']//g;
3464: $item =~ s/^\s+//;
3465: $item =~ s/\s+$//;
3466: }
3467: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3468: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3469: push(@{$related{$swfargs[0]}},$swfargs[2]);
3470: } else {
3471: $related{$swfargs[0]} = [$swfargs[2]];
3472: }
3473: }
1.645 raeburn 3474: }
3475: }
3476: if (lc($tagname) eq 'link') {
3477: if (lc($attr->{'rel'}) eq 'stylesheet') {
3478: &add_filetype($allfiles,$attr->{'href'},'href');
3479: }
3480: }
1.640 albertel 3481: if (lc($tagname) eq 'object' ||
3482: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3483: foreach my $item (keys(%javafiles)) {
3484: $javafiles{$item} = '';
3485: }
1.1164 raeburn 3486: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3487: $lastids{lc($tagname)} = $attr->{'id'};
3488: }
1.640 albertel 3489: }
3490: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3491: my $name = lc($attr->{'name'});
3492: foreach my $item (keys(%javafiles)) {
3493: if ($name eq $item) {
3494: $javafiles{$item} = $attr->{'value'};
3495: last;
3496: }
3497: }
1.1164 raeburn 3498: my $pathfrom;
1.640 albertel 3499: foreach my $item (keys(%mediafiles)) {
3500: if ($name eq $item) {
1.1164 raeburn 3501: $pathfrom = $attr->{'value'};
3502: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3503: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3504: last;
3505: }
3506: }
1.1164 raeburn 3507: if ($name eq 'flashvars') {
3508: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3509: }
3510: if ($pathfrom ne '') {
3511: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3512: $pathfrom);
3513: }
1.640 albertel 3514: }
3515: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3516: foreach my $item (keys(%javafiles)) {
3517: if ($attr->{$item}) {
3518: $javafiles{$item} = $attr->{$item};
3519: last;
3520: }
3521: }
3522: foreach my $item (keys(%mediafiles)) {
3523: if ($attr->{$item}) {
3524: &add_filetype($allfiles,$attr->{$item},$item);
3525: last;
3526: }
3527: }
1.1164 raeburn 3528: if (lc($tagname) eq 'embed') {
3529: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3530: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3531: $attr->{'src'});
3532: }
3533: }
1.640 albertel 3534: }
1.1172.2.35 raeburn 3535: if (lc($tagname) eq 'iframe') {
3536: my $src = $attr->{'src'} ;
3537: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3538: &add_filetype($allfiles,$src,'src');
3539: } elsif ($src =~ m{^/}) {
3540: if ($env{'request.course.id'}) {
3541: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3542: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3543: my $url = &hreflocation('',$fullpath);
3544: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3545: my $relpath = $1;
3546: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3547: &add_filetype($allfiles,$1,'src');
3548: }
3549: }
3550: }
3551: }
3552: }
1.1164 raeburn 3553: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3554: pop(@state);
1.1164 raeburn 3555: }
1.640 albertel 3556: } elsif ($t->[0] eq 'E') {
3557: my ($tagname) = ($t->[1]);
3558: if ($javafiles{'codebase'} ne '') {
3559: $javafiles{'codebase'} .= '/';
3560: }
3561: if (lc($tagname) eq 'applet' ||
3562: lc($tagname) eq 'object' ||
3563: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3564: ) {
3565: foreach my $item (keys(%javafiles)) {
3566: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3567: my $file=$javafiles{'codebase'}.$javafiles{$item};
3568: &add_filetype($allfiles,$file,$item);
3569: }
3570: }
3571: }
3572: pop @state;
3573: }
3574: }
1.1164 raeburn 3575: foreach my $id (sort(keys(%flashvars))) {
3576: if ($shockwave{$id} ne '') {
3577: my @pairs = split(/\&/,$flashvars{$id});
3578: foreach my $pair (@pairs) {
3579: my ($key,$value) = split(/\=/,$pair);
3580: if ($key eq 'thumb') {
3581: &add_filetype($allfiles,$value,$key);
3582: } elsif ($key eq 'content') {
3583: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3584: my ($ext) = ($value =~ /\.([^.]+)$/);
3585: if ($ext ne '') {
3586: &add_filetype($allfiles,$path.$value,$ext);
3587: }
3588: }
3589: }
3590: }
3591: }
1.637 raeburn 3592: return 'ok';
3593: }
3594:
1.639 albertel 3595: sub add_filetype {
3596: my ($allfiles,$file,$type)=@_;
3597: if (exists($allfiles->{$file})) {
3598: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3599: push(@{$allfiles->{$file}}, &escape($type));
3600: }
3601: } else {
3602: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3603: }
3604: }
3605:
1.1164 raeburn 3606: sub embedded_dependency {
3607: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3608: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3609: if (($identifier ne '') &&
3610: (ref($related->{$identifier}) eq 'ARRAY') &&
3611: ($pathfrom ne '')) {
3612: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3613: foreach my $dep (@{$related->{$identifier}}) {
3614: &add_filetype($allfiles,$path.$dep,'object');
3615: }
3616: }
3617: }
3618: return;
3619: }
3620:
1.493 albertel 3621: sub removeuploadedurl {
1.984 neumanie 3622: my ($url)=@_;
3623: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3624: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3625: }
3626:
3627: sub removeuserfile {
3628: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3629: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3630: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3631: if ($result eq 'ok') {
1.798 raeburn 3632: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3633: my $metafile = $fname.'.meta';
3634: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3635: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3636: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3637: my $sqlresult =
1.823 albertel 3638: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3639: 'portfolio_metadata',$group,
3640: 'delete');
1.798 raeburn 3641: }
3642: }
3643: return $result;
1.257 www 3644: }
1.15 www 3645:
1.530 albertel 3646: sub mkdiruserfile {
3647: my ($docuname,$docudom,$dir)=@_;
3648: my $home=&homeserver($docuname,$docudom);
3649: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3650: }
3651:
1.531 albertel 3652: sub renameuserfile {
3653: my ($docuname,$docudom,$old,$new)=@_;
3654: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3655: my $result = &reply("renameuserfile:$docudom:$docuname:".
3656: &escape("$old").':'.&escape("$new"),$home);
3657: if ($result eq 'ok') {
3658: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3659: my $oldmeta = $old.'.meta';
3660: my $newmeta = $new.'.meta';
3661: my $metaresult =
3662: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3663: my $url = "/uploaded/$docudom/$docuname/$old";
3664: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3665: my $sqlresult =
1.823 albertel 3666: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3667: 'portfolio_metadata',$group,
3668: 'delete');
1.798 raeburn 3669: }
3670: }
3671: return $result;
1.531 albertel 3672: }
3673:
1.14 www 3674: # ------------------------------------------------------------------------- Log
3675:
3676: sub log {
3677: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3678: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3679: }
3680:
3681: # ------------------------------------------------------------------ Course Log
1.352 www 3682: #
3683: # This routine flushes several buffers of non-mission-critical nature
3684: #
1.157 www 3685:
3686: sub flushcourselogs {
1.352 www 3687: &logthis('Flushing log buffers');
3688: #
3689: # course logs
3690: # This is a log of all transactions in a course, which can be used
3691: # for data mining purposes
3692: #
3693: # It also collects the courseid database, which lists last transaction
3694: # times and course titles for all courseids
3695: #
3696: my %courseidbuffer=();
1.921 raeburn 3697: foreach my $crsid (keys(%courselogs)) {
1.352 www 3698: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3699: &escape($courselogs{$crsid}),
3700: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3701: delete $courselogs{$crsid};
3702: } else {
3703: &logthis('Failed to flush log buffer for '.$crsid);
3704: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3705: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3706: " exceeded maximum size, deleting.</font>");
3707: delete $courselogs{$crsid};
3708: }
1.352 www 3709: }
1.920 raeburn 3710: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3711: 'description' => $coursedescrbuf{$crsid},
3712: 'inst_code' => $courseinstcodebuf{$crsid},
3713: 'type' => $coursetypebuf{$crsid},
3714: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3715: };
1.191 harris41 3716: }
1.352 www 3717: #
3718: # Write course id database (reverse lookup) to homeserver of courses
3719: # Is used in pickcourse
3720: #
1.840 albertel 3721: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3722: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3723: $courseidbuffer{$crs_home},
3724: $crs_home,'timeonly');
1.352 www 3725: }
3726: #
3727: # File accesses
3728: # Writes to the dynamic metadata of resources to get hit counts, etc.
3729: #
1.449 matthew 3730: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3731: if ($entry =~ /___count$/) {
3732: my ($dom,$name);
1.807 albertel 3733: ($dom,$name,undef)=
1.811 albertel 3734: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3735: if (! defined($dom) || $dom eq '' ||
3736: ! defined($name) || $name eq '') {
1.620 albertel 3737: my $cid = $env{'request.course.id'};
3738: $dom = $env{'request.'.$cid.'.domain'};
3739: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3740: }
1.450 matthew 3741: my $value = $accesshash{$entry};
3742: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3743: my %temphash=($url => $value);
1.449 matthew 3744: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3745: if ($result eq 'ok') {
3746: delete $accesshash{$entry};
3747: }
3748: } else {
1.811 albertel 3749: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3750: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3751: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3752: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3753: delete $accesshash{$entry};
3754: }
1.185 www 3755: }
1.191 harris41 3756: }
1.352 www 3757: #
3758: # Roles
3759: # Reverse lookup of user roles for course faculty/staff and co-authorship
3760: #
1.800 albertel 3761: foreach my $entry (keys(%userrolehash)) {
1.351 www 3762: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3763: split(/\:/,$entry);
3764: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3765: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3766: $rudom,$runame) eq 'ok') {
3767: delete $userrolehash{$entry};
3768: }
3769: }
1.662 raeburn 3770: #
3771: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3772: #
3773: my %domrolebuffer = ();
1.1000 raeburn 3774: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3775: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3776: if ($domrolebuffer{$rudom}) {
3777: $domrolebuffer{$rudom}.='&'.&escape($entry).
3778: '='.&escape($domainrolehash{$entry});
3779: } else {
3780: $domrolebuffer{$rudom}.=&escape($entry).
3781: '='.&escape($domainrolehash{$entry});
3782: }
3783: delete $domainrolehash{$entry};
3784: }
3785: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3786: my %servers = &get_servers($dom,'library');
3787: foreach my $tryserver (keys(%servers)) {
3788: unless (&reply('domroleput:'.$dom.':'.
3789: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3790: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3791: }
1.662 raeburn 3792: }
3793: }
1.186 www 3794: $dumpcount++;
1.157 www 3795: }
3796:
3797: sub courselog {
3798: my $what=shift;
1.158 www 3799: $what=time.':'.$what;
1.620 albertel 3800: unless ($env{'request.course.id'}) { return ''; }
3801: $coursedombuf{$env{'request.course.id'}}=
3802: $env{'course.'.$env{'request.course.id'}.'.domain'};
3803: $coursenumbuf{$env{'request.course.id'}}=
3804: $env{'course.'.$env{'request.course.id'}.'.num'};
3805: $coursehombuf{$env{'request.course.id'}}=
3806: $env{'course.'.$env{'request.course.id'}.'.home'};
3807: $coursedescrbuf{$env{'request.course.id'}}=
3808: $env{'course.'.$env{'request.course.id'}.'.description'};
3809: $courseinstcodebuf{$env{'request.course.id'}}=
3810: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3811: $courseownerbuf{$env{'request.course.id'}}=
3812: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3813: $coursetypebuf{$env{'request.course.id'}}=
3814: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3815: if (defined $courselogs{$env{'request.course.id'}}) {
3816: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3817: } else {
1.620 albertel 3818: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3819: }
1.620 albertel 3820: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3821: &flushcourselogs();
3822: }
1.158 www 3823: }
3824:
3825: sub courseacclog {
3826: my $fnsymb=shift;
1.620 albertel 3827: unless ($env{'request.course.id'}) { return ''; }
3828: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3829: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3830: $what.=':POST';
1.583 matthew 3831: # FIXME: Probably ought to escape things....
1.800 albertel 3832: foreach my $key (keys(%env)) {
3833: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3834: my $formitem = $1;
3835: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3836: $what.=':'.$formitem.'='.$env{$key};
3837: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3838: $what.=':'.$formitem.'='.$env{$key};
3839: }
1.158 www 3840: }
1.191 harris41 3841: }
1.583 matthew 3842: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3843: # FIXME: We should not be depending on a form parameter that someone
3844: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3845: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3846: $what.= ':POST';
3847: # FIXME: Probably ought to escape things....
3848: foreach my $element ('courseexp','crsfulltext','crsrelated',
3849: 'crsdiscuss') {
1.620 albertel 3850: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3851: }
3852: }
1.158 www 3853: }
3854: &courselog($what);
1.149 www 3855: }
3856:
1.185 www 3857: sub countacc {
3858: my $url=&declutter(shift);
1.458 matthew 3859: return if (! defined($url) || $url eq '');
1.620 albertel 3860: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3861: #
3862: # Mark that this url was used in this course
3863: #
1.620 albertel 3864: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3865: #
3866: # Increase the access count for this resource in this child process
3867: #
1.281 www 3868: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3869: $accesshash{$key}++;
1.185 www 3870: }
1.349 www 3871:
1.361 www 3872: sub linklog {
3873: my ($from,$to)=@_;
3874: $from=&declutter($from);
3875: $to=&declutter($to);
3876: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3877: $accesshash{$to.'___'.$from.'___goto'}=1;
3878: }
1.1160 www 3879:
3880: sub statslog {
3881: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3882: if ($users<2) { return; }
3883: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3884: 'course' => $env{'request.course.id'},
3885: 'sections' => '"all"',
3886: 'num_students' => $users,
3887: 'part' => $part,
3888: 'symb' => $symb,
3889: 'mean_tries' => $av_attempts,
3890: 'deg_of_diff' => $degdiff});
3891: foreach my $key (keys(%dynstore)) {
3892: $accesshash{$key}=$dynstore{$key};
3893: }
3894: }
1.361 www 3895:
1.349 www 3896: sub userrolelog {
3897: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3898: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3899: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3900: $userrolehash
3901: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3902: =$tend.':'.$tstart;
1.662 raeburn 3903: }
1.1169 droeschl 3904: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3905: $userrolehash
3906: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3907: =$tend.':'.$tstart;
3908: }
1.1169 droeschl 3909: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3910: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3911: $domainrolehash
3912: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3913: = $tend.':'.$tstart;
3914: }
1.351 www 3915: }
3916:
1.957 raeburn 3917: sub courserolelog {
3918: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3919: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3920: my $cdom = $1;
3921: my $cnum = $2;
3922: my $sec = $3;
3923: my $namespace = 'rolelog';
3924: my %storehash = (
3925: role => $trole,
3926: start => $tstart,
3927: end => $tend,
3928: selfenroll => $selfenroll,
3929: context => $context,
3930: );
3931: if ($trole eq 'gr') {
3932: $namespace = 'groupslog';
3933: $storehash{'group'} = $sec;
3934: } else {
3935: $storehash{'section'} = $sec;
3936: }
3937: &write_log('course',$namespace,\%storehash,$delflag,$username,
3938: $domain,$cnum,$cdom);
3939: if (($trole ne 'st') || ($sec ne '')) {
3940: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3941: }
3942: }
3943: return;
3944: }
3945:
1.1172.2.9 raeburn 3946: sub domainrolelog {
3947: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3948: if ($area =~ m{^/($match_domain)/$}) {
3949: my $cdom = $1;
3950: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3951: my $namespace = 'rolelog';
3952: my %storehash = (
3953: role => $trole,
3954: start => $tstart,
3955: end => $tend,
3956: context => $context,
3957: );
3958: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3959: $domain,$domconfiguser,$cdom);
3960: }
3961: return;
3962:
3963: }
3964:
3965: sub coauthorrolelog {
3966: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3967: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3968: my $audom = $1;
3969: my $auname = $2;
3970: my $namespace = 'rolelog';
3971: my %storehash = (
3972: role => $trole,
3973: start => $tstart,
3974: end => $tend,
3975: context => $context,
3976: );
3977: &write_log('author',$namespace,\%storehash,$delflag,$username,
3978: $domain,$auname,$audom);
3979: }
3980: return;
3981: }
3982:
1.351 www 3983: sub get_course_adv_roles {
1.948 raeburn 3984: my ($cid,$codes) = @_;
1.620 albertel 3985: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3986: my %coursehash=&coursedescription($cid);
1.988 raeburn 3987: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3988: my %nothide=();
1.800 albertel 3989: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3990: if ($user !~ /:/) {
3991: $nothide{join(':',split(/[\@]/,$user))}=1;
3992: } else {
3993: $nothide{$user}=1;
3994: }
1.470 www 3995: }
1.1172.2.23 raeburn 3996: my @possdoms = ($coursehash{'domain'});
3997: if ($coursehash{'checkforpriv'}) {
3998: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3999: }
1.351 www 4000: my %returnhash=();
4001: my %dumphash=
4002: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4003: my $now=time;
1.997 raeburn 4004: my %privileged;
1.1000 raeburn 4005: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4006: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4007: if (($tstart) && ($tstart<0)) { next; }
4008: if (($tend) && ($tend<$now)) { next; }
4009: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4010: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4011: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4012: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4013: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4014: if ($role eq 'cr') { next; }
1.948 raeburn 4015: if ($codes) {
4016: if ($section) { $role .= ':'.$section; }
4017: if ($returnhash{$role}) {
4018: $returnhash{$role}.=','.$username.':'.$domain;
4019: } else {
4020: $returnhash{$role}=$username.':'.$domain;
4021: }
1.351 www 4022: } else {
1.988 raeburn 4023: my $key=&plaintext($role,$crstype);
1.973 bisitz 4024: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4025: if ($returnhash{$key}) {
4026: $returnhash{$key}.=','.$username.':'.$domain;
4027: } else {
4028: $returnhash{$key}=$username.':'.$domain;
4029: }
1.351 www 4030: }
1.948 raeburn 4031: }
1.400 www 4032: return %returnhash;
4033: }
4034:
4035: sub get_my_roles {
1.937 raeburn 4036: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4037: unless (defined($uname)) { $uname=$env{'user.name'}; }
4038: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4039: my (%dumphash,%nothide);
1.1086 raeburn 4040: if ($context eq 'userroles') {
1.1166 raeburn 4041: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4042: } else {
1.1172.2.23 raeburn 4043: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4044: if ($hidepriv) {
4045: my %coursehash=&coursedescription($udom.'_'.$uname);
4046: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4047: if ($user !~ /:/) {
4048: $nothide{join(':',split(/[\@]/,$user))} = 1;
4049: } else {
4050: $nothide{$user} = 1;
4051: }
4052: }
4053: }
1.858 raeburn 4054: }
1.400 www 4055: my %returnhash=();
4056: my $now=time;
1.999 raeburn 4057: my %privileged;
1.800 albertel 4058: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4059: my ($role,$tend,$tstart);
4060: if ($context eq 'userroles') {
1.1149 raeburn 4061: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4062: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4063: } else {
4064: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4065: }
1.400 www 4066: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4067: my $status = 'active';
1.939 raeburn 4068: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4069: $status = 'previous';
4070: }
4071: if (($tstart) && ($now<$tstart)) {
4072: $status = 'future';
4073: }
4074: if (ref($types) eq 'ARRAY') {
4075: if (!grep(/^\Q$status\E$/,@{$types})) {
4076: next;
4077: }
4078: } else {
4079: if ($status ne 'active') {
4080: next;
4081: }
4082: }
1.867 raeburn 4083: my ($rolecode,$username,$domain,$section,$area);
4084: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4085: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4086: (undef,$domain,$username,$section) = split(/\//,$area);
4087: } else {
4088: ($role,$username,$domain,$section) = split(/\:/,$entry);
4089: }
1.832 raeburn 4090: if (ref($roledoms) eq 'ARRAY') {
4091: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4092: next;
4093: }
4094: }
4095: if (ref($roles) eq 'ARRAY') {
4096: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4097: if ($role =~ /^cr\//) {
4098: if (!grep(/^cr$/,@{$roles})) {
4099: next;
4100: }
1.1104 raeburn 4101: } elsif ($role =~ /^gr\//) {
4102: if (!grep(/^gr$/,@{$roles})) {
4103: next;
4104: }
1.922 raeburn 4105: } else {
4106: next;
4107: }
1.832 raeburn 4108: }
1.867 raeburn 4109: }
1.937 raeburn 4110: if ($hidepriv) {
1.1172.2.23 raeburn 4111: my @privroles = ('dc','su');
1.999 raeburn 4112: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4113: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4114: } else {
1.1172.2.23 raeburn 4115: my $possdoms = [$domain];
4116: if (ref($roledoms) eq 'ARRAY') {
4117: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4118: }
1.1172.2.23 raeburn 4119: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4120: if (!$nothide{$username.':'.$domain}) {
4121: next;
4122: }
4123: }
1.937 raeburn 4124: }
4125: }
1.933 raeburn 4126: if ($withsec) {
4127: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4128: $tstart.':'.$tend;
4129: } else {
4130: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4131: }
1.832 raeburn 4132: }
1.373 www 4133: return %returnhash;
1.399 www 4134: }
4135:
4136: # ----------------------------------------------------- Frontpage Announcements
4137: #
4138: #
4139:
4140: sub postannounce {
4141: my ($server,$text)=@_;
1.844 albertel 4142: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4143: unless ($text=~/\w/) { $text=''; }
4144: return &reply('setannounce:'.&escape($text),$server);
4145: }
4146:
4147: sub getannounce {
1.448 albertel 4148:
4149: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4150: my $announcement='';
1.800 albertel 4151: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4152: close($fh);
1.399 www 4153: if ($announcement=~/\w/) {
4154: return
4155: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4156: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4157: } else {
4158: return '';
4159: }
4160: } else {
4161: return '';
4162: }
1.351 www 4163: }
1.353 www 4164:
4165: # ---------------------------------------------------------- Course ID routines
4166: # Deal with domain's nohist_courseid.db files
4167: #
4168:
4169: sub courseidput {
1.921 raeburn 4170: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4171: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4172: my $outcome;
4173: if ($caller eq 'timeonly') {
4174: my $cids = '';
4175: foreach my $item (keys(%$storehash)) {
4176: $cids.=&escape($item).'&';
4177: }
4178: $cids=~s/\&$//;
4179: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4180: $coursehome);
4181: } else {
4182: my $items = '';
4183: foreach my $item (keys(%$storehash)) {
4184: $items.= &escape($item).'='.
4185: &freeze_escape($$storehash{$item}).'&';
4186: }
4187: $items=~s/\&$//;
4188: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4189: $coursehome);
1.918 raeburn 4190: }
4191: if ($outcome eq 'unknown_cmd') {
4192: my $what;
4193: foreach my $cid (keys(%$storehash)) {
4194: $what .= &escape($cid).'=';
1.921 raeburn 4195: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4196: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4197: }
4198: $what =~ s/\:$/&/;
4199: }
4200: $what =~ s/\&$//;
4201: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4202: } else {
4203: return $outcome;
4204: }
1.353 www 4205: }
4206:
4207: sub courseiddump {
1.921 raeburn 4208: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4209: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4210: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4211: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4212: $hasuniquecode)=@_;
1.918 raeburn 4213: my $as_hash = 1;
4214: my %returnhash;
4215: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4216: my %libserv = &all_library();
4217: foreach my $tryserver (keys(%libserv)) {
4218: if ( ( $hostidflag == 1
4219: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4220: || (!defined($hostidflag)) ) {
4221:
1.918 raeburn 4222: if (($domfilter eq '') ||
4223: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4224: my $rep;
4225: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4226: $rep = &LONCAPA::Lond::dump_course_id_handler(
4227: join(":", (&host_domain($tryserver), $sincefilter,
4228: &escape($descfilter), &escape($instcodefilter),
4229: &escape($ownerfilter), &escape($coursefilter),
4230: &escape($typefilter), &escape($regexp_ok),
4231: $as_hash, &escape($selfenrollonly),
4232: &escape($catfilter), $showhidden, $caller,
4233: &escape($cloner), &escape($cc_clone), $cloneonly,
4234: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4235: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4236: } else {
4237: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4238: $sincefilter.':'.&escape($descfilter).':'.
4239: &escape($instcodefilter).':'.&escape($ownerfilter).
4240: ':'.&escape($coursefilter).':'.&escape($typefilter).
4241: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4242: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4243: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4244: &escape($cc_clone).':'.$cloneonly.':'.
4245: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4246: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4247: $tryserver);
4248: }
4249:
1.918 raeburn 4250: my @pairs=split(/\&/,$rep);
4251: foreach my $item (@pairs) {
4252: my ($key,$value)=split(/\=/,$item,2);
4253: $key = &unescape($key);
4254: next if ($key =~ /^error: 2 /);
4255: my $result = &thaw_unescape($value);
4256: if (ref($result) eq 'HASH') {
4257: $returnhash{$key}=$result;
4258: } else {
1.921 raeburn 4259: my @responses = split(/:/,$value);
4260: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4261: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4262: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4263: }
1.1008 raeburn 4264: }
1.353 www 4265: }
4266: }
4267: }
4268: }
4269: return %returnhash;
4270: }
4271:
1.1055 raeburn 4272: sub courselastaccess {
4273: my ($cdom,$cnum,$hostidref) = @_;
4274: my %returnhash;
4275: if ($cdom && $cnum) {
4276: my $chome = &homeserver($cnum,$cdom);
4277: if ($chome ne 'no_host') {
4278: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4279: &extract_lastaccess(\%returnhash,$rep);
4280: }
4281: } else {
4282: if (!$cdom) { $cdom=''; }
4283: my %libserv = &all_library();
4284: foreach my $tryserver (keys(%libserv)) {
4285: if (ref($hostidref) eq 'ARRAY') {
4286: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4287: }
4288: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4289: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4290: &extract_lastaccess(\%returnhash,$rep);
4291: }
4292: }
4293: }
4294: return %returnhash;
4295: }
4296:
4297: sub extract_lastaccess {
4298: my ($returnhash,$rep) = @_;
4299: if (ref($returnhash) eq 'HASH') {
4300: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4301: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4302: $rep eq '') {
4303: my @pairs=split(/\&/,$rep);
4304: foreach my $item (@pairs) {
4305: my ($key,$value)=split(/\=/,$item,2);
4306: $key = &unescape($key);
4307: next if ($key =~ /^error: 2 /);
4308: $returnhash->{$key} = &thaw_unescape($value);
4309: }
4310: }
4311: }
4312: return;
4313: }
4314:
1.658 raeburn 4315: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4316:
4317: sub dcmailput {
1.685 raeburn 4318: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4319: my $status = &Apache::lonnet::critical(
1.740 www 4320: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4321: &escape($message),$server);
1.662 raeburn 4322: return $status;
4323: }
4324:
1.658 raeburn 4325: sub dcmaildump {
4326: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4327: my %returnhash=();
1.846 albertel 4328:
4329: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4330: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4331: &escape($enddate).':';
4332: my @esc_senders=map { &escape($_)} @$senders;
4333: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4334: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4335: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4336: if (($key) && ($value)) {
4337: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4338: }
4339: }
4340: }
4341: return %returnhash;
4342: }
1.662 raeburn 4343: # ---------------------------------------------------------- Domain roles
4344:
4345: sub get_domain_roles {
4346: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4347: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4348: $startdate = '.';
4349: }
1.1018 raeburn 4350: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4351: $enddate = '.';
4352: }
1.922 raeburn 4353: my $rolelist;
4354: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4355: $rolelist = join('&',@{$roles});
1.922 raeburn 4356: }
1.662 raeburn 4357: my %personnel = ();
1.841 albertel 4358:
4359: my %servers = &get_servers($dom,'library');
4360: foreach my $tryserver (keys(%servers)) {
4361: %{$personnel{$tryserver}}=();
4362: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4363: &escape($startdate).':'.
4364: &escape($enddate).':'.
4365: &escape($rolelist), $tryserver))) {
4366: my ($key,$value) = split(/\=/,$line,2);
4367: if (($key) && ($value)) {
4368: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4369: }
4370: }
1.662 raeburn 4371: }
4372: return %personnel;
4373: }
1.658 raeburn 4374:
1.1057 www 4375: # ----------------------------------------------------------- Interval timing
1.149 www 4376:
1.1153 www 4377: {
4378: # Caches needed for speedup of navmaps
4379: # We don't want to cache this for very long at all (5 seconds at most)
4380: #
4381: # The user for whom we cache
4382: my $cachedkey='';
4383: # The cached times for this user
4384: my %cachedtimes=();
4385: # When this was last done
4386: my $cachedtime=();
4387:
4388: sub load_all_first_access {
1.1154 raeburn 4389: my ($uname,$udom)=@_;
1.1156 www 4390: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4391: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4392: return;
4393: }
4394: $cachedtime=time;
4395: $cachedkey=$uname.':'.$udom;
4396: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4397: }
4398:
1.504 albertel 4399: sub get_first_access {
1.1162 raeburn 4400: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4401: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4402: if ($argsymb) { $symb=$argsymb; }
4403: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4404: if ($argmap) { $map = $argmap; }
1.926 albertel 4405: if ($type eq 'course') {
4406: $res='course';
4407: } elsif ($type eq 'map') {
1.588 albertel 4408: $res=&symbread($map);
4409: } else {
4410: $res=$symb;
4411: }
1.1153 www 4412: &load_all_first_access($uname,$udom);
4413: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4414: }
4415:
4416: sub set_first_access {
1.1162 raeburn 4417: my ($type,$interval)=@_;
1.790 albertel 4418: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4419: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4420: if ($type eq 'course') {
4421: $res='course';
4422: } elsif ($type eq 'map') {
1.588 albertel 4423: $res=&symbread($map);
4424: } else {
4425: $res=$symb;
4426: }
1.1153 www 4427: $cachedkey='';
1.1162 raeburn 4428: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4429: if (!$firstaccess) {
1.1162 raeburn 4430: my $start = time;
4431: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4432: $udom,$uname);
4433: if ($putres eq 'ok') {
4434: &put('timerinterval',{"$courseid\0$res"=>$interval},
4435: $udom,$uname);
4436: &appenv(
4437: {
4438: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4439: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4440: }
4441: );
4442: }
4443: return $putres;
1.505 albertel 4444: }
4445: return 'already_set';
1.504 albertel 4446: }
1.1153 www 4447: }
1.1172.2.32 raeburn 4448:
4449: sub checkout {
4450: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4451: my $now=time;
4452: my $lonhost=$perlvar{'lonHostID'};
4453: my $infostr=&escape(
4454: 'CHECKOUTTOKEN&'.
4455: $tuname.'&'.
4456: $tudom.'&'.
4457: $tcrsid.'&'.
4458: $symb.'&'.
4459: $now.'&'.$ENV{'REMOTE_ADDR'});
4460: my $token=&reply('tmpput:'.$infostr,$lonhost);
4461: if ($token=~/^error\:/) {
4462: &logthis("<font color=\"blue\">WARNING: ".
4463: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4464: "</font>");
4465: return '';
4466: }
4467:
4468: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4469: $token=~tr/a-z/A-Z/;
4470:
4471: my %infohash=('resource.0.outtoken' => $token,
4472: 'resource.0.checkouttime' => $now,
4473: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4474:
4475: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4476: return '';
4477: } else {
4478: &logthis("<font color=\"blue\">WARNING: ".
4479: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4480: "</font>");
4481: }
4482:
4483: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4484: &escape('Checkout '.$infostr.' - '.
4485: $token)) ne 'ok') {
4486: return '';
4487: } else {
4488: &logthis("<font color=\"blue\">WARNING: ".
4489: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4490: "</font>");
4491: }
4492: return $token;
4493: }
4494:
4495: # ------------------------------------------------------------ Check in an item
4496:
4497: sub checkin {
4498: my $token=shift;
4499: my $now=time;
4500: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4501: $lonhost=~tr/A-Z/a-z/;
4502: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4503: $dtoken=~s/\W/\_/g;
4504: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4505: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4506:
4507: unless (($tuname) && ($tudom)) {
4508: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4509: return '';
4510: }
4511:
4512: unless (&allowed('mgr',$tcrsid)) {
4513: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4514: $env{'user.name'}.' - '.$env{'user.domain'});
4515: return '';
4516: }
4517:
4518: my %infohash=('resource.0.intoken' => $token,
4519: 'resource.0.checkintime' => $now,
4520: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4521:
4522: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4523: return '';
4524: }
4525:
4526: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4527: &escape('Checkin - '.$token)) ne 'ok') {
4528: return '';
4529: }
4530:
4531: return ($symb,$tuname,$tudom,$tcrsid);
4532: }
4533:
1.110 www 4534: # --------------------------------------------- Set Expire Date for Spreadsheet
4535:
4536: sub expirespread {
4537: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4538: my $cid=$env{'request.course.id'};
1.110 www 4539: if ($cid) {
4540: my $now=time;
4541: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4542: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4543: $env{'course.'.$cid.'.num'}.
1.110 www 4544: ':nohist_expirationdates:'.
4545: &escape($key).'='.$now,
1.620 albertel 4546: $env{'course.'.$cid.'.home'})
1.110 www 4547: }
4548: return 'ok';
1.14 www 4549: }
4550:
1.109 www 4551: # ----------------------------------------------------- Devalidate Spreadsheets
4552:
4553: sub devalidate {
1.325 www 4554: my ($symb,$uname,$udom)=@_;
1.620 albertel 4555: my $cid=$env{'request.course.id'};
1.109 www 4556: if ($cid) {
1.391 matthew 4557: # delete the stored spreadsheets for
4558: # - the student level sheet of this user in course's homespace
4559: # - the assessment level sheet for this resource
4560: # for this user in user's homespace
1.553 albertel 4561: # - current conditional state info
1.325 www 4562: my $key=$uname.':'.$udom.':';
1.109 www 4563: my $status=
1.299 matthew 4564: &del('nohist_calculatedsheets',
1.391 matthew 4565: [$key.'studentcalc:'],
1.620 albertel 4566: $env{'course.'.$cid.'.domain'},
4567: $env{'course.'.$cid.'.num'})
1.133 albertel 4568: .' '.
4569: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4570: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4571: unless ($status eq 'ok ok') {
4572: &logthis('Could not devalidate spreadsheet '.
1.325 www 4573: $uname.' at '.$udom.' for '.
1.109 www 4574: $symb.': '.$status);
1.133 albertel 4575: }
1.553 albertel 4576: &delenv('user.state.'.$cid);
1.109 www 4577: }
4578: }
4579:
1.265 albertel 4580: sub get_scalar {
4581: my ($string,$end) = @_;
4582: my $value;
4583: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4584: $value = $1;
4585: } elsif ($$string =~ s/^([^&]*?)&//) {
4586: $value = $1;
4587: }
4588: return &unescape($value);
4589: }
4590:
4591: sub array2str {
4592: my (@array) = @_;
4593: my $result=&arrayref2str(\@array);
4594: $result=~s/^__ARRAY_REF__//;
4595: $result=~s/__END_ARRAY_REF__$//;
4596: return $result;
4597: }
4598:
1.204 albertel 4599: sub arrayref2str {
4600: my ($arrayref) = @_;
1.265 albertel 4601: my $result='__ARRAY_REF__';
1.204 albertel 4602: foreach my $elem (@$arrayref) {
1.265 albertel 4603: if(ref($elem) eq 'ARRAY') {
4604: $result.=&arrayref2str($elem).'&';
4605: } elsif(ref($elem) eq 'HASH') {
4606: $result.=&hashref2str($elem).'&';
4607: } elsif(ref($elem)) {
4608: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4609: } else {
4610: $result.=&escape($elem).'&';
4611: }
4612: }
4613: $result=~s/\&$//;
1.265 albertel 4614: $result .= '__END_ARRAY_REF__';
1.204 albertel 4615: return $result;
4616: }
4617:
1.168 albertel 4618: sub hash2str {
1.204 albertel 4619: my (%hash) = @_;
4620: my $result=&hashref2str(\%hash);
1.265 albertel 4621: $result=~s/^__HASH_REF__//;
4622: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4623: return $result;
4624: }
4625:
4626: sub hashref2str {
4627: my ($hashref)=@_;
1.265 albertel 4628: my $result='__HASH_REF__';
1.800 albertel 4629: foreach my $key (sort(keys(%$hashref))) {
4630: if (ref($key) eq 'ARRAY') {
4631: $result.=&arrayref2str($key).'=';
4632: } elsif (ref($key) eq 'HASH') {
4633: $result.=&hashref2str($key).'=';
4634: } elsif (ref($key)) {
1.265 albertel 4635: $result.='=';
1.800 albertel 4636: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4637: } else {
1.1132 raeburn 4638: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4639: }
4640:
1.800 albertel 4641: if(ref($hashref->{$key}) eq 'ARRAY') {
4642: $result.=&arrayref2str($hashref->{$key}).'&';
4643: } elsif(ref($hashref->{$key}) eq 'HASH') {
4644: $result.=&hashref2str($hashref->{$key}).'&';
4645: } elsif(ref($hashref->{$key})) {
1.265 albertel 4646: $result.='&';
1.800 albertel 4647: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4648: } else {
1.800 albertel 4649: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4650: }
4651: }
1.168 albertel 4652: $result=~s/\&$//;
1.265 albertel 4653: $result .= '__END_HASH_REF__';
1.168 albertel 4654: return $result;
4655: }
4656:
4657: sub str2hash {
1.265 albertel 4658: my ($string)=@_;
4659: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4660: return %$hash;
4661: }
4662:
4663: sub str2hashref {
1.168 albertel 4664: my ($string) = @_;
1.265 albertel 4665:
4666: my %hash;
4667:
4668: if($string !~ /^__HASH_REF__/) {
4669: if (! ($string eq '' || !defined($string))) {
4670: $hash{'error'}='Not hash reference';
4671: }
4672: return (\%hash, $string);
4673: }
4674:
4675: $string =~ s/^__HASH_REF__//;
4676:
4677: while($string !~ /^__END_HASH_REF__/) {
4678: #key
4679: my $key='';
4680: if($string =~ /^__HASH_REF__/) {
4681: ($key, $string)=&str2hashref($string);
4682: if(defined($key->{'error'})) {
4683: $hash{'error'}='Bad data';
4684: return (\%hash, $string);
4685: }
4686: } elsif($string =~ /^__ARRAY_REF__/) {
4687: ($key, $string)=&str2arrayref($string);
4688: if($key->[0] eq 'Array reference error') {
4689: $hash{'error'}='Bad data';
4690: return (\%hash, $string);
4691: }
4692: } else {
4693: $string =~ s/^(.*?)=//;
1.267 albertel 4694: $key=&unescape($1);
1.265 albertel 4695: }
4696: $string =~ s/^=//;
4697:
4698: #value
4699: my $value='';
4700: if($string =~ /^__HASH_REF__/) {
4701: ($value, $string)=&str2hashref($string);
4702: if(defined($value->{'error'})) {
4703: $hash{'error'}='Bad data';
4704: return (\%hash, $string);
4705: }
4706: } elsif($string =~ /^__ARRAY_REF__/) {
4707: ($value, $string)=&str2arrayref($string);
4708: if($value->[0] eq 'Array reference error') {
4709: $hash{'error'}='Bad data';
4710: return (\%hash, $string);
4711: }
4712: } else {
4713: $value=&get_scalar(\$string,'__END_HASH_REF__');
4714: }
4715: $string =~ s/^&//;
4716:
4717: $hash{$key}=$value;
1.204 albertel 4718: }
1.265 albertel 4719:
4720: $string =~ s/^__END_HASH_REF__//;
4721:
4722: return (\%hash, $string);
1.204 albertel 4723: }
4724:
4725: sub str2array {
1.265 albertel 4726: my ($string)=@_;
4727: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4728: return @$array;
4729: }
4730:
4731: sub str2arrayref {
1.204 albertel 4732: my ($string) = @_;
1.265 albertel 4733: my @array;
4734:
4735: if($string !~ /^__ARRAY_REF__/) {
4736: if (! ($string eq '' || !defined($string))) {
4737: $array[0]='Array reference error';
4738: }
4739: return (\@array, $string);
4740: }
4741:
4742: $string =~ s/^__ARRAY_REF__//;
4743:
4744: while($string !~ /^__END_ARRAY_REF__/) {
4745: my $value='';
4746: if($string =~ /^__HASH_REF__/) {
4747: ($value, $string)=&str2hashref($string);
4748: if(defined($value->{'error'})) {
4749: $array[0] ='Array reference error';
4750: return (\@array, $string);
4751: }
4752: } elsif($string =~ /^__ARRAY_REF__/) {
4753: ($value, $string)=&str2arrayref($string);
4754: if($value->[0] eq 'Array reference error') {
4755: $array[0] ='Array reference error';
4756: return (\@array, $string);
4757: }
4758: } else {
4759: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4760: }
4761: $string =~ s/^&//;
4762:
4763: push(@array, $value);
1.191 harris41 4764: }
1.265 albertel 4765:
4766: $string =~ s/^__END_ARRAY_REF__//;
4767:
4768: return (\@array, $string);
1.168 albertel 4769: }
4770:
1.167 albertel 4771: # -------------------------------------------------------------------Temp Store
4772:
1.168 albertel 4773: sub tmpreset {
4774: my ($symb,$namespace,$domain,$stuname) = @_;
4775: if (!$symb) {
4776: $symb=&symbread();
1.620 albertel 4777: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4778: }
4779: $symb=escape($symb);
4780:
1.620 albertel 4781: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4782: $namespace=~s/\//\_/g;
4783: $namespace=~s/\W//g;
4784:
1.620 albertel 4785: if (!$domain) { $domain=$env{'user.domain'}; }
4786: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4787: if ($domain eq 'public' && $stuname eq 'public') {
4788: $stuname=$ENV{'REMOTE_ADDR'};
4789: }
1.1117 foxr 4790: my $path=LONCAPA::tempdir();
1.168 albertel 4791: my %hash;
4792: if (tie(%hash,'GDBM_File',
4793: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4794: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4795: foreach my $key (keys(%hash)) {
1.180 albertel 4796: if ($key=~ /:$symb/) {
1.168 albertel 4797: delete($hash{$key});
4798: }
4799: }
4800: }
4801: }
4802:
1.167 albertel 4803: sub tmpstore {
1.168 albertel 4804: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4805:
4806: if (!$symb) {
4807: $symb=&symbread();
1.620 albertel 4808: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4809: }
4810: $symb=escape($symb);
4811:
4812: if (!$namespace) {
4813: # I don't think we would ever want to store this for a course.
4814: # it seems this will only be used if we don't have a course.
1.620 albertel 4815: #$namespace=$env{'request.course.id'};
1.168 albertel 4816: #if (!$namespace) {
1.620 albertel 4817: $namespace=$env{'request.state'};
1.168 albertel 4818: #}
4819: }
4820: $namespace=~s/\//\_/g;
4821: $namespace=~s/\W//g;
1.620 albertel 4822: if (!$domain) { $domain=$env{'user.domain'}; }
4823: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4824: if ($domain eq 'public' && $stuname eq 'public') {
4825: $stuname=$ENV{'REMOTE_ADDR'};
4826: }
1.168 albertel 4827: my $now=time;
4828: my %hash;
1.1117 foxr 4829: my $path=LONCAPA::tempdir();
1.168 albertel 4830: if (tie(%hash,'GDBM_File',
4831: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4832: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4833: $hash{"version:$symb"}++;
4834: my $version=$hash{"version:$symb"};
4835: my $allkeys='';
4836: foreach my $key (keys(%$storehash)) {
4837: $allkeys.=$key.':';
1.591 albertel 4838: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4839: }
4840: $hash{"$version:$symb:timestamp"}=$now;
4841: $allkeys.='timestamp';
4842: $hash{"$version:keys:$symb"}=$allkeys;
4843: if (untie(%hash)) {
4844: return 'ok';
4845: } else {
4846: return "error:$!";
4847: }
4848: } else {
4849: return "error:$!";
4850: }
4851: }
1.167 albertel 4852:
1.168 albertel 4853: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4854:
1.168 albertel 4855: sub tmprestore {
4856: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4857:
1.168 albertel 4858: if (!$symb) {
4859: $symb=&symbread();
1.620 albertel 4860: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4861: }
4862: $symb=escape($symb);
4863:
1.620 albertel 4864: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4865:
1.620 albertel 4866: if (!$domain) { $domain=$env{'user.domain'}; }
4867: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4868: if ($domain eq 'public' && $stuname eq 'public') {
4869: $stuname=$ENV{'REMOTE_ADDR'};
4870: }
1.168 albertel 4871: my %returnhash;
4872: $namespace=~s/\//\_/g;
4873: $namespace=~s/\W//g;
4874: my %hash;
1.1117 foxr 4875: my $path=LONCAPA::tempdir();
1.168 albertel 4876: if (tie(%hash,'GDBM_File',
4877: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4878: &GDBM_READER(),0640)) {
1.168 albertel 4879: my $version=$hash{"version:$symb"};
4880: $returnhash{'version'}=$version;
4881: my $scope;
4882: for ($scope=1;$scope<=$version;$scope++) {
4883: my $vkeys=$hash{"$scope:keys:$symb"};
4884: my @keys=split(/:/,$vkeys);
4885: my $key;
4886: $returnhash{"$scope:keys"}=$vkeys;
4887: foreach $key (@keys) {
1.591 albertel 4888: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4889: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4890: }
4891: }
1.168 albertel 4892: if (!(untie(%hash))) {
4893: return "error:$!";
4894: }
4895: } else {
4896: return "error:$!";
4897: }
4898: return %returnhash;
1.167 albertel 4899: }
4900:
1.9 www 4901: # ----------------------------------------------------------------------- Store
4902:
4903: sub store {
1.124 www 4904: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4905: my $home='';
4906:
1.168 albertel 4907: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4908:
1.213 www 4909: $symb=&symbclean($symb);
1.122 albertel 4910: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4911:
1.620 albertel 4912: if (!$domain) { $domain=$env{'user.domain'}; }
4913: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4914:
4915: &devalidate($symb,$stuname,$domain);
1.109 www 4916:
4917: $symb=escape($symb);
1.187 www 4918: if (!$namespace) {
1.620 albertel 4919: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4920: return '';
4921: }
4922: }
1.620 albertel 4923: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4924:
4925: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4926: $$storehash{'host'}=$perlvar{'lonHostID'};
4927:
1.12 www 4928: my $namevalue='';
1.800 albertel 4929: foreach my $key (keys(%$storehash)) {
4930: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4931: }
1.12 www 4932: $namevalue=~s/\&$//;
1.187 www 4933: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4934: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4935: }
4936:
1.47 www 4937: # -------------------------------------------------------------- Critical Store
4938:
4939: sub cstore {
1.124 www 4940: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4941: my $home='';
4942:
1.168 albertel 4943: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4944:
1.213 www 4945: $symb=&symbclean($symb);
1.122 albertel 4946: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4947:
1.620 albertel 4948: if (!$domain) { $domain=$env{'user.domain'}; }
4949: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4950:
4951: &devalidate($symb,$stuname,$domain);
1.109 www 4952:
4953: $symb=escape($symb);
1.187 www 4954: if (!$namespace) {
1.620 albertel 4955: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4956: return '';
4957: }
4958: }
1.620 albertel 4959: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4960:
4961: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4962: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4963:
1.47 www 4964: my $namevalue='';
1.800 albertel 4965: foreach my $key (keys(%$storehash)) {
4966: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4967: }
1.47 www 4968: $namevalue=~s/\&$//;
1.187 www 4969: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4970: return critical
4971: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4972: }
4973:
1.9 www 4974: # --------------------------------------------------------------------- Restore
4975:
4976: sub restore {
1.124 www 4977: my ($symb,$namespace,$domain,$stuname) = @_;
4978: my $home='';
4979:
1.168 albertel 4980: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4981:
1.122 albertel 4982: if (!$symb) {
1.1172.2.26 raeburn 4983: return if ($namespace eq 'courserequests');
4984: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4985: } else {
1.1172.2.26 raeburn 4986: unless ($namespace eq 'courserequests') {
4987: $symb=&escape(&symbclean($symb));
4988: }
1.122 albertel 4989: }
1.188 www 4990: if (!$namespace) {
1.620 albertel 4991: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4992: return '';
4993: }
4994: }
1.620 albertel 4995: if (!$domain) { $domain=$env{'user.domain'}; }
4996: if (!$stuname) { $stuname=$env{'user.name'}; }
4997: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4998: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4999:
1.12 www 5000: my %returnhash=();
1.800 albertel 5001: foreach my $line (split(/\&/,$answer)) {
5002: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5003: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5004: }
1.75 www 5005: my $version;
5006: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5007: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5008: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5009: }
1.75 www 5010: }
1.13 www 5011: return %returnhash;
1.34 www 5012: }
5013:
5014: # ---------------------------------------------------------- Course Description
1.1118 foxr 5015: #
5016: #
1.34 www 5017:
5018: sub coursedescription {
1.731 albertel 5019: my ($courseid,$args)=@_;
1.34 www 5020: $courseid=~s/^\///;
1.49 www 5021: $courseid=~s/\_/\//g;
1.34 www 5022: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5023: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5024: my $normalid=$cdomain.'_'.$cnum;
5025: # need to always cache even if we get errors otherwise we keep
5026: # trying and trying and trying to get the course description.
5027: my %envhash=();
5028: my %returnhash=();
1.731 albertel 5029:
5030: my $expiretime=600;
5031: if ($env{'request.course.id'} eq $normalid) {
5032: $expiretime=120;
5033: }
5034:
5035: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5036: if (!$args->{'freshen_cache'}
5037: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5038: foreach my $key (keys(%env)) {
5039: next if ($key !~ /^\Q$prefix\E(.*)/);
5040: my ($setting) = $1;
5041: $returnhash{$setting} = $env{$key};
5042: }
5043: return %returnhash;
5044: }
5045:
1.1118 foxr 5046: # get the data again
5047:
1.731 albertel 5048: if (!$args->{'one_time'}) {
5049: $envhash{'course.'.$normalid.'.last_cache'}=time;
5050: }
1.811 albertel 5051:
1.34 www 5052: if ($chome ne 'no_host') {
1.302 albertel 5053: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5054: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5055: my $username = $env{'user.name'}; # Defult username
5056: if(defined $args->{'user'}) {
5057: $username = $args->{'user'};
5058: }
1.129 albertel 5059: $returnhash{'home'}= $chome;
5060: $returnhash{'domain'} = $cdomain;
5061: $returnhash{'num'} = $cnum;
1.741 raeburn 5062: if (!defined($returnhash{'type'})) {
5063: $returnhash{'type'} = 'Course';
5064: }
1.130 albertel 5065: while (my ($name,$value) = each %returnhash) {
1.53 www 5066: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5067: }
1.270 www 5068: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5069: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5070: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5071: $envhash{'course.'.$normalid.'.home'}=$chome;
5072: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5073: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5074: }
5075: }
1.731 albertel 5076: if (!$args->{'one_time'}) {
1.949 raeburn 5077: &appenv(\%envhash);
1.731 albertel 5078: }
1.302 albertel 5079: return %returnhash;
1.461 www 5080: }
5081:
1.1080 raeburn 5082: sub update_released_required {
5083: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5084: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5085: $cid = $env{'request.course.id'};
5086: $cdom = $env{'course.'.$cid.'.domain'};
5087: $cnum = $env{'course.'.$cid.'.num'};
5088: $chome = $env{'course.'.$cid.'.home'};
5089: }
5090: if ($needsrelease) {
5091: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5092: my $needsupdate;
5093: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5094: $needsupdate = 1;
5095: } else {
5096: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5097: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5098: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5099: $needsupdate = 1;
5100: }
5101: }
5102: if ($needsupdate) {
5103: my %needshash = (
5104: 'internal.releaserequired' => $needsrelease,
5105: );
5106: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5107: if ($putresult eq 'ok') {
5108: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5109: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5110: if (ref($crsinfo{$cid}) eq 'HASH') {
5111: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5112: &courseidput($cdom,\%crsinfo,$chome,'notime');
5113: }
5114: }
5115: }
5116: }
5117: return;
5118: }
5119:
1.461 www 5120: # -------------------------------------------------See if a user is privileged
5121:
5122: sub privileged {
1.1172.2.23 raeburn 5123: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5124: my $now = time;
1.1172.2.23 raeburn 5125: my $roles;
5126: if (ref($possroles) eq 'ARRAY') {
5127: $roles = $possroles;
5128: } else {
5129: $roles = ['dc','su'];
5130: }
5131: if (ref($possdomains) eq 'ARRAY') {
5132: my %privileged = &privileged_by_domain($possdomains,$roles);
5133: foreach my $dom (@{$possdomains}) {
5134: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5135: (ref($privileged{$dom}) eq 'HASH')) {
5136: foreach my $role (@{$roles}) {
5137: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5138: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5139: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5140: return 1 unless (($end && $end < $now) ||
5141: ($start && $start > $now));
5142: }
5143: }
5144: }
5145: }
5146: }
5147: } else {
5148: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5149: my $now = time;
1.1170 droeschl 5150:
1.1172.2.23 raeburn 5151: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5152: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5153: if (grep(/^\Q$trole\E$/,@{$roles})) {
5154: return 1 unless ($tend && $tend < $now)
5155: or ($tstart && $tstart > $now);
1.1170 droeschl 5156: }
1.1172.2.23 raeburn 5157: }
5158: }
1.461 www 5159: return 0;
1.9 www 5160: }
1.1 albertel 5161:
1.1172.2.23 raeburn 5162: sub privileged_by_domain {
5163: my ($domains,$roles) = @_;
5164: my %privileged = ();
5165: my $cachetime = 60*60*24;
5166: my $now = time;
5167: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5168: return %privileged;
5169: }
5170: foreach my $dom (@{$domains}) {
5171: next if (ref($privileged{$dom}) eq 'HASH');
5172: my $needroles;
5173: foreach my $role (@{$roles}) {
5174: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5175: if (defined($cached)) {
5176: if (ref($result) eq 'HASH') {
5177: $privileged{$dom}{$role} = $result;
5178: }
5179: } else {
5180: $needroles = 1;
5181: }
5182: }
5183: if ($needroles) {
5184: my %dompersonnel = &get_domain_roles($dom,$roles);
5185: $privileged{$dom} = {};
5186: foreach my $server (keys(%dompersonnel)) {
5187: if (ref($dompersonnel{$server}) eq 'HASH') {
5188: foreach my $item (keys(%{$dompersonnel{$server}})) {
5189: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5190: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5191: next if ($end && $end < $now);
5192: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5193: $dompersonnel{$server}{$item};
5194: }
5195: }
5196: }
5197: if (ref($privileged{$dom}) eq 'HASH') {
5198: foreach my $role (@{$roles}) {
5199: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5200: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5201: } else {
5202: my %hash = ();
5203: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5204: }
5205: }
5206: }
5207: }
5208: }
5209: return %privileged;
5210: }
5211:
1.103 harris41 5212: # -------------------------------------------------------- Get user privileges
1.11 www 5213:
5214: sub rolesinit {
1.1169 droeschl 5215: my ($domain, $username) = @_;
5216: my %userroles = ('user.login.time' => time);
5217: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5218:
5219: # firstaccess and timerinterval are related to timed maps/resources.
5220: # also, blocking can be triggered by an activating timer
5221: # it's saved in the user's %env.
5222: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5223: my %timerinterval = &dump('timerinterval', $domain, $username);
5224: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5225: %timerintchk, %timerintenv);
5226:
1.1162 raeburn 5227: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5228: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5229: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5230: }
1.1169 droeschl 5231:
1.1162 raeburn 5232: foreach my $key (keys(%timerinterval)) {
5233: my ($cid,$rest) = split(/\0/,$key);
5234: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5235: }
1.1169 droeschl 5236:
1.11 www 5237: my %allroles=();
1.1162 raeburn 5238: my %allgroups=();
1.11 www 5239:
1.1169 droeschl 5240: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5241: my $role = $rolesdump{$area};
5242: $area =~ s/\_\w\w$//;
5243:
5244: my ($trole, $tend, $tstart, $group_privs);
5245:
5246: if ($role =~ /^cr/) {
5247: # Custom role, defined by a user
5248: # e.g., user.role.cr/msu/smith/mynewrole
5249: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5250: $trole = $1;
5251: ($tend, $tstart) = split('_', $2);
5252: } else {
5253: $trole = $role;
5254: }
5255: } elsif ($role =~ m|^gr/|) {
5256: # Role of member in a group, defined within a course/community
5257: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5258: ($trole, $tend, $tstart) = split(/_/, $role);
5259: next if $tstart eq '-1';
5260: ($trole, $group_privs) = split(/\//, $trole);
5261: $group_privs = &unescape($group_privs);
5262: } else {
5263: # Just a normal role, defined in roles.tab
5264: ($trole, $tend, $tstart) = split(/_/,$role);
5265: }
5266:
5267: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5268: $username);
5269: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5270:
5271: # role expired or not available yet?
5272: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5273: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5274:
5275: next if $area eq '' or $trole eq '';
5276:
5277: my $spec = "$trole.$area";
5278: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5279:
5280: if ($trole =~ /^cr\//) {
5281: # Custom role, defined by a user
5282: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5283: } elsif ($trole eq 'gr') {
5284: # Role of a member in a group, defined within a course/community
5285: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5286: next;
5287: } else {
5288: # Normal role, defined in roles.tab
5289: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5290: }
5291:
5292: my $cid = $tdomain.'_'.$trest;
5293: unless ($firstaccchk{$cid}) {
5294: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5295: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5296: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5297: $coursetimerstarts{$cid}{$item};
5298: }
5299: }
5300: $firstaccchk{$cid} = 1;
5301: }
5302: unless ($timerintchk{$cid}) {
5303: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5304: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5305: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5306: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5307: }
1.12 www 5308: }
1.1169 droeschl 5309: $timerintchk{$cid} = 1;
1.191 harris41 5310: }
1.11 www 5311: }
1.1169 droeschl 5312:
5313: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5314: \%allroles, \%allgroups);
5315: $env{'user.adv'} = $userroles{'user.adv'};
5316:
1.1162 raeburn 5317: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5318: }
5319:
1.567 raeburn 5320: sub set_arearole {
1.1172.2.19 raeburn 5321: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5322: unless ($nolog) {
1.567 raeburn 5323: # log the associated role with the area
1.1172.2.19 raeburn 5324: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5325: }
1.743 albertel 5326: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5327: }
5328:
5329: sub custom_roleprivs {
5330: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5331: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5332: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5333: if (&hostname($homsvr) ne '') {
1.567 raeburn 5334: my ($rdummy,$roledef)=
5335: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5336: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5337: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5338: if (defined($syspriv)) {
1.1043 raeburn 5339: if ($trest =~ /^$match_community$/) {
5340: $syspriv =~ s/bre\&S//;
5341: }
1.567 raeburn 5342: $$allroles{'cm./'}.=':'.$syspriv;
5343: $$allroles{$spec.'./'}.=':'.$syspriv;
5344: }
5345: if ($tdomain ne '') {
5346: if (defined($dompriv)) {
5347: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5348: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5349: }
5350: if (($trest ne '') && (defined($coursepriv))) {
5351: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5352: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5353: }
5354: }
5355: }
5356: }
5357: }
5358:
1.678 raeburn 5359: sub group_roleprivs {
5360: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5361: my $access = 1;
5362: my $now = time;
5363: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5364: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5365: if ($access) {
1.811 albertel 5366: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5367: $$allgroups{$course}{$group} .=':'.$group_privs;
5368: }
5369: }
1.567 raeburn 5370:
5371: sub standard_roleprivs {
5372: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5373: if (defined($pr{$trole.':s'})) {
5374: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5375: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5376: }
5377: if ($tdomain ne '') {
5378: if (defined($pr{$trole.':d'})) {
5379: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5380: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5381: }
5382: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5383: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5384: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5385: }
5386: }
5387: }
5388:
5389: sub set_userprivs {
1.1064 raeburn 5390: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5391: my $author=0;
5392: my $adv=0;
1.678 raeburn 5393: my %grouproles = ();
5394: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5395: my @groupkeys;
1.1000 raeburn 5396: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5397: push(@groupkeys,$role);
5398: }
5399: if (ref($groups_roles) eq 'HASH') {
5400: foreach my $key (keys(%{$groups_roles})) {
5401: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5402: push(@groupkeys,$key);
5403: }
5404: }
5405: }
5406: if (@groupkeys > 0) {
5407: foreach my $role (@groupkeys) {
5408: my ($trole,$area,$sec,$extendedarea);
5409: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5410: $trole = $1;
5411: $area = $2;
5412: $sec = $3;
5413: $extendedarea = $area.$sec;
5414: if (exists($$allgroups{$area})) {
5415: foreach my $group (keys(%{$$allgroups{$area}})) {
5416: my $spec = $trole.'.'.$extendedarea;
5417: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5418: $$allgroups{$area}{$group};
1.1064 raeburn 5419: }
1.678 raeburn 5420: }
5421: }
5422: }
5423: }
5424: }
1.800 albertel 5425: foreach my $group (keys(%grouproles)) {
5426: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5427: }
1.800 albertel 5428: foreach my $role (keys(%{$allroles})) {
5429: my %thesepriv;
1.941 raeburn 5430: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5431: foreach my $item (split(/:/,$$allroles{$role})) {
5432: if ($item ne '') {
5433: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5434: if ($restrictions eq '') {
5435: $thesepriv{$privilege}='F';
5436: } elsif ($thesepriv{$privilege} ne 'F') {
5437: $thesepriv{$privilege}.=$restrictions;
5438: }
5439: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5440: }
5441: }
5442: my $thesestr='';
1.1104 raeburn 5443: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5444: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5445: }
5446: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5447: }
5448: return ($author,$adv);
5449: }
5450:
1.994 raeburn 5451: sub role_status {
1.1104 raeburn 5452: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5453: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5454: my ($one,$two) = split(m{\./},$rolekey,2);
5455: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5456: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5457: $$where = '/'.$two;
1.994 raeburn 5458: $$trolecode=$$role.'.'.$$where;
5459: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5460: $$tstatus='is';
1.1104 raeburn 5461: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5462: $$tstatus='future';
1.1034 raeburn 5463: if ($$tstart<$now) {
5464: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5465: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5466: my (%allroles,%allgroups,$group_privs,
5467: %groups_roles,@rolecodes);
1.1002 raeburn 5468: my %userroles = (
5469: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5470: );
1.1064 raeburn 5471: @rolecodes = ('cm');
1.1002 raeburn 5472: my $spec=$$role.'.'.$$where;
5473: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5474: if ($$role =~ /^cr\//) {
5475: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5476: push(@rolecodes,'cr');
1.1002 raeburn 5477: } elsif ($$role eq 'gr') {
1.1064 raeburn 5478: push(@rolecodes,$$role);
1.1002 raeburn 5479: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5480: $env{'user.name'});
1.1064 raeburn 5481: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5482: (undef,my $group_privs) = split(/\//,$trole);
5483: $group_privs = &unescape($group_privs);
5484: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5485: 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 5486: &get_groups_roles($tdomain,$trest,
5487: \%course_roles,\@rolecodes,
5488: \%groups_roles);
1.1002 raeburn 5489: } else {
1.1064 raeburn 5490: push(@rolecodes,$$role);
1.1002 raeburn 5491: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5492: }
1.1064 raeburn 5493: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5494: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5495: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5496: }
5497: }
1.1034 raeburn 5498: $$tstatus = 'is';
1.1002 raeburn 5499: }
1.994 raeburn 5500: }
5501: if ($$tend) {
1.1104 raeburn 5502: if ($$tend<$update) {
1.994 raeburn 5503: $$tstatus='expired';
5504: } elsif ($$tend<$now) {
5505: $$tstatus='will_not';
5506: }
5507: }
5508: }
5509: }
5510: }
5511:
1.1104 raeburn 5512: sub get_groups_roles {
5513: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5514: return unless((ref($cdom_courseroles) eq 'HASH') &&
5515: (ref($rolecodes) eq 'ARRAY') &&
5516: (ref($groups_roles) eq 'HASH'));
5517: if (keys(%{$cdom_courseroles}) > 0) {
5518: my ($cnum) = ($rest =~ /^($match_courseid)/);
5519: if ($cdom ne '' && $cnum ne '') {
5520: foreach my $key (keys(%{$cdom_courseroles})) {
5521: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5522: my $crsrole = $1;
5523: my $crssec = $2;
5524: if ($crsrole =~ /^cr/) {
5525: unless (grep(/^cr$/,@{$rolecodes})) {
5526: push(@{$rolecodes},'cr');
5527: }
5528: } else {
5529: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5530: push(@{$rolecodes},$crsrole);
5531: }
5532: }
5533: my $rolekey = "$crsrole./$cdom/$cnum";
5534: if ($crssec ne '') {
5535: $rolekey .= "/$crssec";
5536: }
5537: $rolekey .= './';
5538: $groups_roles->{$rolekey} = $rolecodes;
5539: }
5540: }
5541: }
5542: }
5543: return;
5544: }
5545:
5546: sub delete_env_groupprivs {
5547: my ($where,$courseroles,$possroles) = @_;
5548: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5549: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5550: unless (ref($courseroles->{$udom}) eq 'HASH') {
5551: %{$courseroles->{$udom}} =
5552: &get_my_roles('','','userroles',['active'],
5553: $possroles,[$udom],1);
5554: }
5555: if (ref($courseroles->{$udom}) eq 'HASH') {
5556: foreach my $item (keys(%{$courseroles->{$udom}})) {
5557: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5558: my $area = '/'.$cdom.'/'.$cnum;
5559: my $privkey = "user.priv.$crsrole.$area";
5560: if ($crssec ne '') {
5561: $privkey .= '/'.$crssec;
5562: }
5563: $privkey .= ".$area/$group";
5564: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5565: }
5566: }
5567: return;
5568: }
5569:
1.994 raeburn 5570: sub check_adhoc_privs {
1.1104 raeburn 5571: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5572: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5573: my $setprivs;
1.994 raeburn 5574: if ($env{$cckey}) {
5575: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5576: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5577: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5578: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5579: $setprivs = 1;
1.994 raeburn 5580: }
5581: } else {
1.1088 raeburn 5582: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5583: $setprivs = 1;
1.994 raeburn 5584: }
1.1172.2.9 raeburn 5585: return $setprivs;
1.994 raeburn 5586: }
5587:
5588: sub set_adhoc_privileges {
5589: # role can be cc or ca
1.1088 raeburn 5590: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5591: my $area = '/'.$dcdom.'/'.$pickedcourse;
5592: my $spec = $role.'.'.$area;
5593: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5594: $env{'user.name'},1);
1.994 raeburn 5595: my %ccrole = ();
5596: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5597: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5598: &appenv(\%userroles,[$role,'cm']);
5599: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5600: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5601: &appenv( {'request.role' => $spec,
5602: 'request.role.domain' => $dcdom,
5603: 'request.course.sec' => ''
5604: }
5605: );
5606: my $tadv=0;
5607: if (&allowed('adv') eq 'F') { $tadv=1; }
5608: &appenv({'request.role.adv' => $tadv});
5609: }
1.994 raeburn 5610: }
5611:
1.12 www 5612: # --------------------------------------------------------------- get interface
5613:
5614: sub get {
1.131 albertel 5615: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5616: my $items='';
1.800 albertel 5617: foreach my $item (@$storearr) {
5618: $items.=&escape($item).'&';
1.191 harris41 5619: }
1.12 www 5620: $items=~s/\&$//;
1.620 albertel 5621: if (!$udomain) { $udomain=$env{'user.domain'}; }
5622: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5623: my $uhome=&homeserver($uname,$udomain);
5624:
1.133 albertel 5625: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5626: my @pairs=split(/\&/,$rep);
1.273 albertel 5627: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5628: return @pairs;
5629: }
1.15 www 5630: my %returnhash=();
1.42 www 5631: my $i=0;
1.800 albertel 5632: foreach my $item (@$storearr) {
5633: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5634: $i++;
1.191 harris41 5635: }
1.15 www 5636: return %returnhash;
1.27 www 5637: }
5638:
5639: # --------------------------------------------------------------- del interface
5640:
5641: sub del {
1.133 albertel 5642: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5643: my $items='';
1.800 albertel 5644: foreach my $item (@$storearr) {
5645: $items.=&escape($item).'&';
1.191 harris41 5646: }
1.984 neumanie 5647:
1.27 www 5648: $items=~s/\&$//;
1.620 albertel 5649: if (!$udomain) { $udomain=$env{'user.domain'}; }
5650: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5651: my $uhome=&homeserver($uname,$udomain);
5652: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5653: }
5654:
5655: # -------------------------------------------------------------- dump interface
5656:
1.1172.2.22 raeburn 5657: sub unserialize {
5658: my ($rep, $escapedkeys) = @_;
5659:
5660: return {} if $rep =~ /^error/;
5661:
5662: my %returnhash=();
5663: foreach my $item (split(/\&/,$rep)) {
5664: my ($key, $value) = split(/=/, $item, 2);
5665: $key = unescape($key) unless $escapedkeys;
5666: next if $key =~ /^error: 2 /;
5667: $returnhash{$key} = &thaw_unescape($value);
5668: }
5669: return \%returnhash;
5670: }
5671:
5672: # see Lond::dump_with_regexp
5673: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5674: sub dump {
1.1172.2.22 raeburn 5675: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5676: if (!$udomain) { $udomain=$env{'user.domain'}; }
5677: if (!$uname) { $uname=$env{'user.name'}; }
5678: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5679:
1.1172.2.22 raeburn 5680: my $reply;
5681: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5682: # user is hosted on this machine
5683: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5684: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5685: return %{&unserialize($reply, $escapedkeys)};
5686: }
1.755 albertel 5687: if ($regexp) {
5688: $regexp=&escape($regexp);
5689: } else {
5690: $regexp='.';
5691: }
1.1166 raeburn 5692: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5693: my @pairs=split(/\&/,$rep);
5694: my %returnhash=();
1.1098 foxr 5695: if (!($rep =~ /^error/ )) {
5696: foreach my $item (@pairs) {
5697: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5698: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5699: next if ($key =~ /^error: 2 /);
5700: $returnhash{$key}=&thaw_unescape($value);
5701: }
1.755 albertel 5702: }
5703: return %returnhash;
1.407 www 5704: }
5705:
1.1098 foxr 5706:
1.717 albertel 5707: # --------------------------------------------------------- dumpstore interface
5708:
5709: sub dumpstore {
5710: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5711: # same as dump but keys must be escaped. They may contain colon separated
5712: # lists of values that may themself contain colons (e.g. symbs).
5713: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5714: }
5715:
1.407 www 5716: # -------------------------------------------------------------- keys interface
5717:
5718: sub getkeys {
5719: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5720: if (!$udomain) { $udomain=$env{'user.domain'}; }
5721: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5722: my $uhome=&homeserver($uname,$udomain);
5723: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5724: my @keyarray=();
1.800 albertel 5725: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5726: next if ($key =~ /^error: 2 /);
1.800 albertel 5727: push(@keyarray,&unescape($key));
1.407 www 5728: }
5729: return @keyarray;
1.318 matthew 5730: }
5731:
1.319 matthew 5732: # --------------------------------------------------------------- currentdump
5733: sub currentdump {
1.328 matthew 5734: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5735: $courseid = $env{'request.course.id'} if (! defined($courseid));
5736: $sdom = $env{'user.domain'} if (! defined($sdom));
5737: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5738: my $uhome = &homeserver($sname,$sdom);
5739: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5740: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5741: #
1.318 matthew 5742: my %returnhash=();
1.319 matthew 5743: #
5744: if ($rep eq "unknown_cmd") {
5745: # an old lond will not know currentdump
5746: # Do a dump and make it look like a currentdump
1.822 albertel 5747: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5748: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5749: my %hash = @tmp;
5750: @tmp=();
1.424 matthew 5751: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5752: } else {
5753: my @pairs=split(/\&/,$rep);
1.800 albertel 5754: foreach my $pair (@pairs) {
5755: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5756: my ($symb,$param) = split(/:/,$key);
5757: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5758: &thaw_unescape($value);
1.319 matthew 5759: }
1.191 harris41 5760: }
1.12 www 5761: return %returnhash;
1.424 matthew 5762: }
5763:
5764: sub convert_dump_to_currentdump{
5765: my %hash = %{shift()};
5766: my %returnhash;
5767: # Code ripped from lond, essentially. The only difference
5768: # here is the unescaping done by lonnet::dump(). Conceivably
5769: # we might run in to problems with parameter names =~ /^v\./
5770: while (my ($key,$value) = each(%hash)) {
5771: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5772: $symb = &unescape($symb);
5773: $param = &unescape($param);
1.424 matthew 5774: next if ($v eq 'version' || $symb eq 'keys');
5775: next if (exists($returnhash{$symb}) &&
5776: exists($returnhash{$symb}->{$param}) &&
5777: $returnhash{$symb}->{'v.'.$param} > $v);
5778: $returnhash{$symb}->{$param}=$value;
5779: $returnhash{$symb}->{'v.'.$param}=$v;
5780: }
5781: #
5782: # Remove all of the keys in the hashes which keep track of
5783: # the version of the parameter.
5784: while (my ($symb,$param_hash) = each(%returnhash)) {
5785: # use a foreach because we are going to delete from the hash.
5786: foreach my $key (keys(%$param_hash)) {
5787: delete($param_hash->{$key}) if ($key =~ /^v\./);
5788: }
5789: }
5790: return \%returnhash;
1.12 www 5791: }
5792:
1.627 albertel 5793: # ------------------------------------------------------ critical inc interface
5794:
5795: sub cinc {
5796: return &inc(@_,'critical');
5797: }
5798:
1.449 matthew 5799: # --------------------------------------------------------------- inc interface
5800:
5801: sub inc {
1.627 albertel 5802: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5803: if (!$udomain) { $udomain=$env{'user.domain'}; }
5804: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5805: my $uhome=&homeserver($uname,$udomain);
5806: my $items='';
5807: if (! ref($store)) {
5808: # got a single value, so use that instead
5809: $items = &escape($store).'=&';
5810: } elsif (ref($store) eq 'SCALAR') {
5811: $items = &escape($$store).'=&';
5812: } elsif (ref($store) eq 'ARRAY') {
5813: $items = join('=&',map {&escape($_);} @{$store});
5814: } elsif (ref($store) eq 'HASH') {
5815: while (my($key,$value) = each(%{$store})) {
5816: $items.= &escape($key).'='.&escape($value).'&';
5817: }
5818: }
5819: $items=~s/\&$//;
1.627 albertel 5820: if ($critical) {
5821: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5822: } else {
5823: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5824: }
1.449 matthew 5825: }
5826:
1.12 www 5827: # --------------------------------------------------------------- put interface
5828:
5829: sub put {
1.134 albertel 5830: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5831: if (!$udomain) { $udomain=$env{'user.domain'}; }
5832: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5833: my $uhome=&homeserver($uname,$udomain);
1.12 www 5834: my $items='';
1.800 albertel 5835: foreach my $item (keys(%$storehash)) {
5836: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5837: }
1.12 www 5838: $items=~s/\&$//;
1.134 albertel 5839: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5840: }
5841:
1.631 albertel 5842: # ------------------------------------------------------------ newput interface
5843:
5844: sub newput {
5845: my ($namespace,$storehash,$udomain,$uname)=@_;
5846: if (!$udomain) { $udomain=$env{'user.domain'}; }
5847: if (!$uname) { $uname=$env{'user.name'}; }
5848: my $uhome=&homeserver($uname,$udomain);
5849: my $items='';
5850: foreach my $key (keys(%$storehash)) {
5851: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5852: }
5853: $items=~s/\&$//;
5854: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5855: }
5856:
5857: # --------------------------------------------------------- putstore interface
5858:
1.524 raeburn 5859: sub putstore {
1.715 albertel 5860: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5861: if (!$udomain) { $udomain=$env{'user.domain'}; }
5862: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5863: my $uhome=&homeserver($uname,$udomain);
5864: my $items='';
1.715 albertel 5865: foreach my $key (keys(%$storehash)) {
5866: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5867: }
1.715 albertel 5868: $items=~s/\&$//;
1.716 albertel 5869: my $esc_symb=&escape($symb);
5870: my $esc_v=&escape($version);
1.715 albertel 5871: my $reply =
1.716 albertel 5872: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5873: $uhome);
5874: if ($reply eq 'unknown_cmd') {
1.716 albertel 5875: # gfall back to way things use to be done
1.715 albertel 5876: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5877: $uname);
1.524 raeburn 5878: }
1.715 albertel 5879: return $reply;
5880: }
5881:
5882: sub old_putstore {
1.716 albertel 5883: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5884: if (!$udomain) { $udomain=$env{'user.domain'}; }
5885: if (!$uname) { $uname=$env{'user.name'}; }
5886: my $uhome=&homeserver($uname,$udomain);
5887: my %newstorehash;
1.800 albertel 5888: foreach my $item (keys(%$storehash)) {
5889: my $key = $version.':'.&escape($symb).':'.$item;
5890: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5891: }
5892: my $items='';
5893: my %allitems = ();
1.800 albertel 5894: foreach my $item (keys(%newstorehash)) {
5895: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5896: my $key = $1.':keys:'.$2;
5897: $allitems{$key} .= $3.':';
5898: }
1.800 albertel 5899: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5900: }
1.800 albertel 5901: foreach my $item (keys(%allitems)) {
5902: $allitems{$item} =~ s/\:$//;
5903: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5904: }
5905: $items=~s/\&$//;
5906: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5907: }
5908:
1.47 www 5909: # ------------------------------------------------------ critical put interface
5910:
5911: sub cput {
1.134 albertel 5912: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5913: if (!$udomain) { $udomain=$env{'user.domain'}; }
5914: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5915: my $uhome=&homeserver($uname,$udomain);
1.47 www 5916: my $items='';
1.800 albertel 5917: foreach my $item (keys(%$storehash)) {
5918: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5919: }
1.47 www 5920: $items=~s/\&$//;
1.134 albertel 5921: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5922: }
5923:
5924: # -------------------------------------------------------------- eget interface
5925:
5926: sub eget {
1.133 albertel 5927: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5928: my $items='';
1.800 albertel 5929: foreach my $item (@$storearr) {
5930: $items.=&escape($item).'&';
1.191 harris41 5931: }
1.12 www 5932: $items=~s/\&$//;
1.620 albertel 5933: if (!$udomain) { $udomain=$env{'user.domain'}; }
5934: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5935: my $uhome=&homeserver($uname,$udomain);
5936: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5937: my @pairs=split(/\&/,$rep);
5938: my %returnhash=();
1.42 www 5939: my $i=0;
1.800 albertel 5940: foreach my $item (@$storearr) {
5941: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5942: $i++;
1.191 harris41 5943: }
1.12 www 5944: return %returnhash;
5945: }
5946:
1.667 albertel 5947: # ------------------------------------------------------------ tmpput interface
5948: sub tmpput {
1.802 raeburn 5949: my ($storehash,$server,$context)=@_;
1.667 albertel 5950: my $items='';
1.800 albertel 5951: foreach my $item (keys(%$storehash)) {
5952: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5953: }
5954: $items=~s/\&$//;
1.802 raeburn 5955: if (defined($context)) {
5956: $items .= ':'.&escape($context);
5957: }
1.667 albertel 5958: return &reply("tmpput:$items",$server);
5959: }
5960:
5961: # ------------------------------------------------------------ tmpget interface
5962: sub tmpget {
1.688 albertel 5963: my ($token,$server)=@_;
5964: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5965: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5966: my %returnhash;
5967: foreach my $item (split(/\&/,$rep)) {
5968: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5969: next if ($key =~ /^error: 2 /);
1.667 albertel 5970: $returnhash{&unescape($key)}=&thaw_unescape($value);
5971: }
5972: return %returnhash;
5973: }
5974:
1.1113 raeburn 5975: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5976: sub tmpdel {
5977: my ($token,$server)=@_;
5978: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5979: return &reply("tmpdel:$token",$server);
5980: }
5981:
1.1172.2.13 raeburn 5982: # ------------------------------------------------------------ get_timebased_id
5983:
5984: sub get_timebased_id {
5985: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5986: $maxtries) = @_;
5987: my ($newid,$error,$dellock);
5988: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5989: return ('','ok','invalid call to get suffix');
5990: }
5991:
5992: # set defaults for any optional args for which values were not supplied
5993: if ($who eq '') {
5994: $who = $env{'user.name'}.':'.$env{'user.domain'};
5995: }
5996: if (!$locktries) {
5997: $locktries = 3;
5998: }
5999: if (!$maxtries) {
6000: $maxtries = 10;
6001: }
6002:
6003: if (($cdom eq '') || ($cnum eq '')) {
6004: if ($env{'request.course.id'}) {
6005: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6006: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6007: }
6008: if (($cdom eq '') || ($cnum eq '')) {
6009: return ('','ok','call to get suffix not in course context');
6010: }
6011: }
6012:
6013: # construct locking item
6014: my $lockhash = {
6015: $prefix."\0".'locked_'.$keyid => $who,
6016: };
6017: my $tries = 0;
6018:
6019: # attempt to get lock on nohist_$namespace file
6020: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6021: while (($gotlock ne 'ok') && $tries <$locktries) {
6022: $tries ++;
6023: sleep 1;
6024: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6025: }
6026:
6027: # attempt to get unique identifier, based on current timestamp
6028: if ($gotlock eq 'ok') {
6029: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6030: my $id = time;
6031: $newid = $id;
6032: my $idtries = 0;
6033: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6034: if ($idtype eq 'concat') {
6035: $newid = $id.$idtries;
6036: } else {
6037: $newid ++;
6038: }
6039: $idtries ++;
6040: }
6041: if (!exists($inuse{$prefix."\0".$newid})) {
6042: my %new_item = (
6043: $prefix."\0".$newid => $who,
6044: );
6045: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6046: $cdom,$cnum);
6047: if ($putresult ne 'ok') {
6048: undef($newid);
6049: $error = 'error saving new item: '.$putresult;
6050: }
6051: } else {
6052: $error = ('error: no unique suffix available for the new item ');
6053: }
6054: # remove lock
6055: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6056: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6057: } else {
6058: $error = "error: could not obtain lockfile\n";
6059: $dellock = 'ok';
6060: }
6061: return ($newid,$dellock,$error);
6062: }
6063:
1.765 albertel 6064: # -------------------------------------------------- portfolio access checking
6065:
6066: sub portfolio_access {
1.766 albertel 6067: my ($requrl) = @_;
1.765 albertel 6068: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6069: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6070: if ($result) {
6071: my %setters;
6072: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6073: my ($startblock,$endblock) =
6074: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6075: if ($startblock && $endblock) {
6076: return 'B';
6077: }
6078: } else {
6079: my ($startblock,$endblock) =
6080: &Apache::loncommon::blockcheck(\%setters,'port');
6081: if ($startblock && $endblock) {
6082: return 'B';
6083: }
6084: }
6085: }
1.765 albertel 6086: if ($result eq 'ok') {
1.766 albertel 6087: return 'F';
1.765 albertel 6088: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6089: return 'A';
1.765 albertel 6090: }
1.766 albertel 6091: return '';
1.765 albertel 6092: }
6093:
6094: sub get_portfolio_access {
1.767 albertel 6095: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6096:
6097: if (!ref($access_hash)) {
6098: my $current_perms = &get_portfile_permissions($udom,$unum);
6099: my %access_controls = &get_access_controls($current_perms,$group,
6100: $file_name);
6101: $access_hash = $access_controls{$file_name};
6102: }
6103:
1.765 albertel 6104: my ($public,$guest,@domains,@users,@courses,@groups);
6105: my $now = time;
6106: if (ref($access_hash) eq 'HASH') {
6107: foreach my $key (keys(%{$access_hash})) {
6108: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6109: if ($start > $now) {
6110: next;
6111: }
6112: if ($end && $end<$now) {
6113: next;
6114: }
6115: if ($scope eq 'public') {
6116: $public = $key;
6117: last;
6118: } elsif ($scope eq 'guest') {
6119: $guest = $key;
6120: } elsif ($scope eq 'domains') {
6121: push(@domains,$key);
6122: } elsif ($scope eq 'users') {
6123: push(@users,$key);
6124: } elsif ($scope eq 'course') {
6125: push(@courses,$key);
6126: } elsif ($scope eq 'group') {
6127: push(@groups,$key);
6128: }
6129: }
6130: if ($public) {
6131: return 'ok';
6132: }
6133: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6134: if ($guest) {
6135: return $guest;
6136: }
6137: } else {
6138: if (@domains > 0) {
6139: foreach my $domkey (@domains) {
6140: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6141: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6142: return 'ok';
6143: }
6144: }
6145: }
6146: }
6147: if (@users > 0) {
6148: foreach my $userkey (@users) {
1.865 raeburn 6149: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6150: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6151: if (ref($item) eq 'HASH') {
6152: if (($item->{'uname'} eq $env{'user.name'}) &&
6153: ($item->{'udom'} eq $env{'user.domain'})) {
6154: return 'ok';
6155: }
6156: }
6157: }
6158: }
1.765 albertel 6159: }
6160: }
6161: my %roleshash;
6162: my @courses_and_groups = @courses;
6163: push(@courses_and_groups,@groups);
6164: if (@courses_and_groups > 0) {
6165: my (%allgroups,%allroles);
6166: my ($start,$end,$role,$sec,$group);
6167: foreach my $envkey (%env) {
1.1060 raeburn 6168: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6169: my $cid = $2.'_'.$3;
6170: if ($1 eq 'gr') {
6171: $group = $4;
6172: $allgroups{$cid}{$group} = $env{$envkey};
6173: } else {
6174: if ($4 eq '') {
6175: $sec = 'none';
6176: } else {
6177: $sec = $4;
6178: }
6179: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6180: }
1.811 albertel 6181: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6182: my $cid = $2.'_'.$3;
6183: if ($4 eq '') {
6184: $sec = 'none';
6185: } else {
6186: $sec = $4;
6187: }
6188: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6189: }
6190: }
6191: if (keys(%allroles) == 0) {
6192: return;
6193: }
6194: foreach my $key (@courses_and_groups) {
6195: my %content = %{$$access_hash{$key}};
6196: my $cnum = $content{'number'};
6197: my $cdom = $content{'domain'};
6198: my $cid = $cdom.'_'.$cnum;
6199: if (!exists($allroles{$cid})) {
6200: next;
6201: }
6202: foreach my $role_id (keys(%{$content{'roles'}})) {
6203: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6204: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6205: my @status = @{$content{'roles'}{$role_id}{'access'}};
6206: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6207: foreach my $role (keys(%{$allroles{$cid}})) {
6208: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6209: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6210: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6211: if (grep/^all$/,@sections) {
6212: return 'ok';
6213: } else {
6214: if (grep/^$sec$/,@sections) {
6215: return 'ok';
6216: }
6217: }
6218: }
6219: }
6220: if (keys(%{$allgroups{$cid}}) == 0) {
6221: if (grep/^none$/,@groups) {
6222: return 'ok';
6223: }
6224: } else {
6225: if (grep/^all$/,@groups) {
6226: return 'ok';
6227: }
6228: foreach my $group (keys(%{$allgroups{$cid}})) {
6229: if (grep/^$group$/,@groups) {
6230: return 'ok';
6231: }
6232: }
6233: }
6234: }
6235: }
6236: }
6237: }
6238: }
6239: if ($guest) {
6240: return $guest;
6241: }
6242: }
6243: }
6244: return;
6245: }
6246:
6247: sub course_group_datechecker {
6248: my ($dates,$now,$status) = @_;
6249: my ($start,$end) = split(/\./,$dates);
6250: if (!$start && !$end) {
6251: return 'ok';
6252: }
6253: if (grep/^active$/,@{$status}) {
6254: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6255: return 'ok';
6256: }
6257: }
6258: if (grep/^previous$/,@{$status}) {
6259: if ($end > $now ) {
6260: return 'ok';
6261: }
6262: }
6263: if (grep/^future$/,@{$status}) {
6264: if ($start > $now) {
6265: return 'ok';
6266: }
6267: }
6268: return;
6269: }
6270:
6271: sub parse_portfolio_url {
6272: my ($url) = @_;
6273:
6274: my ($type,$udom,$unum,$group,$file_name);
6275:
1.823 albertel 6276: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6277: $type = 1;
6278: $udom = $1;
6279: $unum = $2;
6280: $file_name = $3;
1.823 albertel 6281: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6282: $type = 2;
6283: $udom = $1;
6284: $unum = $2;
6285: $group = $3;
6286: $file_name = $3.'/'.$4;
6287: }
6288: if (wantarray) {
6289: return ($type,$udom,$unum,$file_name,$group);
6290: }
6291: return $type;
6292: }
6293:
6294: sub is_portfolio_url {
6295: my ($url) = @_;
6296: return scalar(&parse_portfolio_url($url));
6297: }
6298:
1.798 raeburn 6299: sub is_portfolio_file {
6300: my ($file) = @_;
1.820 raeburn 6301: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6302: return 1;
6303: }
6304: return;
6305: }
6306:
1.976 raeburn 6307: sub usertools_access {
1.1084 raeburn 6308: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6309: my ($access,%tools);
6310: if ($context eq '') {
6311: $context = 'tools';
6312: }
6313: if ($context eq 'requestcourses') {
6314: %tools = (
6315: official => 1,
6316: unofficial => 1,
1.1006 raeburn 6317: community => 1,
1.1172.2.37 raeburn 6318: textbook => 1,
1.985 raeburn 6319: );
1.1172.2.9 raeburn 6320: } elsif ($context eq 'requestauthor') {
6321: %tools = (
6322: requestauthor => 1,
6323: );
1.985 raeburn 6324: } else {
6325: %tools = (
6326: aboutme => 1,
6327: blog => 1,
1.1172.2.6 raeburn 6328: webdav => 1,
1.985 raeburn 6329: portfolio => 1,
6330: );
6331: }
1.976 raeburn 6332: return if (!defined($tools{$tool}));
6333:
1.1172.2.35 raeburn 6334: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6335: $udom = $env{'user.domain'};
6336: $uname = $env{'user.name'};
6337: }
6338:
1.978 raeburn 6339: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6340: if ($action ne 'reload') {
1.985 raeburn 6341: if ($context eq 'requestcourses') {
6342: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6343: } elsif ($context eq 'requestauthor') {
6344: return $env{'environment.canrequest.author'};
1.985 raeburn 6345: } else {
6346: return $env{'environment.availabletools.'.$tool};
6347: }
6348: }
1.976 raeburn 6349: }
6350:
1.1172.2.9 raeburn 6351: my ($toolstatus,$inststatus,$envkey);
6352: if ($context eq 'requestauthor') {
6353: $envkey = $context;
6354: } else {
6355: $envkey = $context.'.'.$tool;
6356: }
1.976 raeburn 6357:
1.985 raeburn 6358: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6359: ($action ne 'reload')) {
1.1172.2.9 raeburn 6360: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6361: $inststatus = $env{'environment.inststatus'};
6362: } else {
1.1084 raeburn 6363: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6364: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6365: $inststatus = $userenvref->{'inststatus'};
6366: } else {
1.1172.2.9 raeburn 6367: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6368: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6369: $inststatus = $userenv{'inststatus'};
6370: }
1.976 raeburn 6371: }
6372:
6373: if ($toolstatus ne '') {
6374: if ($toolstatus) {
6375: $access = 1;
6376: } else {
6377: $access = 0;
6378: }
6379: return $access;
6380: }
6381:
1.1084 raeburn 6382: my ($is_adv,%domdef);
6383: if (ref($is_advref) eq 'HASH') {
6384: $is_adv = $is_advref->{'is_adv'};
6385: } else {
6386: $is_adv = &is_advanced_user($udom,$uname);
6387: }
6388: if (ref($domdefref) eq 'HASH') {
6389: %domdef = %{$domdefref};
6390: } else {
6391: %domdef = &get_domain_defaults($udom);
6392: }
1.976 raeburn 6393: if (ref($domdef{$tool}) eq 'HASH') {
6394: if ($is_adv) {
6395: if ($domdef{$tool}{'_LC_adv'} ne '') {
6396: if ($domdef{$tool}{'_LC_adv'}) {
6397: $access = 1;
6398: } else {
6399: $access = 0;
6400: }
6401: return $access;
6402: }
6403: }
6404: if ($inststatus ne '') {
6405: my ($hasaccess,$hasnoaccess);
6406: foreach my $affiliation (split(/:/,$inststatus)) {
6407: if ($domdef{$tool}{$affiliation} ne '') {
6408: if ($domdef{$tool}{$affiliation}) {
6409: $hasaccess = 1;
6410: } else {
6411: $hasnoaccess = 1;
6412: }
6413: }
6414: }
6415: if ($hasaccess || $hasnoaccess) {
6416: if ($hasaccess) {
6417: $access = 1;
6418: } elsif ($hasnoaccess) {
6419: $access = 0;
6420: }
6421: return $access;
6422: }
6423: } else {
6424: if ($domdef{$tool}{'default'} ne '') {
6425: if ($domdef{$tool}{'default'}) {
6426: $access = 1;
6427: } elsif ($domdef{$tool}{'default'} == 0) {
6428: $access = 0;
6429: }
6430: return $access;
6431: }
6432: }
6433: } else {
1.1172.2.6 raeburn 6434: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6435: $access = 1;
6436: } else {
6437: $access = 0;
6438: }
1.976 raeburn 6439: return $access;
6440: }
6441: }
6442:
1.1050 raeburn 6443: sub is_course_owner {
6444: my ($cdom,$cnum,$udom,$uname) = @_;
6445: if (($udom eq '') || ($uname eq '')) {
6446: $udom = $env{'user.domain'};
6447: $uname = $env{'user.name'};
6448: }
6449: unless (($udom eq '') || ($uname eq '')) {
6450: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6451: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6452: return 1;
6453: } else {
6454: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6455: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6456: return 1;
6457: }
6458: }
6459: }
6460: }
6461: return;
6462: }
6463:
1.976 raeburn 6464: sub is_advanced_user {
6465: my ($udom,$uname) = @_;
1.1085 raeburn 6466: if ($udom ne '' && $uname ne '') {
6467: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6468: if (wantarray) {
6469: return ($env{'user.adv'},$env{'user.author'});
6470: } else {
6471: return $env{'user.adv'};
6472: }
1.1085 raeburn 6473: }
6474: }
1.976 raeburn 6475: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6476: my %allroles;
1.1128 raeburn 6477: my ($is_adv,$is_author);
1.976 raeburn 6478: foreach my $role (keys(%roleshash)) {
6479: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6480: my $area = '/'.$tdomain.'/'.$trest;
6481: if ($sec ne '') {
6482: $area .= '/'.$sec;
6483: }
6484: if (($area ne '') && ($trole ne '')) {
6485: my $spec=$trole.'.'.$area;
6486: if ($trole =~ /^cr\//) {
6487: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6488: } elsif ($trole ne 'gr') {
6489: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6490: }
1.1128 raeburn 6491: if ($trole eq 'au') {
6492: $is_author = 1;
6493: }
1.976 raeburn 6494: }
6495: }
6496: foreach my $role (keys(%allroles)) {
6497: last if ($is_adv);
6498: foreach my $item (split(/:/,$allroles{$role})) {
6499: if ($item ne '') {
6500: my ($privilege,$restrictions)=split(/&/,$item);
6501: if ($privilege eq 'adv') {
6502: $is_adv = 1;
6503: last;
6504: }
6505: }
6506: }
6507: }
1.1128 raeburn 6508: if (wantarray) {
6509: return ($is_adv,$is_author);
6510: }
1.976 raeburn 6511: return $is_adv;
6512: }
1.798 raeburn 6513:
1.1035 raeburn 6514: sub check_can_request {
1.1036 raeburn 6515: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6516: my $canreq = 0;
6517: my ($types,$typename) = &Apache::loncommon::course_types();
6518: my @options = ('approval','validate','autolimit');
6519: my $optregex = join('|',@options);
6520: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6521: foreach my $type (@{$types}) {
6522: if (&usertools_access($env{'user.name'},
6523: $env{'user.domain'},
6524: $type,undef,'requestcourses')) {
6525: $canreq ++;
1.1036 raeburn 6526: if (ref($request_domains) eq 'HASH') {
6527: push(@{$request_domains->{$type}},$env{'user.domain'});
6528: }
1.1035 raeburn 6529: if ($dom eq $env{'user.domain'}) {
6530: $can_request->{$type} = 1;
6531: }
6532: }
6533: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6534: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6535: if (@curr > 0) {
1.1036 raeburn 6536: foreach my $item (@curr) {
6537: if (ref($request_domains) eq 'HASH') {
6538: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6539: if ($otherdom ne '') {
6540: if (ref($request_domains->{$type}) eq 'ARRAY') {
6541: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6542: push(@{$request_domains->{$type}},$otherdom);
6543: }
6544: } else {
6545: push(@{$request_domains->{$type}},$otherdom);
6546: }
6547: }
6548: }
6549: }
6550: unless($dom eq $env{'user.domain'}) {
6551: $canreq ++;
1.1035 raeburn 6552: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6553: $can_request->{$type} = 1;
6554: }
6555: }
6556: }
6557: }
6558: }
6559: }
6560: return $canreq;
6561: }
6562:
1.341 www 6563: # ---------------------------------------------- Custom access rule evaluation
6564:
6565: sub customaccess {
6566: my ($priv,$uri)=@_;
1.807 albertel 6567: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6568: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6569: $udom = &LONCAPA::clean_domain($udom);
6570: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6571: my $access=0;
1.800 albertel 6572: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6573: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6574: if ($type eq 'user') {
6575: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6576: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6577: if ($tdom) {
6578: if ($tdom ne $env{'user.domain'}) { next; }
6579: }
1.896 albertel 6580: if ($tuname) {
6581: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6582: }
6583: $access=($effect eq 'allow');
6584: last;
6585: }
6586: } else {
6587: if ($role) {
6588: if ($role ne $urole) { next; }
6589: }
6590: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6591: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6592: if ($tdom) {
6593: if ($tdom ne $udom) { next; }
6594: }
6595: if ($tcrs) {
6596: if ($tcrs ne $ucrs) { next; }
6597: }
6598: if ($tsec) {
6599: if ($tsec ne $usec) { next; }
6600: }
6601: $access=($effect eq 'allow');
6602: last;
6603: }
6604: if ($realm eq '' && $role eq '') {
6605: $access=($effect eq 'allow');
6606: }
1.402 bowersj2 6607: }
1.341 www 6608: }
6609: return $access;
6610: }
6611:
1.103 harris41 6612: # ------------------------------------------------- Check for a user privilege
1.12 www 6613:
6614: sub allowed {
1.810 raeburn 6615: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6616: my $ver_orguri=$uri;
1.439 www 6617: $uri=&deversion($uri);
1.152 www 6618: my $orguri=$uri;
1.52 www 6619: $uri=&declutter($uri);
1.809 raeburn 6620:
1.810 raeburn 6621: if ($priv eq 'evb') {
6622: # Evade communication block restrictions for specified role in a course
6623: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6624: return $1;
6625: } else {
6626: return;
6627: }
6628: }
6629:
1.620 albertel 6630: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6631: # Free bre access to adm and meta resources
1.775 albertel 6632: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6633: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6634: && ($priv eq 'bre')) {
1.14 www 6635: return 'F';
1.159 www 6636: }
6637:
1.545 banghart 6638: # Free bre access to user's own portfolio contents
1.714 raeburn 6639: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6640: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6641: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6642: my %setters;
6643: my ($startblock,$endblock) =
6644: &Apache::loncommon::blockcheck(\%setters,'port');
6645: if ($startblock && $endblock) {
6646: return 'B';
6647: } else {
6648: return 'F';
6649: }
1.545 banghart 6650: }
6651:
1.762 raeburn 6652: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6653: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6654: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6655: if (exists($env{'request.course.id'})) {
6656: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6657: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6658: if (($domain eq $cdom) && ($name eq $cnum)) {
6659: my $courseprivid=$env{'request.course.id'};
6660: $courseprivid=~s/\_/\//;
6661: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6662: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6663: return $1;
1.762 raeburn 6664: } else {
6665: if ($env{'request.course.sec'}) {
6666: $courseprivid.='/'.$env{'request.course.sec'};
6667: }
6668: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6669: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6670: return $2;
6671: }
1.714 raeburn 6672: }
6673: }
6674: }
6675: }
6676:
1.159 www 6677: # Free bre to public access
6678:
6679: if ($priv eq 'bre') {
1.238 www 6680: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6681: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6682: return 'F';
6683: }
1.238 www 6684: if ($copyright eq 'priv') {
6685: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6686: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6687: return '';
6688: }
6689: }
6690: if ($copyright eq 'domain') {
6691: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6692: unless (($env{'user.domain'} eq $1) ||
6693: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6694: return '';
6695: }
1.262 matthew 6696: }
1.620 albertel 6697: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6698: # Library role, so allow browsing of resources in this domain.
6699: return 'F';
1.238 www 6700: }
1.341 www 6701: if ($copyright eq 'custom') {
6702: unless (&customaccess($priv,$uri)) { return ''; }
6703: }
1.14 www 6704: }
1.264 matthew 6705: # Domain coordinator is trying to create a course
1.620 albertel 6706: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6707: # uri is the requested domain in this case.
6708: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6709: # a role of dc for the domain in question.
1.620 albertel 6710: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6711: }
1.29 www 6712:
1.52 www 6713: my $thisallowed='';
6714: my $statecond=0;
6715: my $courseprivid='';
6716:
1.1039 raeburn 6717: my $ownaccess;
1.1043 raeburn 6718: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6719: if (($priv eq 'bro') && ($env{'user.author'})) {
6720: if ($uri eq '') {
6721: $ownaccess = 1;
6722: } else {
6723: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6724: my $udom = $env{'user.domain'};
6725: my $uname = $env{'user.name'};
6726: if ($uri =~ m{^\Q$udom\E/?$}) {
6727: $ownaccess = 1;
1.1040 raeburn 6728: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6729: unless ($uri =~ m{\.\./}) {
6730: $ownaccess = 1;
6731: }
6732: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6733: my $now = time;
6734: if ($uri =~ m{^([^/]+)/?$}) {
6735: my $adom = $1;
6736: foreach my $key (keys(%env)) {
1.1042 raeburn 6737: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6738: my ($start,$end) = split('.',$env{$key});
6739: if (($now >= $start) && (!$end || $end < $now)) {
6740: $ownaccess = 1;
6741: last;
6742: }
6743: }
6744: }
6745: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6746: my $adom = $1;
6747: my $aname = $2;
1.1042 raeburn 6748: foreach my $role ('ca','aa') {
6749: if ($env{"user.role.$role./$adom/$aname"}) {
6750: my ($start,$end) =
6751: split('.',$env{"user.role.$role./$adom/$aname"});
6752: if (($now >= $start) && (!$end || $end < $now)) {
6753: $ownaccess = 1;
6754: last;
6755: }
1.1039 raeburn 6756: }
6757: }
6758: }
6759: }
6760: }
6761: }
6762: }
6763:
1.52 www 6764: # Course
6765:
1.620 albertel 6766: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6767: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6768: $thisallowed.=$1;
6769: }
1.52 www 6770: }
1.29 www 6771:
1.52 www 6772: # Domain
6773:
1.620 albertel 6774: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6775: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6776: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6777: $thisallowed.=$1;
6778: }
1.12 www 6779: }
1.52 www 6780:
1.1141 raeburn 6781: # User who is not author or co-author might still be able to edit
6782: # resource of an author in the domain (e.g., if Domain Coordinator).
6783: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6784: (&allowed('mdc',$env{'request.course.id'}))) {
6785: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6786: $thisallowed.=$1;
6787: }
6788: }
6789:
1.52 www 6790: # Course: uri itself is a course
1.66 www 6791: my $courseuri=$uri;
6792: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6793: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6794:
1.620 albertel 6795: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6796: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6797: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6798: $thisallowed.=$1;
6799: }
1.12 www 6800: }
1.29 www 6801:
1.665 albertel 6802: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6803: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6804: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6805: $thisallowed='';
1.671 raeburn 6806: my ($match)=&is_on_map($uri);
6807: if ($match) {
6808: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6809: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6810: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6811: if (@blockers > 0) {
6812: $thisallowed = 'B';
6813: } else {
6814: $thisallowed.=$1;
6815: }
1.671 raeburn 6816: }
6817: } else {
1.705 albertel 6818: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6819: if ($refuri) {
6820: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6821: $thisallowed='F';
1.671 raeburn 6822: } else {
6823: $refuri=&declutter($refuri);
6824: my ($match) = &is_on_map($refuri);
6825: if ($match) {
1.1162 raeburn 6826: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6827: if (@blockers > 0) {
6828: $thisallowed = 'B';
6829: } else {
6830: $thisallowed='F';
6831: }
1.671 raeburn 6832: }
1.669 raeburn 6833: }
1.671 raeburn 6834: }
6835: }
1.314 www 6836: }
1.492 albertel 6837:
1.766 albertel 6838: if ($priv eq 'bre'
6839: && $thisallowed ne 'F'
6840: && $thisallowed ne '2'
6841: && &is_portfolio_url($uri)) {
6842: $thisallowed = &portfolio_access($uri);
6843: }
6844:
1.52 www 6845: # Full access at system, domain or course-wide level? Exit.
1.29 www 6846: if ($thisallowed=~/F/) {
6847: return 'F';
6848: }
6849:
1.52 www 6850: # If this is generating or modifying users, exit with special codes
1.29 www 6851:
1.643 www 6852: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6853: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6854: my ($audom,$auname)=split('/',$uri);
1.643 www 6855: # no author name given, so this just checks on the general right to make a co-author in this domain
6856: unless ($auname) { return $thisallowed; }
6857: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6858: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6859: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6860: ($audom ne $env{'request.role.domain'}))) { return ''; }
6861: }
1.52 www 6862: return $thisallowed;
6863: }
6864: #
1.103 harris41 6865: # Gathered so far: system, domain and course wide privileges
1.52 www 6866: #
6867: # Course: See if uri or referer is an individual resource that is part of
6868: # the course
6869:
1.620 albertel 6870: if ($env{'request.course.id'}) {
1.232 www 6871:
1.620 albertel 6872: $courseprivid=$env{'request.course.id'};
6873: if ($env{'request.course.sec'}) {
6874: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6875: }
6876: $courseprivid=~s/\_/\//;
6877: my $checkreferer=1;
1.232 www 6878: my ($match,$cond)=&is_on_map($uri);
6879: if ($match) {
6880: $statecond=$cond;
1.620 albertel 6881: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6882: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6883: my $value = $1;
6884: if ($priv eq 'bre') {
6885: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6886: if (@blockers > 0) {
6887: $thisallowed = 'B';
6888: } else {
6889: $thisallowed.=$value;
6890: }
6891: } else {
6892: $thisallowed.=$value;
6893: }
1.52 www 6894: $checkreferer=0;
6895: }
1.29 www 6896: }
1.83 www 6897:
1.148 www 6898: if ($checkreferer) {
1.620 albertel 6899: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6900: unless ($refuri) {
1.800 albertel 6901: foreach my $key (keys(%env)) {
6902: if ($key=~/^httpref\..*\*/) {
6903: my $pattern=$key;
1.156 www 6904: $pattern=~s/^httpref\.\/res\///;
1.148 www 6905: $pattern=~s/\*/\[\^\/\]\+/g;
6906: $pattern=~s/\//\\\//g;
1.152 www 6907: if ($orguri=~/$pattern/) {
1.800 albertel 6908: $refuri=$env{$key};
1.148 www 6909: }
6910: }
1.191 harris41 6911: }
1.148 www 6912: }
1.232 www 6913:
1.148 www 6914: if ($refuri) {
1.152 www 6915: $refuri=&declutter($refuri);
1.232 www 6916: my ($match,$cond)=&is_on_map($refuri);
6917: if ($match) {
6918: my $refstatecond=$cond;
1.620 albertel 6919: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6920: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6921: my $value = $1;
6922: if ($priv eq 'bre') {
6923: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6924: if (@blockers > 0) {
6925: $thisallowed = 'B';
6926: } else {
6927: $thisallowed.=$value;
6928: }
6929: } else {
6930: $thisallowed.=$value;
6931: }
1.53 www 6932: $uri=$refuri;
6933: $statecond=$refstatecond;
1.52 www 6934: }
6935: }
1.148 www 6936: }
1.29 www 6937: }
1.52 www 6938: }
1.29 www 6939:
1.52 www 6940: #
1.103 harris41 6941: # Gathered now: all privileges that could apply, and condition number
1.52 www 6942: #
6943: #
6944: # Full or no access?
6945: #
1.29 www 6946:
1.52 www 6947: if ($thisallowed=~/F/) {
6948: return 'F';
6949: }
1.29 www 6950:
1.52 www 6951: unless ($thisallowed) {
6952: return '';
6953: }
1.29 www 6954:
1.52 www 6955: # Restrictions exist, deal with them
6956: #
6957: # C:according to course preferences
6958: # R:according to resource settings
6959: # L:unless locked
6960: # X:according to user session state
6961: #
6962:
6963: # Possibly locked functionality, check all courses
1.54 www 6964: # Locks might take effect only after 10 minutes cache expiration for other
6965: # courses, and 2 minutes for current course
1.52 www 6966:
6967: my $envkey;
6968: if ($thisallowed=~/L/) {
1.1000 raeburn 6969: foreach $envkey (keys(%env)) {
1.54 www 6970: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6971: my $courseid=$2;
6972: my $roleid=$1.'.'.$2;
1.92 www 6973: $courseid=~s/^\///;
1.54 www 6974: my $expiretime=600;
1.620 albertel 6975: if ($env{'request.role'} eq $roleid) {
1.54 www 6976: $expiretime=120;
6977: }
6978: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6979: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6980: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6981: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6982: }
1.620 albertel 6983: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6984: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6985: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6986: &log($env{'user.domain'},$env{'user.name'},
6987: $env{'user.home'},
1.57 www 6988: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6989: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6990: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6991: return '';
6992: }
6993: }
1.620 albertel 6994: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6995: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6996: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6997: &log($env{'user.domain'},$env{'user.name'},
6998: $env{'user.home'},
1.57 www 6999: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7000: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7001: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7002: return '';
7003: }
7004: }
7005: }
1.29 www 7006: }
1.52 www 7007: }
7008:
7009: #
7010: # Rest of the restrictions depend on selected course
7011: #
7012:
1.620 albertel 7013: unless ($env{'request.course.id'}) {
1.766 albertel 7014: if ($thisallowed eq 'A') {
7015: return 'A';
1.814 raeburn 7016: } elsif ($thisallowed eq 'B') {
7017: return 'B';
1.766 albertel 7018: } else {
7019: return '1';
7020: }
1.52 www 7021: }
1.29 www 7022:
1.52 www 7023: #
7024: # Now user is definitely in a course
7025: #
1.53 www 7026:
7027:
7028: # Course preferences
7029:
7030: if ($thisallowed=~/C/) {
1.620 albertel 7031: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7032: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7033: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7034: =~/\Q$rolecode\E/) {
1.1103 raeburn 7035: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7036: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7037: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7038: $env{'request.course.id'});
7039: }
1.237 www 7040: return '';
7041: }
7042:
1.620 albertel 7043: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7044: =~/\Q$unamedom\E/) {
1.1103 raeburn 7045: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7046: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7047: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7048: $env{'request.course.id'});
7049: }
1.54 www 7050: return '';
7051: }
1.53 www 7052: }
7053:
7054: # Resource preferences
7055:
7056: if ($thisallowed=~/R/) {
1.620 albertel 7057: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7058: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7059: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7060: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7061: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7062: }
7063: return '';
1.54 www 7064: }
1.53 www 7065: }
1.30 www 7066:
1.246 www 7067: # Restricted by state or randomout?
1.30 www 7068:
1.52 www 7069: if ($thisallowed=~/X/) {
1.620 albertel 7070: if ($env{'acc.randomout'}) {
1.579 albertel 7071: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7072: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7073: return '';
7074: }
1.247 www 7075: }
7076: if (&condval($statecond)) {
1.52 www 7077: return '2';
7078: } else {
7079: return '';
7080: }
7081: }
1.30 www 7082:
1.766 albertel 7083: if ($thisallowed eq 'A') {
7084: return 'A';
1.814 raeburn 7085: } elsif ($thisallowed eq 'B') {
7086: return 'B';
1.766 albertel 7087: }
1.52 www 7088: return 'F';
1.232 www 7089: }
1.1162 raeburn 7090:
1.1172.2.13 raeburn 7091: # ------------------------------------------- Check construction space access
7092:
7093: sub constructaccess {
7094: my ($url,$setpriv)=@_;
7095:
7096: # We do not allow editing of previous versions of files
7097: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7098:
7099: # Get username and domain from URL
7100: my ($ownername,$ownerdomain,$ownerhome);
7101:
7102: ($ownerdomain,$ownername) =
7103: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7104:
7105: # The URL does not really point to any authorspace, forget it
7106: unless (($ownername) && ($ownerdomain)) { return ''; }
7107:
7108: # Now we need to see if the user has access to the authorspace of
7109: # $ownername at $ownerdomain
7110:
7111: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7112: # Real author for this?
7113: $ownerhome = $env{'user.home'};
7114: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7115: return ($ownername,$ownerdomain,$ownerhome);
7116: }
7117: } else {
7118: # Co-author for this?
7119: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7120: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7121: $ownerhome = &homeserver($ownername,$ownerdomain);
7122: return ($ownername,$ownerdomain,$ownerhome);
7123: }
7124: }
7125:
7126: # We don't have any access right now. If we are not possibly going to do anything about this,
7127: # we might as well leave
7128: unless ($setpriv) { return ''; }
7129:
7130: # Backdoor access?
7131: my $allowed=&allowed('eco',$ownerdomain);
7132: # Nope
7133: unless ($allowed) { return ''; }
7134: # Looks like we may have access, but could be locked by the owner of the construction space
7135: if ($allowed eq 'U') {
7136: my %blocked=&get('environment',['domcoord.author'],
7137: $ownerdomain,$ownername);
7138: # Is blocked by owner
7139: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7140: }
7141: if (($allowed eq 'F') || ($allowed eq 'U')) {
7142: # Grant temporary access
7143: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7144: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7145: if (!$update) { $update = $then; }
7146: my $refresh=$env{'user.refresh.time'};
7147: if (!$refresh) { $refresh = $update; }
7148: my $now = time;
7149: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7150: $now,'ca','constructaccess');
7151: $ownerhome = &homeserver($ownername,$ownerdomain);
7152: return($ownername,$ownerdomain,$ownerhome);
7153: }
7154: # No business here
7155: return '';
7156: }
7157:
1.1162 raeburn 7158: sub get_comm_blocks {
7159: my ($cdom,$cnum) = @_;
7160: if ($cdom eq '' || $cnum eq '') {
7161: return unless ($env{'request.course.id'});
7162: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7163: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7164: }
7165: my %commblocks;
7166: my $hashid=$cdom.'_'.$cnum;
7167: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7168: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7169: %commblocks = %{$blocksref};
7170: } else {
7171: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7172: my $cachetime = 600;
7173: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7174: }
7175: return %commblocks;
7176: }
7177:
7178: sub has_comm_blocking {
7179: my ($priv,$symb,$uri,$blocks) = @_;
7180: return unless ($env{'request.course.id'});
7181: return unless ($priv eq 'bre');
7182: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7183: my %commblocks;
7184: if (ref($blocks) eq 'HASH') {
7185: %commblocks = %{$blocks};
7186: } else {
7187: %commblocks = &get_comm_blocks();
7188: }
7189: return unless (keys(%commblocks) > 0);
7190: if (!$symb) { $symb=&symbread($uri,1); }
7191: my ($map,$resid,undef)=&decode_symb($symb);
7192: my %tocheck = (
7193: maps => $map,
7194: resources => $symb,
7195: );
7196: my @blockers;
7197: my $now = time;
1.1163 raeburn 7198: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7199: foreach my $block (keys(%commblocks)) {
7200: if ($block =~ /^(\d+)____(\d+)$/) {
7201: my ($start,$end) = ($1,$2);
7202: if ($start <= $now && $end >= $now) {
7203: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7204: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7205: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7206: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7207: unless (grep(/^\Q$block\E$/,@blockers)) {
7208: push(@blockers,$block);
7209: }
7210: }
7211: }
7212: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7213: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7214: unless (grep(/^\Q$block\E$/,@blockers)) {
7215: push(@blockers,$block);
7216: }
7217: }
7218: }
7219: }
7220: }
7221: }
7222: } elsif ($block =~ /^firstaccess____(.+)$/) {
7223: my $item = $1;
1.1163 raeburn 7224: my @to_test;
1.1162 raeburn 7225: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7226: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7227: my $check_interval;
7228: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7229: my @interval;
7230: my $type = 'map';
7231: if ($item eq 'course') {
7232: $type = 'course';
7233: @interval=&EXT("resource.0.interval");
7234: } else {
7235: if ($item =~ /___\d+___/) {
7236: $type = 'resource';
7237: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7238: if (ref($navmap)) {
7239: my $res = $navmap->getBySymb($item);
7240: push(@to_test,$res);
7241: }
1.1162 raeburn 7242: } else {
7243: my $mapsymb = &symbread($item,1);
7244: if ($mapsymb) {
7245: if (ref($navmap)) {
7246: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7247: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7248: foreach my $res (@to_test) {
1.1162 raeburn 7249: my $symb = $res->symb();
7250: next if ($symb eq $mapsymb);
7251: if ($symb ne '') {
7252: @interval=&EXT("resource.0.interval",$symb);
7253: last;
7254: }
7255: }
7256: }
7257: }
7258: }
7259: }
7260: if ($interval[0] =~ /\d+/) {
7261: my $first_access;
7262: if ($type eq 'resource') {
7263: $first_access=&get_first_access($interval[1],$item);
7264: } elsif ($type eq 'map') {
7265: $first_access=&get_first_access($interval[1],undef,$item);
7266: } else {
7267: $first_access=&get_first_access($interval[1]);
7268: }
7269: if ($first_access) {
7270: my $timesup = $first_access+$interval[0];
7271: if ($timesup > $now) {
1.1163 raeburn 7272: foreach my $res (@to_test) {
7273: if ($res->is_problem()) {
7274: if ($res->completable()) {
7275: unless (grep(/^\Q$block\E$/,@blockers)) {
7276: push(@blockers,$block);
7277: }
7278: last;
7279: }
7280: }
1.1162 raeburn 7281: }
7282: }
7283: }
7284: }
7285: }
7286: }
7287: }
7288: }
7289: }
7290: return @blockers;
7291: }
7292:
7293: sub check_docs_block {
7294: my ($docsblock,$tocheck) =@_;
7295: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7296: return;
7297: }
7298: if (ref($docsblock->{'maps'}) eq 'HASH') {
7299: if ($tocheck->{'maps'}) {
7300: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7301: return 1;
7302: }
7303: }
7304: }
7305: if (ref($docsblock->{'resources'}) eq 'HASH') {
7306: if ($tocheck->{'resources'}) {
7307: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7308: return 1;
7309: }
7310: }
7311: }
7312: return;
7313: }
7314:
1.1133 foxr 7315: #
7316: # Removes the versino from a URI and
7317: # splits it in to its filename and path to the filename.
7318: # Seems like File::Basename could have done this more clearly.
7319: # Parameters:
7320: # $uri - input URI
7321: # Returns:
7322: # Two element list consisting of
7323: # $pathname - the URI up to and excluding the trailing /
7324: # $filename - The part of the URI following the last /
7325: # NOTE:
7326: # Another realization of this is simply:
7327: # use File::Basename;
7328: # ...
7329: # $uri = shift;
7330: # $filename = basename($uri);
7331: # $path = dirname($uri);
7332: # return ($filename, $path);
7333: #
7334: # The implementation below is probably faster however.
7335: #
1.710 albertel 7336: sub split_uri_for_cond {
7337: my $uri=&deversion(&declutter(shift));
7338: my @uriparts=split(/\//,$uri);
7339: my $filename=pop(@uriparts);
7340: my $pathname=join('/',@uriparts);
7341: return ($pathname,$filename);
7342: }
1.232 www 7343: # --------------------------------------------------- Is a resource on the map?
7344:
7345: sub is_on_map {
1.710 albertel 7346: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7347: #Trying to find the conditional for the file
1.620 albertel 7348: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7349: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7350: if ($match) {
1.289 bowersj2 7351: return (1,$1);
7352: } else {
1.434 www 7353: return (0,0);
1.289 bowersj2 7354: }
1.12 www 7355: }
7356:
1.427 www 7357: # --------------------------------------------------------- Get symb from alias
7358:
7359: sub get_symb_from_alias {
7360: my $symb=shift;
7361: my ($map,$resid,$url)=&decode_symb($symb);
7362: # Already is a symb
7363: if ($url) { return $symb; }
7364: # Must be an alias
7365: my $aliassymb='';
7366: my %bighash;
1.620 albertel 7367: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7368: &GDBM_READER(),0640)) {
7369: my $rid=$bighash{'mapalias_'.$symb};
7370: if ($rid) {
7371: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7372: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7373: $resid,$bighash{'src_'.$rid});
1.427 www 7374: }
7375: untie %bighash;
7376: }
7377: return $aliassymb;
7378: }
7379:
1.12 www 7380: # ----------------------------------------------------------------- Define Role
7381:
7382: sub definerole {
7383: if (allowed('mcr','/')) {
7384: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7385: foreach my $role (split(':',$sysrole)) {
7386: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7387: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7388: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7389: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7390: return "refused:s:$crole&$cqual";
7391: }
7392: }
1.191 harris41 7393: }
1.800 albertel 7394: foreach my $role (split(':',$domrole)) {
7395: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7396: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7397: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7398: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7399: return "refused:d:$crole&$cqual";
7400: }
7401: }
1.191 harris41 7402: }
1.800 albertel 7403: foreach my $role (split(':',$courole)) {
7404: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7405: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7406: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7407: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7408: return "refused:c:$crole&$cqual";
7409: }
7410: }
1.191 harris41 7411: }
1.620 albertel 7412: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7413: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7414: "rolesdef_$rolename=".
7415: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7416: return reply($command,$env{'user.home'});
1.12 www 7417: } else {
7418: return 'refused';
7419: }
1.105 harris41 7420: }
7421:
7422: # ---------------- Make a metadata query against the network of library servers
7423:
7424: sub metadata_query {
1.1172.2.33 raeburn 7425: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7426: my %rhash;
1.845 albertel 7427: my %libserv = &all_library();
1.244 matthew 7428: my @server_list = (defined($server_array) ? @$server_array
7429: : keys(%libserv) );
7430: for my $server (@server_list) {
1.1172.2.33 raeburn 7431: my $domains = '';
7432: if (ref($domains_hash) eq 'HASH') {
7433: $domains = $domains_hash->{$server};
7434: }
1.118 harris41 7435: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7436: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7437: $rhash{$server}=$reply;
7438: }
7439: else {
7440: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7441: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7442: $server);
7443: $rhash{$server}=$reply;
7444: }
1.112 harris41 7445: }
1.118 harris41 7446: return \%rhash;
1.240 www 7447: }
7448:
7449: # ----------------------------------------- Send log queries and wait for reply
7450:
7451: sub log_query {
7452: my ($uname,$udom,$query,%filters)=@_;
7453: my $uhome=&homeserver($uname,$udom);
7454: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7455: my $uhost=&hostname($uhome);
1.800 albertel 7456: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7457: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7458: $uhome);
1.479 albertel 7459: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7460: return get_query_reply($queryid);
7461: }
7462:
1.818 raeburn 7463: # -------------------------- Update MySQL table for portfolio file
7464:
7465: sub update_portfolio_table {
1.821 raeburn 7466: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7467: if ($group ne '') {
7468: $file_name =~s /^\Q$group\E//;
7469: }
1.818 raeburn 7470: my $homeserver = &homeserver($uname,$udom);
7471: my $queryid=
1.821 raeburn 7472: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7473: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7474: my $reply = &get_query_reply($queryid);
7475: return $reply;
7476: }
7477:
1.899 raeburn 7478: # -------------------------- Update MySQL allusers table
7479:
7480: sub update_allusers_table {
7481: my ($uname,$udom,$names) = @_;
7482: my $homeserver = &homeserver($uname,$udom);
7483: my $queryid=
7484: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7485: 'lastname='.&escape($names->{'lastname'}).'%%'.
7486: 'firstname='.&escape($names->{'firstname'}).'%%'.
7487: 'middlename='.&escape($names->{'middlename'}).'%%'.
7488: 'generation='.&escape($names->{'generation'}).'%%'.
7489: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7490: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7491: return;
1.899 raeburn 7492: }
7493:
1.508 raeburn 7494: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7495:
7496: sub fetch_enrollment_query {
1.511 raeburn 7497: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7498: my $homeserver;
1.547 raeburn 7499: my $maxtries = 1;
1.508 raeburn 7500: if ($context eq 'automated') {
7501: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7502: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7503: } else {
7504: $homeserver = &homeserver($cnum,$dom);
7505: }
1.838 albertel 7506: my $host=&hostname($homeserver);
1.506 raeburn 7507: my $cmd = '';
1.1000 raeburn 7508: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7509: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7510: }
7511: $cmd =~ s/%%$//;
7512: $cmd = &escape($cmd);
7513: my $query = 'fetchenrollment';
1.620 albertel 7514: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7515: unless ($queryid=~/^\Q$host\E\_/) {
7516: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7517: return 'error: '.$queryid;
7518: }
1.506 raeburn 7519: my $reply = &get_query_reply($queryid);
1.547 raeburn 7520: my $tries = 1;
7521: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7522: $reply = &get_query_reply($queryid);
7523: $tries ++;
7524: }
1.526 raeburn 7525: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7526: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7527: } else {
1.901 albertel 7528: my @responses = split(/:/,$reply);
1.515 raeburn 7529: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7530: foreach my $line (@responses) {
7531: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7532: $$replyref{$key} = $value;
7533: }
7534: } else {
1.1117 foxr 7535: my $pathname = LONCAPA::tempdir();
1.800 albertel 7536: foreach my $line (@responses) {
7537: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7538: $$replyref{$key} = $value;
7539: if ($value > 0) {
1.800 albertel 7540: foreach my $item (@{$$affiliatesref{$key}}) {
7541: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7542: my $destname = $pathname.'/'.$filename;
7543: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7544: if ($xml_classlist =~ /^error/) {
7545: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7546: } else {
1.506 raeburn 7547: if ( open(FILE,">$destname") ) {
7548: print FILE &unescape($xml_classlist);
7549: close(FILE);
1.526 raeburn 7550: } else {
7551: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7552: }
7553: }
7554: }
7555: }
7556: }
7557: }
7558: return 'ok';
7559: }
7560: return 'error';
7561: }
7562:
1.242 www 7563: sub get_query_reply {
7564: my $queryid=shift;
1.1117 foxr 7565: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7566: my $reply='';
7567: for (1..100) {
7568: sleep 2;
7569: if (-e $replyfile.'.end') {
1.448 albertel 7570: if (open(my $fh,$replyfile)) {
1.904 albertel 7571: $reply = join('',<$fh>);
7572: close($fh);
1.240 www 7573: } else { return 'error: reply_file_error'; }
1.242 www 7574: return &unescape($reply);
7575: }
1.240 www 7576: }
1.242 www 7577: return 'timeout:'.$queryid;
1.240 www 7578: }
7579:
7580: sub courselog_query {
1.241 www 7581: #
7582: # possible filters:
7583: # url: url or symb
7584: # username
7585: # domain
7586: # action: view, submit, grade
7587: # start: timestamp
7588: # end: timestamp
7589: #
1.240 www 7590: my (%filters)=@_;
1.620 albertel 7591: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7592: if ($filters{'url'}) {
7593: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7594: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7595: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7596: }
1.620 albertel 7597: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7598: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7599: return &log_query($cname,$cdom,'courselog',%filters);
7600: }
7601:
7602: sub userlog_query {
1.858 raeburn 7603: #
7604: # possible filters:
7605: # action: log check role
7606: # start: timestamp
7607: # end: timestamp
7608: #
1.240 www 7609: my ($uname,$udom,%filters)=@_;
7610: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7611: }
7612:
1.506 raeburn 7613: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7614:
7615: sub auto_run {
1.508 raeburn 7616: my ($cnum,$cdom) = @_;
1.876 raeburn 7617: my $response = 0;
7618: my $settings;
7619: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7620: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7621: $settings = $domconfig{'autoenroll'};
7622: if ($settings->{'run'} eq '1') {
7623: $response = 1;
7624: }
7625: } else {
1.934 raeburn 7626: my $homeserver;
7627: if (&is_course($cdom,$cnum)) {
7628: $homeserver = &homeserver($cnum,$cdom);
7629: } else {
7630: $homeserver = &domain($cdom,'primary');
7631: }
7632: if ($homeserver ne 'no_host') {
7633: $response = &reply('autorun:'.$cdom,$homeserver);
7634: }
1.876 raeburn 7635: }
1.506 raeburn 7636: return $response;
7637: }
1.776 albertel 7638:
1.506 raeburn 7639: sub auto_get_sections {
1.508 raeburn 7640: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7641: my $homeserver;
7642: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7643: $homeserver = &homeserver($cnum,$cdom);
7644: }
7645: if (!defined($homeserver)) {
7646: if ($cdom =~ /^$match_domain$/) {
7647: $homeserver = &domain($cdom,'primary');
7648: }
7649: }
7650: my @secs;
7651: if (defined($homeserver)) {
7652: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7653: unless ($response eq 'refused') {
7654: @secs = split(/:/,$response);
7655: }
1.506 raeburn 7656: }
7657: return @secs;
7658: }
1.776 albertel 7659:
1.506 raeburn 7660: sub auto_new_course {
1.1099 raeburn 7661: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7662: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7663: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7664: return $response;
7665: }
1.776 albertel 7666:
1.506 raeburn 7667: sub auto_validate_courseID {
1.508 raeburn 7668: my ($cnum,$cdom,$inst_course_id) = @_;
7669: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7670: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7671: return $response;
7672: }
1.776 albertel 7673:
1.1007 raeburn 7674: sub auto_validate_instcode {
1.1020 raeburn 7675: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7676: my ($homeserver,$response);
7677: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7678: $homeserver = &homeserver($cnum,$cdom);
7679: }
7680: if (!defined($homeserver)) {
7681: if ($cdom =~ /^$match_domain$/) {
7682: $homeserver = &domain($cdom,'primary');
7683: }
7684: }
1.1065 raeburn 7685: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7686: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7687: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7688: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7689: }
7690:
1.506 raeburn 7691: sub auto_create_password {
1.873 raeburn 7692: my ($cnum,$cdom,$authparam,$udom) = @_;
7693: my ($homeserver,$response);
1.506 raeburn 7694: my $create_passwd = 0;
7695: my $authchk = '';
1.873 raeburn 7696: if ($udom =~ /^$match_domain$/) {
7697: $homeserver = &domain($udom,'primary');
7698: }
7699: if ($homeserver eq '') {
7700: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7701: $homeserver = &homeserver($cnum,$cdom);
7702: }
7703: }
7704: if ($homeserver eq '') {
7705: $authchk = 'nodomain';
1.506 raeburn 7706: } else {
1.873 raeburn 7707: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7708: if ($response eq 'refused') {
7709: $authchk = 'refused';
7710: } else {
1.901 albertel 7711: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7712: }
1.506 raeburn 7713: }
7714: return ($authparam,$create_passwd,$authchk);
7715: }
7716:
1.706 raeburn 7717: sub auto_photo_permission {
7718: my ($cnum,$cdom,$students) = @_;
7719: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7720: my ($outcome,$perm_reqd,$conditions) =
7721: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7722: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7723: return (undef,undef);
7724: }
1.706 raeburn 7725: return ($outcome,$perm_reqd,$conditions);
7726: }
7727:
7728: sub auto_checkphotos {
7729: my ($uname,$udom,$pid) = @_;
7730: my $homeserver = &homeserver($uname,$udom);
7731: my ($result,$resulttype);
7732: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7733: &escape($uname).':'.&escape($pid),
7734: $homeserver));
1.709 albertel 7735: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7736: return (undef,undef);
7737: }
1.706 raeburn 7738: if ($outcome) {
7739: ($result,$resulttype) = split(/:/,$outcome);
7740: }
7741: return ($result,$resulttype);
7742: }
7743:
7744: sub auto_photochoice {
7745: my ($cnum,$cdom) = @_;
7746: my $homeserver = &homeserver($cnum,$cdom);
7747: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7748: &escape($cdom),
7749: $homeserver)));
1.709 albertel 7750: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7751: return (undef,undef);
7752: }
1.706 raeburn 7753: return ($update,$comment);
7754: }
7755:
7756: sub auto_photoupdate {
7757: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7758: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7759: my $host=&hostname($homeserver);
1.706 raeburn 7760: my $cmd = '';
7761: my $maxtries = 1;
1.800 albertel 7762: foreach my $affiliate (keys(%{$affiliatesref})) {
7763: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7764: }
7765: $cmd =~ s/%%$//;
7766: $cmd = &escape($cmd);
7767: my $query = 'institutionalphotos';
7768: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7769: unless ($queryid=~/^\Q$host\E\_/) {
7770: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7771: return 'error: '.$queryid;
7772: }
7773: my $reply = &get_query_reply($queryid);
7774: my $tries = 1;
7775: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7776: $reply = &get_query_reply($queryid);
7777: $tries ++;
7778: }
7779: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7780: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7781: } else {
7782: my @responses = split(/:/,$reply);
7783: my $outcome = shift(@responses);
7784: foreach my $item (@responses) {
7785: my ($key,$value) = split(/=/,$item);
7786: $$photo{$key} = $value;
7787: }
7788: return $outcome;
7789: }
7790: return 'error';
7791: }
7792:
1.521 raeburn 7793: sub auto_instcode_format {
1.793 albertel 7794: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7795: $cat_order) = @_;
1.521 raeburn 7796: my $courses = '';
1.772 raeburn 7797: my @homeservers;
1.521 raeburn 7798: if ($caller eq 'global') {
1.841 albertel 7799: my %servers = &get_servers($codedom,'library');
7800: foreach my $tryserver (keys(%servers)) {
7801: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7802: push(@homeservers,$tryserver);
7803: }
1.584 raeburn 7804: }
1.1022 raeburn 7805: } elsif ($caller eq 'requests') {
7806: if ($codedom =~ /^$match_domain$/) {
7807: my $chome = &domain($codedom,'primary');
7808: unless ($chome eq 'no_host') {
7809: push(@homeservers,$chome);
7810: }
7811: }
1.521 raeburn 7812: } else {
1.772 raeburn 7813: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7814: }
1.793 albertel 7815: foreach my $code (keys(%{$instcodes})) {
7816: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7817: }
7818: chop($courses);
1.772 raeburn 7819: my $ok_response = 0;
7820: my $response;
7821: while (@homeservers > 0 && $ok_response == 0) {
7822: my $server = shift(@homeservers);
7823: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7824: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7825: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7826: split(/:/,$response);
1.772 raeburn 7827: %{$codes} = (%{$codes},&str2hash($codes_str));
7828: push(@{$codetitles},&str2array($codetitles_str));
7829: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7830: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7831: $ok_response = 1;
7832: }
7833: }
7834: if ($ok_response) {
1.521 raeburn 7835: return 'ok';
1.772 raeburn 7836: } else {
7837: return $response;
1.521 raeburn 7838: }
7839: }
7840:
1.792 raeburn 7841: sub auto_instcode_defaults {
7842: my ($domain,$returnhash,$code_order) = @_;
7843: my @homeservers;
1.841 albertel 7844:
7845: my %servers = &get_servers($domain,'library');
7846: foreach my $tryserver (keys(%servers)) {
7847: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7848: push(@homeservers,$tryserver);
7849: }
1.792 raeburn 7850: }
1.841 albertel 7851:
1.792 raeburn 7852: my $response;
1.841 albertel 7853: foreach my $server (@homeservers) {
1.792 raeburn 7854: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7855: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7856:
7857: foreach my $pair (split(/\&/,$response)) {
7858: my ($name,$value)=split(/\=/,$pair);
7859: if ($name eq 'code_order') {
7860: @{$code_order} = split(/\&/,&unescape($value));
7861: } else {
7862: $returnhash->{&unescape($name)}=&unescape($value);
7863: }
7864: }
7865: return 'ok';
1.792 raeburn 7866: }
1.841 albertel 7867:
7868: return $response;
1.1003 raeburn 7869: }
7870:
7871: sub auto_possible_instcodes {
1.1007 raeburn 7872: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7873: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7874: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7875: return;
7876: }
1.1003 raeburn 7877: my (@homeservers,$uhome);
7878: if (defined(&domain($domain,'primary'))) {
7879: $uhome=&domain($domain,'primary');
7880: push(@homeservers,&domain($domain,'primary'));
7881: } else {
7882: my %servers = &get_servers($domain,'library');
7883: foreach my $tryserver (keys(%servers)) {
7884: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7885: push(@homeservers,$tryserver);
7886: }
7887: }
7888: }
7889: my $response;
7890: foreach my $server (@homeservers) {
7891: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7892: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7893: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7894: split(':',$response);
7895: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7896: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7897: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7898: my ($name,$value)=split('=',$item);
7899: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7900: }
7901: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7902: my ($name,$value)=split('=',$item);
7903: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7904: }
7905: return 'ok';
7906: }
7907: return $response;
7908: }
1.792 raeburn 7909:
1.1010 raeburn 7910: sub auto_courserequest_checks {
7911: my ($dom) = @_;
1.1020 raeburn 7912: my ($homeserver,%validations);
7913: if ($dom =~ /^$match_domain$/) {
7914: $homeserver = &domain($dom,'primary');
7915: }
7916: unless ($homeserver eq 'no_host') {
7917: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7918: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7919: my @items = split(/&/,$response);
7920: foreach my $item (@items) {
7921: my ($key,$value) = split('=',$item);
7922: $validations{&unescape($key)} = &thaw_unescape($value);
7923: }
7924: }
7925: }
1.1010 raeburn 7926: return %validations;
7927: }
7928:
1.1020 raeburn 7929: sub auto_courserequest_validation {
7930: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7931: my ($homeserver,$response);
7932: if ($dom =~ /^$match_domain$/) {
7933: $homeserver = &domain($dom,'primary');
7934: }
7935: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7936:
1.1020 raeburn 7937: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7938: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7939: ':'.&escape($instcode).':'.&escape($instseclist),
7940: $homeserver));
7941: }
7942: return $response;
7943: }
7944:
1.777 albertel 7945: sub auto_validate_class_sec {
1.918 raeburn 7946: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7947: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7948: my $ownerlist;
7949: if (ref($owners) eq 'ARRAY') {
7950: $ownerlist = join(',',@{$owners});
7951: } else {
7952: $ownerlist = $owners;
7953: }
1.773 raeburn 7954: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7955: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7956: return $response;
7957: }
7958:
1.1172.2.38 raeburn 7959: sub auto_crsreq_update {
7960: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7961: $code,$inbound) = @_;
7962: my ($homeserver,%crsreqresponse);
7963: if ($cdom =~ /^$match_domain$/) {
7964: $homeserver = &domain($cdom,'primary');
7965: }
7966: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7967: my $info;
7968: if (ref($inbound) eq 'HASH') {
7969: $info = &freeze_escape($inbound);
7970: }
7971: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7972: ':'.&escape($action).':'.&escape($ownername).':'.
7973: &escape($ownerdomain).':'.&escape($fullname).':'.
7974: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7975: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7976: my @items = split(/&/,$response);
7977: foreach my $item (@items) {
7978: my ($key,$value) = split('=',$item);
7979: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7980: }
7981: }
7982: }
7983: return \%crsreqresponse;
7984: }
7985:
1.679 raeburn 7986: # ------------------------------------------------------- Course Group routines
7987:
7988: sub get_coursegroups {
1.809 raeburn 7989: my ($cdom,$cnum,$group,$namespace) = @_;
7990: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7991: }
7992:
1.679 raeburn 7993: sub modify_coursegroup {
7994: my ($cdom,$cnum,$groupsettings) = @_;
7995: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7996: }
7997:
1.809 raeburn 7998: sub toggle_coursegroup_status {
7999: my ($cdom,$cnum,$group,$action) = @_;
8000: my ($from_namespace,$to_namespace);
8001: if ($action eq 'delete') {
8002: $from_namespace = 'coursegroups';
8003: $to_namespace = 'deleted_groups';
8004: } else {
8005: $from_namespace = 'deleted_groups';
8006: $to_namespace = 'coursegroups';
8007: }
8008: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8009: if (my $tmp = &error(%curr_group)) {
8010: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8011: return ('read error',$tmp);
8012: } else {
8013: my %savedsettings = %curr_group;
1.809 raeburn 8014: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8015: my $deloutcome;
8016: if ($result eq 'ok') {
1.809 raeburn 8017: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8018: } else {
8019: return ('write error',$result);
8020: }
8021: if ($deloutcome eq 'ok') {
8022: return 'ok';
8023: } else {
8024: return ('delete error',$deloutcome);
8025: }
8026: }
8027: }
8028:
1.679 raeburn 8029: sub modify_group_roles {
1.957 raeburn 8030: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8031: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8032: my $role = 'gr/'.&escape($userprivs);
8033: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8034: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8035: if ($result eq 'ok') {
8036: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8037: }
1.679 raeburn 8038: return $result;
8039: }
8040:
8041: sub modify_coursegroup_membership {
8042: my ($cdom,$cnum,$membership) = @_;
8043: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8044: return $result;
8045: }
8046:
1.682 raeburn 8047: sub get_active_groups {
8048: my ($udom,$uname,$cdom,$cnum) = @_;
8049: my $now = time;
8050: my %groups = ();
8051: foreach my $key (keys(%env)) {
1.811 albertel 8052: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8053: my ($start,$end) = split(/\./,$env{$key});
8054: if (($end!=0) && ($end<$now)) { next; }
8055: if (($start!=0) && ($start>$now)) { next; }
8056: if ($1 eq $cdom && $2 eq $cnum) {
8057: $groups{$3} = $env{$key} ;
8058: }
8059: }
8060: }
8061: return %groups;
8062: }
8063:
1.683 raeburn 8064: sub get_group_membership {
8065: my ($cdom,$cnum,$group) = @_;
8066: return(&dump('groupmembership',$cdom,$cnum,$group));
8067: }
8068:
8069: sub get_users_groups {
8070: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8071: my @usersgroups;
1.683 raeburn 8072: my $cachetime=1800;
8073:
8074: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8075: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8076: if (defined($cached)) {
1.734 albertel 8077: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8078: } else {
8079: $grouplist = '';
1.816 raeburn 8080: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8081: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8082: my $access_end = $env{'course.'.$courseid.
8083: '.default_enrollment_end_date'};
8084: my $now = time;
8085: foreach my $key (keys(%roleshash)) {
8086: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8087: my $group = $1;
8088: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8089: my $start = $2;
8090: my $end = $1;
8091: if ($start == -1) { next; } # deleted from group
8092: if (($start!=0) && ($start>$now)) { next; }
8093: if (($end!=0) && ($end<$now)) {
8094: if ($access_end && $access_end < $now) {
8095: if ($access_end - $end < 86400) {
8096: push(@usersgroups,$group);
1.733 raeburn 8097: }
8098: }
1.817 raeburn 8099: next;
1.733 raeburn 8100: }
1.817 raeburn 8101: push(@usersgroups,$group);
1.683 raeburn 8102: }
8103: }
8104: }
1.817 raeburn 8105: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8106: $grouplist = join(':',@usersgroups);
8107: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8108: }
1.733 raeburn 8109: return @usersgroups;
1.683 raeburn 8110: }
8111:
8112: sub devalidate_getgroups_cache {
8113: my ($udom,$uname,$cdom,$cnum)=@_;
8114: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8115:
1.683 raeburn 8116: my $hashid="$udom:$uname:$courseid";
8117: &devalidate_cache_new('getgroups',$hashid);
8118: }
8119:
1.12 www 8120: # ------------------------------------------------------------------ Plain Text
8121:
8122: sub plaintext {
1.988 raeburn 8123: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8124: if ($short =~ m{^cr/}) {
1.758 albertel 8125: return (split('/',$short))[-1];
8126: }
1.742 raeburn 8127: if (!defined($cid)) {
8128: $cid = $env{'request.course.id'};
8129: }
8130: my %rolenames = (
1.1008 raeburn 8131: Course => 'std',
8132: Community => 'alt1',
1.742 raeburn 8133: );
1.1037 raeburn 8134: if ($cid ne '') {
8135: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8136: unless ($forcedefault) {
8137: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8138: &Apache::lonlocal::mt_escape(\$roletext);
8139: return &Apache::lonlocal::mt($roletext);
8140: }
8141: }
8142: }
8143: if ((defined($type)) && (defined($rolenames{$type})) &&
8144: (defined($rolenames{$type})) &&
8145: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8146: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8147: } elsif ($cid ne '') {
8148: my $crstype = $env{'course.'.$cid.'.type'};
8149: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8150: (defined($prp{$short}{$rolenames{$crstype}}))) {
8151: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8152: }
1.742 raeburn 8153: }
1.1037 raeburn 8154: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8155: }
8156:
8157: # ----------------------------------------------------------------- Assign Role
8158:
8159: sub assignrole {
1.957 raeburn 8160: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8161: $context)=@_;
1.21 www 8162: my $mrole;
8163: if ($role =~ /^cr\//) {
1.393 www 8164: my $cwosec=$url;
1.811 albertel 8165: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8166: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8167: my $refused = 1;
8168: if ($context eq 'requestcourses') {
8169: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8170: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8171: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8172: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8173: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8174: if ($crsenv{'internal.courseowner'} eq
8175: $env{'user.name'}.':'.$env{'user.domain'}) {
8176: $refused = '';
8177: }
8178: }
8179: }
8180: }
8181: }
8182: if ($refused) {
8183: &logthis('Refused custom assignrole: '.
8184: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8185: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8186: return 'refused';
8187: }
1.104 www 8188: }
1.21 www 8189: $mrole='cr';
1.678 raeburn 8190: } elsif ($role =~ /^gr\//) {
8191: my $cwogrp=$url;
1.811 albertel 8192: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8193: unless (&allowed('mdg',$cwogrp)) {
8194: &logthis('Refused group assignrole: '.
8195: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8196: $env{'user.name'}.' at '.$env{'user.domain'});
8197: return 'refused';
8198: }
8199: $mrole='gr';
1.21 www 8200: } else {
1.82 www 8201: my $cwosec=$url;
1.811 albertel 8202: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8203: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8204: my $refused;
8205: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8206: if (!(&allowed('c'.$role,$url))) {
8207: $refused = 1;
8208: }
8209: } else {
8210: $refused = 1;
8211: }
1.947 raeburn 8212: if ($refused) {
1.1045 raeburn 8213: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8214: if (!$selfenroll && $context eq 'course') {
8215: my %crsenv;
8216: if ($role eq 'cc' || $role eq 'co') {
8217: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8218: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8219: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8220: if ($crsenv{'internal.courseowner'} eq
8221: $env{'user.name'}.':'.$env{'user.domain'}) {
8222: $refused = '';
8223: }
8224: }
8225: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8226: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8227: if ($crsenv{'internal.courseowner'} eq
8228: $env{'user.name'}.':'.$env{'user.domain'}) {
8229: $refused = '';
8230: }
8231: }
8232: }
8233: }
8234: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8235: $refused = '';
1.1017 raeburn 8236: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8237: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8238: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8239: my $wrongcc;
8240: if ($cnum =~ /^$match_community$/) {
8241: $wrongcc = 1 if ($role eq 'cc');
8242: } else {
8243: $wrongcc = 1 if ($role eq 'co');
8244: }
8245: unless ($wrongcc) {
8246: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8247: if ($crsenv{'internal.courseowner'} eq
8248: $env{'user.name'}.':'.$env{'user.domain'}) {
8249: $refused = '';
8250: }
1.1017 raeburn 8251: }
8252: }
1.1172.2.9 raeburn 8253: } elsif ($context eq 'requestauthor') {
8254: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8255: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8256: if ($env{'environment.requestauthor'} eq 'automatic') {
8257: $refused = '';
8258: } else {
8259: my %domdefaults = &get_domain_defaults($udom);
8260: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8261: my $checkbystatus;
8262: if ($env{'user.adv'}) {
8263: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8264: if ($disposition eq 'automatic') {
8265: $refused = '';
8266: } elsif ($disposition eq '') {
8267: $checkbystatus = 1;
8268: }
8269: } else {
8270: $checkbystatus = 1;
8271: }
8272: if ($checkbystatus) {
8273: if ($env{'environment.inststatus'}) {
8274: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8275: foreach my $type (@inststatuses) {
8276: if (($type ne '') &&
8277: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8278: $refused = '';
8279: }
8280: }
8281: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8282: $refused = '';
8283: }
8284: }
8285: }
8286: }
8287: }
1.1017 raeburn 8288: }
8289: if ($refused) {
1.947 raeburn 8290: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8291: ' '.$role.' '.$end.' '.$start.' by '.
8292: $env{'user.name'}.' at '.$env{'user.domain'});
8293: return 'refused';
8294: }
1.932 raeburn 8295: }
1.1131 raeburn 8296: } elsif ($role eq 'au') {
8297: if ($url ne '/'.$udom.'/') {
8298: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8299: ' to assign author role for '.$uname.':'.$udom.
8300: ' in domain: '.$url.' refused (wrong domain).');
8301: return 'refused';
8302: }
1.104 www 8303: }
1.21 www 8304: $mrole=$role;
8305: }
1.620 albertel 8306: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8307: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8308: if ($end) { $command.='_'.$end; }
1.21 www 8309: if ($start) {
8310: if ($end) {
1.81 www 8311: $command.='_'.$start;
1.21 www 8312: } else {
1.81 www 8313: $command.='_0_'.$start;
1.21 www 8314: }
8315: }
1.739 raeburn 8316: my $origstart = $start;
8317: my $origend = $end;
1.957 raeburn 8318: my $delflag;
1.357 www 8319: # actually delete
8320: if ($deleteflag) {
1.373 www 8321: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8322: # modify command to delete the role
1.620 albertel 8323: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8324: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8325: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8326: # set start and finish to negative values for userrolelog
8327: $start=-1;
8328: $end=-1;
1.957 raeburn 8329: $delflag = 1;
1.357 www 8330: }
8331: }
8332: # send command
1.349 www 8333: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8334: # log new user role if status is ok
1.349 www 8335: if ($answer eq 'ok') {
1.663 raeburn 8336: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8337: if (($role eq 'cc') || ($role eq 'in') ||
8338: ($role eq 'ep') || ($role eq 'ad') ||
8339: ($role eq 'ta') || ($role eq 'st') ||
8340: ($role=~/^cr/) || ($role eq 'gr') ||
8341: ($role eq 'co')) {
1.1172.2.13 raeburn 8342: # for course roles, perform group memberships changes triggered by role change.
8343: unless ($role =~ /^gr/) {
8344: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8345: $origstart,$selfenroll,$context);
8346: }
1.1172.2.9 raeburn 8347: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8348: $selfenroll,$context);
8349: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8350: ($role eq 'au') || ($role eq 'dc')) {
8351: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8352: $context);
8353: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8354: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8355: $context);
8356: }
1.1053 raeburn 8357: if ($role eq 'cc') {
8358: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8359: }
1.349 www 8360: }
8361: return $answer;
1.169 harris41 8362: }
8363:
1.1053 raeburn 8364: sub autoupdate_coowners {
8365: my ($url,$end,$start,$uname,$udom) = @_;
8366: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8367: if (($cdom ne '') && ($cnum ne '')) {
8368: my $now = time;
8369: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8370: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8371: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8372: my $instcode = $coursehash{'internal.coursecode'};
8373: if ($instcode ne '') {
1.1056 raeburn 8374: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8375: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8376: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8377: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8378: if ($result eq 'valid') {
8379: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8380: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8381: push(@newcoowners,$coowner);
8382: }
8383: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8384: push(@newcoowners,$uname.':'.$udom);
8385: }
8386: @newcoowners = sort(@newcoowners);
8387: } else {
8388: push(@newcoowners,$uname.':'.$udom);
8389: }
8390: } else {
8391: if ($coursehash{'internal.co-owners'}) {
8392: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8393: unless ($coowner eq $uname.':'.$udom) {
8394: push(@newcoowners,$coowner);
8395: }
8396: }
8397: unless (@newcoowners > 0) {
8398: $delcoowners = 1;
8399: $coowners = '';
8400: }
8401: }
8402: }
8403: if (@newcoowners || $delcoowners) {
8404: &store_coowners($cdom,$cnum,$coursehash{'home'},
8405: $delcoowners,@newcoowners);
8406: }
8407: }
8408: }
8409: }
8410: }
8411: }
8412: }
8413:
8414: sub store_coowners {
8415: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8416: my $cid = $cdom.'_'.$cnum;
8417: my ($coowners,$delresult,$putresult);
8418: if (@newcoowners) {
8419: $coowners = join(',',@newcoowners);
8420: my %coownershash = (
8421: 'internal.co-owners' => $coowners,
8422: );
8423: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8424: if ($putresult eq 'ok') {
8425: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8426: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8427: }
8428: }
8429: }
8430: if ($delcoowners) {
8431: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8432: if ($delresult eq 'ok') {
8433: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8434: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8435: }
8436: }
8437: }
8438: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8439: my %crsinfo =
8440: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8441: if (ref($crsinfo{$cid}) eq 'HASH') {
8442: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8443: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8444: }
8445: }
8446: }
8447:
1.169 harris41 8448: # -------------------------------------------------- Modify user authentication
1.197 www 8449: # Overrides without validation
8450:
1.169 harris41 8451: sub modifyuserauth {
8452: my ($udom,$uname,$umode,$upass)=@_;
8453: my $uhome=&homeserver($uname,$udom);
1.197 www 8454: unless (&allowed('mau',$udom)) { return 'refused'; }
8455: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8456: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8457: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8458: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8459: &escape($upass),$uhome);
1.620 albertel 8460: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8461: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8462: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8463: &log($udom,,$uname,$uhome,
1.620 albertel 8464: 'Authentication changed by '.$env{'user.domain'}.', '.
8465: $env{'user.name'}.', '.$umode.
1.197 www 8466: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8467: unless ($reply eq 'ok') {
1.197 www 8468: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8469: return 'error: '.$reply;
8470: }
1.170 harris41 8471: return 'ok';
1.80 www 8472: }
8473:
1.81 www 8474: # --------------------------------------------------------------- Modify a user
1.80 www 8475:
1.81 www 8476: sub modifyuser {
1.206 matthew 8477: my ($udom, $uname, $uid,
8478: $umode, $upass, $first,
8479: $middle, $last, $gene,
1.1058 raeburn 8480: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8481: $udom= &LONCAPA::clean_domain($udom);
8482: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8483: my $showcandelete = 'none';
8484: if (ref($candelete) eq 'ARRAY') {
8485: if (@{$candelete} > 0) {
8486: $showcandelete = join(', ',@{$candelete});
8487: }
8488: }
1.81 www 8489: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8490: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8491: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8492: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8493: ' desiredhome not specified').
1.620 albertel 8494: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8495: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8496: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8497: my $newuser;
8498: if ($uhome eq 'no_host') {
8499: $newuser = 1;
8500: }
1.80 www 8501: # ----------------------------------------------------------------- Create User
1.406 albertel 8502: if (($uhome eq 'no_host') &&
8503: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8504: my $unhome='';
1.844 albertel 8505: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8506: $unhome = $desiredhome;
1.620 albertel 8507: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8508: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8509: } else { # load balancing routine for determining $unhome
1.81 www 8510: my $loadm=10000000;
1.841 albertel 8511: my %servers = &get_servers($udom,'library');
8512: foreach my $tryserver (keys(%servers)) {
8513: my $answer=reply('load',$tryserver);
8514: if (($answer=~/\d+/) && ($answer<$loadm)) {
8515: $loadm=$answer;
8516: $unhome=$tryserver;
8517: }
1.80 www 8518: }
8519: }
8520: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8521: return 'error: unable to find a home server for '.$uname.
8522: ' in domain '.$udom;
1.80 www 8523: }
8524: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8525: &escape($upass),$unhome);
8526: unless ($reply eq 'ok') {
8527: return 'error: '.$reply;
8528: }
1.230 stredwic 8529: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8530: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8531: return 'error: unable verify users home machine.';
1.80 www 8532: }
1.209 matthew 8533: } # End of creation of new user
1.80 www 8534: # ---------------------------------------------------------------------- Add ID
8535: if ($uid) {
8536: $uid=~tr/A-Z/a-z/;
8537: my %uidhash=&idrget($udom,$uname);
1.196 www 8538: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8539: && (!$forceid)) {
1.80 www 8540: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8541: return 'error: user id "'.$uid.'" does not match '.
8542: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8543: }
8544: } else {
8545: &idput($udom,($uname => $uid));
8546: }
8547: }
8548: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8549: my @tmp=&get('environment',
1.899 raeburn 8550: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8551: 'permanentemail','inststatus'],
1.134 albertel 8552: $udom,$uname);
1.1075 raeburn 8553: my (%names,%oldnames);
1.313 matthew 8554: if ($tmp[0] =~ m/^error:.*/) {
8555: %names=();
8556: } else {
8557: %names = @tmp;
1.1075 raeburn 8558: %oldnames = %names;
1.313 matthew 8559: }
1.388 www 8560: #
1.1058 raeburn 8561: # If name, email and/or uid are blank (e.g., because an uploaded file
8562: # of users did not contain them), do not overwrite existing values
8563: # unless field is in $candelete array ref.
8564: #
8565:
8566: my @fields = ('firstname','middlename','lastname','generation',
8567: 'permanentemail','id');
8568: my %newvalues;
8569: if (ref($candelete) eq 'ARRAY') {
8570: foreach my $field (@fields) {
8571: if (grep(/^\Q$field\E$/,@{$candelete})) {
8572: if ($field eq 'firstname') {
8573: $names{$field} = $first;
8574: } elsif ($field eq 'middlename') {
8575: $names{$field} = $middle;
8576: } elsif ($field eq 'lastname') {
8577: $names{$field} = $last;
8578: } elsif ($field eq 'generation') {
8579: $names{$field} = $gene;
8580: } elsif ($field eq 'permanentemail') {
8581: $names{$field} = $email;
8582: } elsif ($field eq 'id') {
8583: $names{$field} = $uid;
8584: }
8585: }
8586: }
8587: }
1.388 www 8588: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8589: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8590: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8591: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8592: if ($email) {
8593: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8594: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8595: }
1.899 raeburn 8596: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8597: if (defined($inststatus)) {
8598: $names{'inststatus'} = '';
8599: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8600: if (ref($usertypes) eq 'HASH') {
8601: my @okstatuses;
8602: foreach my $item (split(/:/,$inststatus)) {
8603: if (defined($usertypes->{$item})) {
8604: push(@okstatuses,$item);
8605: }
8606: }
8607: if (@okstatuses) {
8608: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8609: }
8610: }
8611: }
1.1075 raeburn 8612: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8613: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8614: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8615: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8616: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8617: } else {
8618: $logmsg .= ' during self creation';
8619: }
1.1075 raeburn 8620: my $changed;
8621: if ($newuser) {
8622: $changed = 1;
8623: } else {
8624: foreach my $field (@fields) {
8625: if ($names{$field} ne $oldnames{$field}) {
8626: $changed = 1;
8627: last;
8628: }
8629: }
8630: }
8631: unless ($changed) {
8632: $logmsg = 'No changes in user information needed for: '.$logmsg;
8633: &logthis($logmsg);
8634: return 'ok';
8635: }
8636: my $reply = &put('environment', \%names, $udom,$uname);
8637: if ($reply ne 'ok') {
8638: return 'error: '.$reply;
8639: }
1.1087 raeburn 8640: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8641: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8642: }
1.1075 raeburn 8643: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8644: &devalidate_cache_new('namescache',$uname.':'.$udom);
8645: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8646: &logthis($logmsg);
1.134 albertel 8647: return 'ok';
1.80 www 8648: }
8649:
1.81 www 8650: # -------------------------------------------------------------- Modify student
1.80 www 8651:
1.81 www 8652: sub modifystudent {
8653: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8654: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8655: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8656: if (!$cid) {
1.620 albertel 8657: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8658: return 'not_in_class';
8659: }
1.80 www 8660: }
8661: # --------------------------------------------------------------- Make the user
1.81 www 8662: my $reply=&modifyuser
1.209 matthew 8663: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8664: $desiredhome,$email,$inststatus);
1.80 www 8665: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8666: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8667: # student's environment
1.297 matthew 8668: $uid = undef if (!$forceid);
1.455 albertel 8669: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8670: $gene,$usec,$end,$start,$type,$locktype,
8671: $cid,$selfenroll,$context,$credits);
1.297 matthew 8672: return $reply;
8673: }
8674:
8675: sub modify_student_enrollment {
1.1172.2.23 raeburn 8676: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8677: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8678: my ($cdom,$cnum,$chome);
8679: if (!$cid) {
1.620 albertel 8680: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8681: return 'not_in_class';
8682: }
1.620 albertel 8683: $cdom=$env{'course.'.$cid.'.domain'};
8684: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8685: } else {
8686: ($cdom,$cnum)=split(/_/,$cid);
8687: }
1.620 albertel 8688: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8689: if (!$chome) {
1.457 raeburn 8690: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8691: }
1.455 albertel 8692: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8693: # Make sure the user exists
1.81 www 8694: my $uhome=&homeserver($uname,$udom);
8695: if (($uhome eq '') || ($uhome eq 'no_host')) {
8696: return 'error: no such user';
8697: }
1.297 matthew 8698: # Get student data if we were not given enough information
8699: if (!defined($first) || $first eq '' ||
8700: !defined($last) || $last eq '' ||
8701: !defined($uid) || $uid eq '' ||
8702: !defined($middle) || $middle eq '' ||
8703: !defined($gene) || $gene eq '') {
1.294 matthew 8704: # They did not supply us with enough data to enroll the student, so
8705: # we need to pick up more information.
1.297 matthew 8706: my %tmp = &get('environment',
1.294 matthew 8707: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8708: ,$udom,$uname);
8709:
1.800 albertel 8710: #foreach my $key (keys(%tmp)) {
8711: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8712: #}
1.294 matthew 8713: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8714: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8715: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8716: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8717: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8718: }
1.556 albertel 8719: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8720: my $user = "$uname:$udom";
8721: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8722: my $reply=cput('classlist',
1.1148 raeburn 8723: {$user =>
1.1172.2.19 raeburn 8724: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8725: $cdom,$cnum);
1.1148 raeburn 8726: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8727: &devalidate_getsection_cache($udom,$uname,$cid);
8728: } else {
1.81 www 8729: return 'error: '.$reply;
8730: }
1.297 matthew 8731: # Add student role to user
1.83 www 8732: my $uurl='/'.$cid;
1.81 www 8733: $uurl=~s/\_/\//g;
8734: if ($usec) {
8735: $uurl.='/'.$usec;
8736: }
1.1148 raeburn 8737: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8738: $selfenroll,$context);
8739: if ($result ne 'ok') {
8740: if ($old_entry{$user} ne '') {
8741: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8742: } else {
8743: $reply = &del('classlist',[$user],$cdom,$cnum);
8744: }
8745: }
8746: return $result;
1.21 www 8747: }
8748:
1.556 albertel 8749: sub format_name {
8750: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8751: my $name;
8752: if ($first ne 'lastname') {
8753: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8754: } else {
8755: if ($lastname=~/\S/) {
8756: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8757: $name=~s/\s+,/,/;
8758: } else {
8759: $name.= $firstname.' '.$middlename.' '.$generation;
8760: }
8761: }
8762: $name=~s/^\s+//;
8763: $name=~s/\s+$//;
8764: $name=~s/\s+/ /g;
8765: return $name;
8766: }
8767:
1.84 www 8768: # ------------------------------------------------- Write to course preferences
8769:
8770: sub writecoursepref {
8771: my ($courseid,%prefs)=@_;
8772: $courseid=~s/^\///;
8773: $courseid=~s/\_/\//g;
8774: my ($cdomain,$cnum)=split(/\//,$courseid);
8775: my $chome=homeserver($cnum,$cdomain);
8776: if (($chome eq '') || ($chome eq 'no_host')) {
8777: return 'error: no such course';
8778: }
8779: my $cstring='';
1.800 albertel 8780: foreach my $pref (keys(%prefs)) {
8781: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8782: }
1.84 www 8783: $cstring=~s/\&$//;
8784: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8785: }
8786:
8787: # ---------------------------------------------------------- Make/modify course
8788:
8789: sub createcourse {
1.741 raeburn 8790: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8791: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8792: $url=&declutter($url);
8793: my $cid='';
1.1028 raeburn 8794: if ($context eq 'requestcourses') {
8795: my $can_create = 0;
8796: my ($ownername,$ownerdom) = split(':',$course_owner);
8797: if ($udom eq $ownerdom) {
8798: if (&usertools_access($ownername,$ownerdom,$category,undef,
8799: $context)) {
8800: $can_create = 1;
8801: }
8802: } else {
8803: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8804: $category);
8805: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8806: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8807: if (@curr > 0) {
8808: my @options = qw(approval validate autolimit);
8809: my $optregex = join('|',@options);
8810: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8811: $can_create = 1;
8812: }
8813: }
8814: }
8815: }
8816: if ($can_create) {
8817: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8818: unless (&allowed('ccc',$udom)) {
8819: return 'refused';
8820: }
1.1017 raeburn 8821: }
8822: } else {
8823: return 'refused';
8824: }
1.1028 raeburn 8825: } elsif (!&allowed('ccc',$udom)) {
8826: return 'refused';
1.84 www 8827: }
1.1011 raeburn 8828: # --------------------------------------------------------------- Get Unique ID
8829: my $uname;
8830: if ($cnum =~ /^$match_courseid$/) {
8831: my $chome=&homeserver($cnum,$udom,'true');
8832: if (($chome eq '') || ($chome eq 'no_host')) {
8833: $uname = $cnum;
8834: } else {
1.1038 raeburn 8835: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8836: }
8837: } else {
1.1038 raeburn 8838: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8839: }
8840: return $uname if ($uname =~ /^error/);
8841: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8842: if (!defined($course_server)) {
8843: if (defined(&domain($udom,'primary'))) {
8844: $course_server = &domain($udom,'primary');
8845: } else {
8846: $course_server = $env{'user.home'};
8847: }
8848: }
8849: my %host_servers =
8850: &Apache::lonnet::get_servers($udom,'library');
8851: unless ($host_servers{$course_server}) {
8852: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8853: }
1.84 www 8854: # ------------------------------------------------------------- Make the course
8855: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8856: $course_server);
1.84 www 8857: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8858: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8859: if (($uhome eq '') || ($uhome eq 'no_host')) {
8860: return 'error: no such course';
8861: }
1.271 www 8862: # ----------------------------------------------------------------- Course made
1.516 raeburn 8863: # log existence
1.1029 raeburn 8864: my $now = time;
1.918 raeburn 8865: my $newcourse = {
8866: $udom.'_'.$uname => {
1.921 raeburn 8867: description => $description,
8868: inst_code => $inst_code,
8869: owner => $course_owner,
8870: type => $crstype,
1.1029 raeburn 8871: creator => $env{'user.name'}.':'.
8872: $env{'user.domain'},
8873: created => $now,
8874: context => $context,
1.918 raeburn 8875: },
8876: };
1.921 raeburn 8877: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8878: # set toplevel url
1.271 www 8879: my $topurl=$url;
8880: unless ($nonstandard) {
8881: # ------------------------------------------ For standard courses, make top url
8882: my $mapurl=&clutter($url);
1.278 www 8883: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8884: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8885: <map>
8886: <resource id="1" type="start"></resource>
8887: <resource id="2" src="$mapurl"></resource>
8888: <resource id="3" type="finish"></resource>
8889: <link index="1" from="1" to="2"></link>
8890: <link index="2" from="2" to="3"></link>
8891: </map>
8892: ENDINITMAP
8893: $topurl=&declutter(
1.638 albertel 8894: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8895: );
8896: }
8897: # ----------------------------------------------------------- Write preferences
1.84 www 8898: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8899: ('description' => $description,
8900: 'url' => $topurl,
8901: 'internal.creator' => $env{'user.name'}.':'.
8902: $env{'user.domain'},
8903: 'internal.created' => $now,
8904: 'internal.creationcontext' => $context)
8905: );
1.84 www 8906: return '/'.$udom.'/'.$uname;
8907: }
8908:
1.1011 raeburn 8909: # ------------------------------------------------------------------- Create ID
8910: sub generate_coursenum {
1.1038 raeburn 8911: my ($udom,$crstype) = @_;
1.1011 raeburn 8912: my $domdesc = &domain($udom);
8913: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8914: my $first;
8915: if ($crstype eq 'Community') {
8916: $first = '0';
8917: } else {
8918: $first = int(1+rand(9));
8919: }
8920: my $uname=$first.
1.1011 raeburn 8921: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8922: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8923: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8924: # ----------------------------------------------- Make sure that does not exist
8925: my $uhome=&homeserver($uname,$udom,'true');
8926: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8927: if ($crstype eq 'Community') {
8928: $first = '0';
8929: } else {
8930: $first = int(1+rand(9));
8931: }
8932: $uname=$first.
1.1011 raeburn 8933: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8934: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8935: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8936: $uhome=&homeserver($uname,$udom,'true');
8937: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8938: return 'error: unable to generate unique course-ID';
8939: }
8940: }
8941: return $uname;
8942: }
8943:
1.813 albertel 8944: sub is_course {
1.1167 droeschl 8945: my ($cdom, $cnum) = scalar(@_) == 1 ?
8946: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8947:
8948: return unless $cdom and $cnum;
8949:
8950: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8951: '.');
8952:
1.1172.2.23 raeburn 8953: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8954: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8955: }
8956:
1.1015 raeburn 8957: sub store_userdata {
8958: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8959: my $result;
1.1016 raeburn 8960: if ($datakey ne '') {
1.1013 raeburn 8961: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8962: if ($udom eq '' || $uname eq '') {
8963: $udom = $env{'user.domain'};
8964: $uname = $env{'user.name'};
8965: }
8966: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8967: if (($uhome eq '') || ($uhome eq 'no_host')) {
8968: $result = 'error: no_host';
8969: } else {
8970: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8971: $storehash->{'host'} = $perlvar{'lonHostID'};
8972:
8973: my $namevalue='';
8974: foreach my $key (keys(%{$storehash})) {
8975: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8976: }
8977: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8978: unless ($namespace eq 'courserequests') {
8979: $datakey = &escape($datakey);
8980: }
1.1105 raeburn 8981: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8982: $namevalue,$uhome);
1.1013 raeburn 8983: }
8984: } else {
8985: $result = 'error: data to store was not a hash reference';
8986: }
8987: } else {
8988: $result= 'error: invalid requestkey';
8989: }
8990: return $result;
8991: }
8992:
1.21 www 8993: # ---------------------------------------------------------- Assign Custom Role
8994:
8995: sub assigncustomrole {
1.957 raeburn 8996: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8997: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8998: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8999: }
9000:
9001: # ----------------------------------------------------------------- Revoke Role
9002:
9003: sub revokerole {
1.957 raeburn 9004: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9005: my $now=time;
1.965 raeburn 9006: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9007: }
9008:
9009: # ---------------------------------------------------------- Revoke Custom Role
9010:
9011: sub revokecustomrole {
1.957 raeburn 9012: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9013: my $now=time;
1.357 www 9014: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9015: $deleteflag,$selfenroll,$context);
1.17 www 9016: }
9017:
1.533 banghart 9018: # ------------------------------------------------------------ Disk usage
1.535 albertel 9019: sub diskusage {
1.955 raeburn 9020: my ($udom,$uname,$directorypath,$getpropath)=@_;
9021: $directorypath =~ s/\/$//;
9022: my $listing=&reply('du2:'.&escape($directorypath).':'
9023: .&escape($getpropath).':'.&escape($uname).':'
9024: .&escape($udom),homeserver($uname,$udom));
9025: if ($listing eq 'unknown_cmd') {
9026: if ($getpropath) {
9027: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9028: }
9029: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9030: }
1.514 albertel 9031: return $listing;
1.512 banghart 9032: }
9033:
1.566 banghart 9034: sub is_locked {
1.1096 raeburn 9035: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9036: my @check;
9037: my $is_locked;
1.1093 raeburn 9038: push (@check,$file_name);
1.613 albertel 9039: my %locked = &get('file_permissions',\@check,
1.620 albertel 9040: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9041: my ($tmp)=keys(%locked);
9042: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9043:
1.566 banghart 9044: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9045: $is_locked = 'false';
9046: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9047: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9048: $is_locked = 'true';
1.1096 raeburn 9049: if (ref($which) eq 'ARRAY') {
9050: push(@{$which},$entry);
9051: } else {
9052: last;
9053: }
1.745 raeburn 9054: }
9055: }
1.566 banghart 9056: } else {
9057: $is_locked = 'false';
9058: }
1.1093 raeburn 9059: return $is_locked;
1.566 banghart 9060: }
9061:
1.759 albertel 9062: sub declutter_portfile {
9063: my ($file) = @_;
1.833 albertel 9064: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9065: return $file;
9066: }
9067:
1.559 banghart 9068: # ------------------------------------------------------------- Mark as Read Only
9069:
9070: sub mark_as_readonly {
9071: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9072: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9073: my ($tmp)=keys(%current_permissions);
9074: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9075: foreach my $file (@{$files}) {
1.759 albertel 9076: $file = &declutter_portfile($file);
1.561 banghart 9077: push(@{$current_permissions{$file}},$what);
1.559 banghart 9078: }
1.613 albertel 9079: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9080: return;
9081: }
9082:
1.572 banghart 9083: # ------------------------------------------------------------Save Selected Files
9084:
9085: sub save_selected_files {
9086: my ($user, $path, @files) = @_;
9087: my $filename = $user."savedfiles";
1.573 banghart 9088: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9089: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9090: foreach my $file (@files) {
1.620 albertel 9091: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9092: }
9093: foreach my $file (@other_files) {
1.574 banghart 9094: print (OUT $file."\n");
1.572 banghart 9095: }
1.574 banghart 9096: close (OUT);
1.572 banghart 9097: return 'ok';
9098: }
9099:
1.574 banghart 9100: sub clear_selected_files {
9101: my ($user) = @_;
9102: my $filename = $user."savedfiles";
1.1117 foxr 9103: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9104: print (OUT undef);
9105: close (OUT);
9106: return ("ok");
9107: }
9108:
1.572 banghart 9109: sub files_in_path {
9110: my ($user, $path) = @_;
9111: my $filename = $user."savedfiles";
9112: my %return_files;
1.1117 foxr 9113: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9114: while (my $line_in = <IN>) {
1.574 banghart 9115: chomp ($line_in);
9116: my @paths_and_file = split (m!/!, $line_in);
9117: my $file_part = pop (@paths_and_file);
9118: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9119: $path_part.='/';
9120: my $path_and_file = $path_part.$file_part;
9121: if ($path_part eq $path) {
9122: $return_files{$file_part}= 'selected';
9123: }
9124: }
1.574 banghart 9125: close (IN);
9126: return (\%return_files);
1.572 banghart 9127: }
9128:
9129: # called in portfolio select mode, to show files selected NOT in current directory
9130: sub files_not_in_path {
9131: my ($user, $path) = @_;
9132: my $filename = $user."savedfiles";
9133: my @return_files;
9134: my $path_part;
1.1117 foxr 9135: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9136: while (my $line = <IN>) {
1.572 banghart 9137: #ok, I know it's clunky, but I want it to work
1.800 albertel 9138: my @paths_and_file = split(m|/|, $line);
9139: my $file_part = pop(@paths_and_file);
9140: chomp($file_part);
9141: my $path_part = join('/', @paths_and_file);
1.572 banghart 9142: $path_part .= '/';
9143: my $path_and_file = $path_part.$file_part;
9144: if ($path_part ne $path) {
1.800 albertel 9145: push(@return_files, ($path_and_file));
1.572 banghart 9146: }
9147: }
1.800 albertel 9148: close(OUT);
1.574 banghart 9149: return (@return_files);
1.572 banghart 9150: }
9151:
1.745 raeburn 9152: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9153:
1.745 raeburn 9154: sub get_portfile_permissions {
9155: my ($domain,$user) = @_;
1.613 albertel 9156: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9157: my ($tmp)=keys(%current_permissions);
9158: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9159: return \%current_permissions;
9160: }
9161:
9162: #---------------------------------------------Get portfolio file access controls
9163:
1.749 raeburn 9164: sub get_access_controls {
1.745 raeburn 9165: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9166: my %access;
9167: my $real_file = $file;
9168: $file =~ s/\.meta$//;
1.745 raeburn 9169: if (defined($file)) {
1.749 raeburn 9170: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9171: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9172: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9173: }
9174: }
1.745 raeburn 9175: } else {
1.749 raeburn 9176: foreach my $key (keys(%{$current_permissions})) {
9177: if ($key =~ /\0accesscontrol$/) {
9178: if (defined($group)) {
9179: if ($key !~ m-^\Q$group\E/-) {
9180: next;
9181: }
9182: }
9183: my ($fullpath) = split(/\0/,$key);
9184: if (ref($$current_permissions{$key}) eq 'HASH') {
9185: foreach my $control (keys(%{$$current_permissions{$key}})) {
9186: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9187: }
9188: }
9189: }
9190: }
9191: }
9192: return %access;
9193: }
9194:
9195: sub modify_access_controls {
9196: my ($file_name,$changes,$domain,$user)=@_;
9197: my ($outcome,$deloutcome);
9198: my %store_permissions;
9199: my %new_values;
9200: my %new_control;
9201: my %translation;
9202: my @deletions = ();
9203: my $now = time;
9204: if (exists($$changes{'activate'})) {
9205: if (ref($$changes{'activate'}) eq 'HASH') {
9206: my @newitems = sort(keys(%{$$changes{'activate'}}));
9207: my $numnew = scalar(@newitems);
9208: for (my $i=0; $i<$numnew; $i++) {
9209: my $newkey = $newitems[$i];
9210: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9211: if ($newkey =~ /^\d+:/) {
9212: $newkey =~ s/^(\d+)/$newid/;
9213: $translation{$1} = $newid;
9214: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9215: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9216: $translation{$1} = $newid;
9217: }
1.749 raeburn 9218: $new_values{$file_name."\0".$newkey} =
9219: $$changes{'activate'}{$newitems[$i]};
9220: $new_control{$newkey} = $now;
9221: }
9222: }
9223: }
9224: my %todelete;
9225: my %changed_items;
9226: foreach my $action ('delete','update') {
9227: if (exists($$changes{$action})) {
9228: if (ref($$changes{$action}) eq 'HASH') {
9229: foreach my $key (keys(%{$$changes{$action}})) {
9230: my ($itemnum) = ($key =~ /^([^:]+):/);
9231: if ($action eq 'delete') {
9232: $todelete{$itemnum} = 1;
9233: } else {
9234: $changed_items{$itemnum} = $key;
9235: }
9236: }
1.745 raeburn 9237: }
9238: }
1.749 raeburn 9239: }
9240: # get lock on access controls for file.
9241: my $lockhash = {
9242: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9243: ':'.$env{'user.domain'},
9244: };
9245: my $tries = 0;
9246: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9247:
9248: while (($gotlock ne 'ok') && $tries <3) {
9249: $tries ++;
9250: sleep 1;
9251: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9252: }
9253: if ($gotlock eq 'ok') {
9254: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9255: my ($tmp)=keys(%curr_permissions);
9256: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9257: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9258: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9259: if (ref($curr_controls) eq 'HASH') {
9260: foreach my $control_item (keys(%{$curr_controls})) {
9261: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9262: if (defined($todelete{$itemnum})) {
9263: push(@deletions,$file_name."\0".$control_item);
9264: } else {
9265: if (defined($changed_items{$itemnum})) {
9266: $new_control{$changed_items{$itemnum}} = $now;
9267: push(@deletions,$file_name."\0".$control_item);
9268: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9269: } else {
9270: $new_control{$control_item} = $$curr_controls{$control_item};
9271: }
9272: }
1.745 raeburn 9273: }
9274: }
9275: }
1.970 raeburn 9276: my ($group);
9277: if (&is_course($domain,$user)) {
9278: ($group,my $file) = split(/\//,$file_name,2);
9279: }
1.749 raeburn 9280: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9281: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9282: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9283: # remove lock
9284: my @del_lock = ($file_name."\0".'locked_access_records');
9285: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9286: my $sqlresult =
1.970 raeburn 9287: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9288: $group);
1.749 raeburn 9289: } else {
9290: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9291: }
1.749 raeburn 9292: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9293: }
9294:
1.827 raeburn 9295: sub make_public_indefinitely {
9296: my ($requrl) = @_;
9297: my $now = time;
9298: my $action = 'activate';
9299: my $aclnum = 0;
9300: if (&is_portfolio_url($requrl)) {
9301: my (undef,$udom,$unum,$file_name,$group) =
9302: &parse_portfolio_url($requrl);
9303: my $current_perms = &get_portfile_permissions($udom,$unum);
9304: my %access_controls = &get_access_controls($current_perms,
9305: $group,$file_name);
9306: foreach my $key (keys(%{$access_controls{$file_name}})) {
9307: my ($num,$scope,$end,$start) =
9308: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9309: if ($scope eq 'public') {
9310: if ($start <= $now && $end == 0) {
9311: $action = 'none';
9312: } else {
9313: $action = 'update';
9314: $aclnum = $num;
9315: }
9316: last;
9317: }
9318: }
9319: if ($action eq 'none') {
9320: return 'ok';
9321: } else {
9322: my %changes;
9323: my $newend = 0;
9324: my $newstart = $now;
9325: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9326: $changes{$action}{$newkey} = {
9327: type => 'public',
9328: time => {
9329: start => $newstart,
9330: end => $newend,
9331: },
9332: };
9333: my ($outcome,$deloutcome,$new_values,$translation) =
9334: &modify_access_controls($file_name,\%changes,$udom,$unum);
9335: return $outcome;
9336: }
9337: } else {
9338: return 'invalid';
9339: }
9340: }
9341:
1.745 raeburn 9342: #------------------------------------------------------Get Marked as Read Only
9343:
9344: sub get_marked_as_readonly {
9345: my ($domain,$user,$what,$group) = @_;
9346: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9347: my @readonly_files;
1.629 banghart 9348: my $cmp1=$what;
9349: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9350: while (my ($file_name,$value) = each(%{$current_permissions})) {
9351: if (defined($group)) {
9352: if ($file_name !~ m-^\Q$group\E/-) {
9353: next;
9354: }
9355: }
1.561 banghart 9356: if (ref($value) eq "ARRAY"){
9357: foreach my $stored_what (@{$value}) {
1.629 banghart 9358: my $cmp2=$stored_what;
1.759 albertel 9359: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9360: $cmp2=join('',@{$stored_what});
1.745 raeburn 9361: }
1.629 banghart 9362: if ($cmp1 eq $cmp2) {
1.561 banghart 9363: push(@readonly_files, $file_name);
1.745 raeburn 9364: last;
1.563 banghart 9365: } elsif (!defined($what)) {
9366: push(@readonly_files, $file_name);
1.745 raeburn 9367: last;
1.561 banghart 9368: }
9369: }
1.745 raeburn 9370: }
1.561 banghart 9371: }
9372: return @readonly_files;
9373: }
1.577 banghart 9374: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9375:
1.577 banghart 9376: sub get_marked_as_readonly_hash {
1.745 raeburn 9377: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9378: my %readonly_files;
1.745 raeburn 9379: while (my ($file_name,$value) = each(%{$current_permissions})) {
9380: if (defined($group)) {
9381: if ($file_name !~ m-^\Q$group\E/-) {
9382: next;
9383: }
9384: }
1.577 banghart 9385: if (ref($value) eq "ARRAY"){
9386: foreach my $stored_what (@{$value}) {
1.745 raeburn 9387: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9388: foreach my $lock_descriptor(@{$stored_what}) {
9389: if ($lock_descriptor eq 'graded') {
9390: $readonly_files{$file_name} = 'graded';
9391: } elsif ($lock_descriptor eq 'handback') {
9392: $readonly_files{$file_name} = 'handback';
9393: } else {
9394: if (!exists($readonly_files{$file_name})) {
9395: $readonly_files{$file_name} = 'locked';
9396: }
9397: }
1.745 raeburn 9398: }
1.750 banghart 9399: }
1.577 banghart 9400: }
9401: }
9402: }
9403: return %readonly_files;
9404: }
1.559 banghart 9405: # ------------------------------------------------------------ Unmark as Read Only
9406:
9407: sub unmark_as_readonly {
1.629 banghart 9408: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9409: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9410: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9411: $file_name = &declutter_portfile($file_name);
1.634 albertel 9412: my $symb_crs = $what;
9413: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9414: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9415: my ($tmp)=keys(%current_permissions);
9416: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9417: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9418: foreach my $file (@readonly_files) {
1.759 albertel 9419: my $clean_file = &declutter_portfile($file);
9420: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9421: my $current_locks = $current_permissions{$file};
1.563 banghart 9422: my @new_locks;
9423: my @del_keys;
9424: if (ref($current_locks) eq "ARRAY"){
9425: foreach my $locker (@{$current_locks}) {
1.632 albertel 9426: my $compare=$locker;
1.749 raeburn 9427: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9428: $compare=join('',@{$locker});
1.746 raeburn 9429: if ($compare ne $symb_crs) {
9430: push(@new_locks, $locker);
9431: }
1.563 banghart 9432: }
9433: }
1.650 albertel 9434: if (scalar(@new_locks) > 0) {
1.563 banghart 9435: $current_permissions{$file} = \@new_locks;
9436: } else {
9437: push(@del_keys, $file);
1.613 albertel 9438: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9439: delete($current_permissions{$file});
1.563 banghart 9440: }
9441: }
1.561 banghart 9442: }
1.613 albertel 9443: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9444: return;
9445: }
1.512 banghart 9446:
1.17 www 9447: # ------------------------------------------------------------ Directory lister
9448:
9449: sub dirlist {
1.955 raeburn 9450: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9451: $uri=~s/^\///;
9452: $uri=~s/\/$//;
1.253 stredwic 9453: my ($udom, $uname);
1.955 raeburn 9454: if ($getuserdir) {
1.253 stredwic 9455: $udom = $userdomain;
9456: $uname = $username;
1.955 raeburn 9457: } else {
9458: (undef,$udom,$uname)=split(/\//,$uri);
9459: if(defined($userdomain)) {
9460: $udom = $userdomain;
9461: }
9462: if(defined($username)) {
9463: $uname = $username;
9464: }
1.253 stredwic 9465: }
1.955 raeburn 9466: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9467:
1.955 raeburn 9468: $dirRoot = $perlvar{'lonDocRoot'};
9469: if (defined($getpropath)) {
9470: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9471: $dirRoot =~ s/\/$//;
1.955 raeburn 9472: } elsif (defined($getuserdir)) {
9473: my $subdir=$uname.'__';
9474: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9475: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9476: ."/$udom/$subdir/$uname";
9477: } elsif (defined($alternateRoot)) {
9478: $dirRoot = $alternateRoot;
1.751 banghart 9479: }
1.253 stredwic 9480:
9481: if($udom) {
9482: if($uname) {
1.1135 raeburn 9483: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9484: if ($uhome eq 'no_host') {
9485: return ([],'no_host');
9486: }
1.955 raeburn 9487: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9488: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9489: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9490: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9491: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9492: } else {
9493: @listing_results = map { &unescape($_); } split(/:/,$listing);
9494: }
1.605 matthew 9495: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9496: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9497: @listing_results = split(/:/,$listing);
9498: } else {
9499: @listing_results = map { &unescape($_); } split(/:/,$listing);
9500: }
1.1135 raeburn 9501: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9502: ($listing eq 'rejected') || ($listing eq 'refused') ||
9503: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9504: return ([],$listing);
9505: } else {
9506: return (\@listing_results);
1.1135 raeburn 9507: }
1.955 raeburn 9508: } elsif(!$alternateRoot) {
1.1136 raeburn 9509: my (%allusers,%listerror);
1.841 albertel 9510: my %servers = &get_servers($udom,'library');
1.955 raeburn 9511: foreach my $tryserver (keys(%servers)) {
9512: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9513: &escape($udom),$tryserver);
9514: if ($listing eq 'unknown_cmd') {
9515: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9516: $udom, $tryserver);
9517: } else {
9518: @listing_results = map { &unescape($_); } split(/:/,$listing);
9519: }
1.841 albertel 9520: if ($listing eq 'unknown_cmd') {
9521: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9522: $udom, $tryserver);
9523: @listing_results = split(/:/,$listing);
9524: } else {
9525: @listing_results =
9526: map { &unescape($_); } split(/:/,$listing);
9527: }
1.1136 raeburn 9528: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9529: ($listing eq 'rejected') || ($listing eq 'refused') ||
9530: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9531: $listerror{$tryserver} = $listing;
9532: } else {
1.841 albertel 9533: foreach my $line (@listing_results) {
9534: my ($entry) = split(/&/,$line,2);
9535: $allusers{$entry} = 1;
9536: }
9537: }
1.253 stredwic 9538: }
1.1136 raeburn 9539: my @alluserslist=();
1.800 albertel 9540: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9541: push(@alluserslist,$user.'&user');
1.253 stredwic 9542: }
1.1136 raeburn 9543: return (\@alluserslist);
1.253 stredwic 9544: } else {
1.1136 raeburn 9545: return ([],'missing username');
1.253 stredwic 9546: }
1.955 raeburn 9547: } elsif(!defined($getpropath)) {
1.1136 raeburn 9548: my $path = $perlvar{'lonDocRoot'}.'/res/';
9549: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9550: return (\@all_domains);
1.955 raeburn 9551: } else {
1.1136 raeburn 9552: return ([],'missing domain');
1.275 stredwic 9553: }
9554: }
9555:
9556: # --------------------------------------------- GetFileTimestamp
9557: # This function utilizes dirlist and returns the date stamp for
9558: # when it was last modified. It will also return an error of -1
9559: # if an error occurs
9560:
9561: sub GetFileTimestamp {
1.955 raeburn 9562: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9563: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9564: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9565: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9566: undef,$getuserdir);
9567: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9568: return -1;
9569: }
9570: if (ref($fileref) eq 'ARRAY') {
9571: my @stats = split('&',$fileref->[0]);
1.375 matthew 9572: # @stats contains first the filename, then the stat output
9573: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9574: } else {
9575: return -1;
1.253 stredwic 9576: }
1.26 www 9577: }
9578:
1.712 albertel 9579: sub stat_file {
9580: my ($uri) = @_;
1.787 albertel 9581: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9582:
1.955 raeburn 9583: my ($udom,$uname,$file);
1.712 albertel 9584: if ($uri =~ m-^/(uploaded|editupload)/-) {
9585: ($udom,$uname,$file) =
1.811 albertel 9586: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9587: $file = 'userfiles/'.$file;
9588: }
9589: if ($uri =~ m-^/res/-) {
9590: ($udom,$uname) =
1.807 albertel 9591: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9592: $file = $uri;
9593: }
9594:
9595: if (!$udom || !$uname || !$file) {
9596: # unable to handle the uri
9597: return ();
9598: }
1.956 raeburn 9599: my $getpropath;
9600: if ($file =~ /^userfiles\//) {
9601: $getpropath = 1;
9602: }
1.1136 raeburn 9603: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9604: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9605: return ();
9606: } else {
9607: if (ref($listref) eq 'ARRAY') {
9608: my @stats = split('&',$listref->[0]);
9609: shift(@stats); #filename is first
9610: return @stats;
9611: }
1.712 albertel 9612: }
9613: return ();
9614: }
9615:
1.26 www 9616: # -------------------------------------------------------- Value of a Condition
9617:
1.713 albertel 9618: # gets the value of a specific preevaluated condition
9619: # stored in the string $env{user.state.<cid>}
9620: # or looks up a condition reference in the bighash and if if hasn't
9621: # already been evaluated recurses into docondval to get the value of
9622: # the condition, then memoizing it to
9623: # $env{user.state.<cid>.<condition>}
1.40 www 9624: sub directcondval {
9625: my $number=shift;
1.620 albertel 9626: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9627: &Apache::lonuserstate::evalstate();
9628: }
1.713 albertel 9629: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9630: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9631: } elsif ($number =~ /^_/) {
9632: my $sub_condition;
9633: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9634: &GDBM_READER(),0640)) {
9635: $sub_condition=$bighash{'conditions'.$number};
9636: untie(%bighash);
9637: }
9638: my $value = &docondval($sub_condition);
1.949 raeburn 9639: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9640: return $value;
9641: }
1.620 albertel 9642: if ($env{'user.state.'.$env{'request.course.id'}}) {
9643: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9644: } else {
9645: return 2;
9646: }
9647: }
9648:
1.713 albertel 9649: # get the collection of conditions for this resource
1.26 www 9650: sub condval {
9651: my $condidx=shift;
1.54 www 9652: my $allpathcond='';
1.713 albertel 9653: foreach my $cond (split(/\|/,$condidx)) {
9654: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9655: $allpathcond.=
9656: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9657: }
1.191 harris41 9658: }
1.54 www 9659: $allpathcond=~s/\|$//;
1.713 albertel 9660: return &docondval($allpathcond);
9661: }
9662:
9663: #evaluates an expression of conditions
9664: sub docondval {
9665: my ($allpathcond) = @_;
9666: my $result=0;
9667: if ($env{'request.course.id'}
9668: && defined($allpathcond)) {
9669: my $operand='|';
9670: my @stack;
9671: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9672: if ($chunk eq '(') {
9673: push @stack,($operand,$result);
9674: } elsif ($chunk eq ')') {
9675: my $before=pop @stack;
9676: if (pop @stack eq '&') {
9677: $result=$result>$before?$before:$result;
9678: } else {
9679: $result=$result>$before?$result:$before;
9680: }
9681: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9682: $operand=$chunk;
9683: } else {
9684: my $new=directcondval($chunk);
9685: if ($operand eq '&') {
9686: $result=$result>$new?$new:$result;
9687: } else {
9688: $result=$result>$new?$result:$new;
9689: }
9690: }
9691: }
1.26 www 9692: }
9693: return $result;
1.421 albertel 9694: }
9695:
9696: # ---------------------------------------------------- Devalidate courseresdata
9697:
9698: sub devalidatecourseresdata {
9699: my ($coursenum,$coursedomain)=@_;
9700: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9701: &devalidate_cache_new('courseres',$hashid);
1.28 www 9702: }
9703:
1.763 www 9704:
1.200 www 9705: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9706: #
9707: # Parameters:
9708: # $coursenum - Number of the course.
9709: # $coursedomain - Domain at which the course was created.
9710: # Returns:
9711: # A hash of the course parameters along (I think) with timestamps
9712: # and version info.
1.877 foxr 9713:
1.624 albertel 9714: sub get_courseresdata {
9715: my ($coursenum,$coursedomain)=@_;
1.200 www 9716: my $coursehom=&homeserver($coursenum,$coursedomain);
9717: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9718: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9719: my %dumpreply;
1.417 albertel 9720: unless (defined($cached)) {
1.624 albertel 9721: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9722: $result=\%dumpreply;
1.251 albertel 9723: my ($tmp) = keys(%dumpreply);
9724: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9725: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9726: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9727: return $tmp;
1.416 albertel 9728: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9729: $result=undef;
1.599 albertel 9730: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9731: }
9732: }
1.624 albertel 9733: return $result;
9734: }
9735:
1.633 albertel 9736: sub devalidateuserresdata {
9737: my ($uname,$udom)=@_;
9738: my $hashid="$udom:$uname";
9739: &devalidate_cache_new('userres',$hashid);
9740: }
9741:
1.624 albertel 9742: sub get_userresdata {
9743: my ($uname,$udom)=@_;
9744: #most student don\'t have any data set, check if there is some data
9745: if (&EXT_cache_status($udom,$uname)) { return undef; }
9746:
9747: my $hashid="$udom:$uname";
9748: my ($result,$cached)=&is_cached_new('userres',$hashid);
9749: if (!defined($cached)) {
9750: my %resourcedata=&dump('resourcedata',$udom,$uname);
9751: $result=\%resourcedata;
9752: &do_cache_new('userres',$hashid,$result,600);
9753: }
9754: my ($tmp)=keys(%$result);
9755: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9756: return $result;
9757: }
9758: #error 2 occurs when the .db doesn't exist
9759: if ($tmp!~/error: 2 /) {
1.672 albertel 9760: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9761: " Trying to get resource data for ".
9762: $uname." at ".$udom.": ".
9763: $tmp."</font>");
9764: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9765: #&EXT_cache_set($udom,$uname);
9766: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9767: undef($tmp); # not really an error so don't send it back
1.624 albertel 9768: }
9769: return $tmp;
9770: }
1.879 foxr 9771: #----------------------------------------------- resdata - return resource data
9772: # Purpose:
9773: # Return resource data for either users or for a course.
9774: # Parameters:
9775: # $name - Course/user name.
9776: # $domain - Name of the domain the user/course is registered on.
9777: # $type - Type of thing $name is (must be 'course' or 'user'
9778: # @which - Array of names of resources desired.
9779: # Returns:
9780: # The value of the first reasource in @which that is found in the
9781: # resource hash.
9782: # Exceptional Conditions:
9783: # If the $type passed in is not valid (not the string 'course' or
9784: # 'user', an undefined reference is returned.
9785: # If none of the resources are found, an undef is returned
1.624 albertel 9786: sub resdata {
9787: my ($name,$domain,$type,@which)=@_;
9788: my $result;
9789: if ($type eq 'course') {
9790: $result=&get_courseresdata($name,$domain);
9791: } elsif ($type eq 'user') {
9792: $result=&get_userresdata($name,$domain);
9793: }
9794: if (!ref($result)) { return $result; }
1.251 albertel 9795: foreach my $item (@which) {
1.927 albertel 9796: if (defined($result->{$item->[0]})) {
9797: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9798: }
1.250 albertel 9799: }
1.291 albertel 9800: return undef;
1.200 www 9801: }
9802:
1.1172.2.31 raeburn 9803: sub get_numsuppfiles {
9804: my ($cnum,$cdom,$ignorecache)=@_;
9805: my $hashid=$cnum.':'.$cdom;
9806: my ($suppcount,$cached);
9807: unless ($ignorecache) {
9808: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9809: }
9810: unless (defined($cached)) {
9811: my $chome=&homeserver($cnum,$cdom);
9812: unless ($chome eq 'no_host') {
9813: ($suppcount,my $errors) = (0,0);
9814: my $suppmap = 'supplemental.sequence';
9815: ($suppcount,$errors) =
9816: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9817: }
9818: &do_cache_new('suppcount',$hashid,$suppcount,600);
9819: }
9820: return $suppcount;
9821: }
9822:
1.379 matthew 9823: #
9824: # EXT resource caching routines
9825: #
9826:
9827: sub clear_EXT_cache_status {
1.383 albertel 9828: &delenv('cache.EXT.');
1.379 matthew 9829: }
9830:
9831: sub EXT_cache_status {
9832: my ($target_domain,$target_user) = @_;
1.383 albertel 9833: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9834: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9835: # We know already the user has no data
9836: return 1;
9837: } else {
9838: return 0;
9839: }
9840: }
9841:
9842: sub EXT_cache_set {
9843: my ($target_domain,$target_user) = @_;
1.383 albertel 9844: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9845: #&appenv({$cachename => time});
1.379 matthew 9846: }
9847:
1.28 www 9848: # --------------------------------------------------------- Value of a Variable
1.58 www 9849: sub EXT {
1.715 albertel 9850:
1.1172.2.28 raeburn 9851: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9852: unless ($varname) { return ''; }
1.218 albertel 9853: #get real user name/domain, courseid and symb
9854: my $courseid;
1.359 albertel 9855: my $publicuser;
1.427 www 9856: if ($symbparm) {
9857: $symbparm=&get_symb_from_alias($symbparm);
9858: }
1.218 albertel 9859: if (!($uname && $udom)) {
1.790 albertel 9860: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9861: if (!$symbparm) { $symbparm=$cursymb; }
9862: } else {
1.620 albertel 9863: $courseid=$env{'request.course.id'};
1.218 albertel 9864: }
1.48 www 9865: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9866: my $rest;
1.320 albertel 9867: if (defined($therest[0])) {
1.48 www 9868: $rest=join('.',@therest);
9869: } else {
9870: $rest='';
9871: }
1.320 albertel 9872:
1.57 www 9873: my $qualifierrest=$qualifier;
9874: if ($rest) { $qualifierrest.='.'.$rest; }
9875: my $spacequalifierrest=$space;
9876: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9877: if ($realm eq 'user') {
1.48 www 9878: # --------------------------------------------------------------- user.resource
9879: if ($space eq 'resource') {
1.651 albertel 9880: if ( (defined($Apache::lonhomework::parsing_a_problem)
9881: || defined($Apache::lonhomework::parsing_a_task))
9882: &&
1.744 albertel 9883: ($symbparm eq &symbread()) ) {
9884: # if we are in the middle of processing the resource the
9885: # get the value we are planning on committing
9886: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9887: return $Apache::lonhomework::results{$qualifierrest};
9888: } else {
9889: return $Apache::lonhomework::history{$qualifierrest};
9890: }
1.335 albertel 9891: } else {
1.359 albertel 9892: my %restored;
1.620 albertel 9893: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9894: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9895: } else {
9896: %restored=&restore($symbparm,$courseid,$udom,$uname);
9897: }
1.335 albertel 9898: return $restored{$qualifierrest};
9899: }
1.48 www 9900: # ----------------------------------------------------------------- user.access
9901: } elsif ($space eq 'access') {
1.218 albertel 9902: # FIXME - not supporting calls for a specific user
1.48 www 9903: return &allowed($qualifier,$rest);
9904: # ------------------------------------------ user.preferences, user.environment
9905: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9906: if (($uname eq $env{'user.name'}) &&
9907: ($udom eq $env{'user.domain'})) {
9908: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9909: } else {
1.359 albertel 9910: my %returnhash;
9911: if (!$publicuser) {
9912: %returnhash=&userenvironment($udom,$uname,
9913: $qualifierrest);
9914: }
1.218 albertel 9915: return $returnhash{$qualifierrest};
9916: }
1.48 www 9917: # ----------------------------------------------------------------- user.course
9918: } elsif ($space eq 'course') {
1.218 albertel 9919: # FIXME - not supporting calls for a specific user
1.620 albertel 9920: return $env{join('.',('request.course',$qualifier))};
1.48 www 9921: # ------------------------------------------------------------------- user.role
9922: } elsif ($space eq 'role') {
1.218 albertel 9923: # FIXME - not supporting calls for a specific user
1.620 albertel 9924: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9925: if ($qualifier eq 'value') {
9926: return $role;
9927: } elsif ($qualifier eq 'extent') {
9928: return $where;
9929: }
9930: # ----------------------------------------------------------------- user.domain
9931: } elsif ($space eq 'domain') {
1.218 albertel 9932: return $udom;
1.48 www 9933: # ------------------------------------------------------------------- user.name
9934: } elsif ($space eq 'name') {
1.218 albertel 9935: return $uname;
1.48 www 9936: # ---------------------------------------------------- Any other user namespace
1.29 www 9937: } else {
1.359 albertel 9938: my %reply;
9939: if (!$publicuser) {
9940: %reply=&get($space,[$qualifierrest],$udom,$uname);
9941: }
9942: return $reply{$qualifierrest};
1.48 www 9943: }
1.236 www 9944: } elsif ($realm eq 'query') {
9945: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9946: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9947: [$spacequalifierrest]);
1.620 albertel 9948: return $env{'form.'.$spacequalifierrest};
1.236 www 9949: } elsif ($realm eq 'request') {
1.48 www 9950: # ------------------------------------------------------------- request.browser
9951: if ($space eq 'browser') {
1.1145 bisitz 9952: return $env{'browser.'.$qualifier};
1.57 www 9953: # ------------------------------------------------------------ request.filename
9954: } else {
1.620 albertel 9955: return $env{'request.'.$spacequalifierrest};
1.29 www 9956: }
1.28 www 9957: } elsif ($realm eq 'course') {
1.48 www 9958: # ---------------------------------------------------------- course.description
1.620 albertel 9959: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9960: } elsif ($realm eq 'resource') {
1.165 www 9961:
1.620 albertel 9962: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9963: if (!$symbparm) { $symbparm=&symbread(); }
9964: }
1.693 albertel 9965:
1.1172.2.30 raeburn 9966: if ($qualifier eq '') {
9967: if ($space eq 'title') {
9968: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9969: return &gettitle($symbparm);
9970: }
1.693 albertel 9971:
1.1172.2.30 raeburn 9972: if ($space eq 'map') {
9973: my ($map) = &decode_symb($symbparm);
9974: return &symbread($map);
9975: }
9976: if ($space eq 'maptitle') {
9977: my ($map) = &decode_symb($symbparm);
9978: return &gettitle($map);
9979: }
9980: if ($space eq 'filename') {
9981: if ($symbparm) {
9982: return &clutter((&decode_symb($symbparm))[2]);
9983: }
9984: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9985: }
1.1172.2.30 raeburn 9986:
9987: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9988: if ($space eq 'visibleparts') {
9989: my $navmap = Apache::lonnavmaps::navmap->new();
9990: my $item;
9991: if (ref($navmap)) {
9992: my $res = $navmap->getBySymb($symbparm);
9993: my $parts = $res->parts();
9994: if (ref($parts) eq 'ARRAY') {
9995: $item = join(',',@{$parts});
9996: }
9997: undef($navmap);
9998: }
9999: return $item;
10000: }
10001: }
10002: }
1.693 albertel 10003:
10004: my ($section, $group, @groups);
1.593 albertel 10005: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10006: if (($courseid eq '') && ($cid)) {
10007: $courseid = $cid;
10008: }
10009: if (($symbparm && $courseid) &&
10010: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10011:
1.218 albertel 10012: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10013:
1.60 www 10014: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10015: my $symbp=$symbparm;
1.735 albertel 10016: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10017:
10018: my $symbparm=$symbp.'.'.$spacequalifierrest;
10019: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10020:
1.620 albertel 10021: if (($env{'user.name'} eq $uname) &&
10022: ($env{'user.domain'} eq $udom)) {
10023: $section=$env{'request.course.sec'};
1.733 raeburn 10024: @groups = split(/:/,$env{'request.course.groups'});
10025: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10026: } else {
1.539 albertel 10027: if (! defined($usection)) {
1.551 albertel 10028: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10029: } else {
10030: $section = $usection;
10031: }
1.733 raeburn 10032: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10033: }
10034:
10035: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10036: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10037: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10038:
1.593 albertel 10039: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10040: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10041: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10042:
1.60 www 10043: # ----------------------------------------------------------- first, check user
1.624 albertel 10044:
10045: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10046: ([$courselevelr,'resource'],
10047: [$courselevelm,'map' ],
10048: [$courselevel, 'course' ]));
1.931 albertel 10049: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10050:
1.594 albertel 10051: # ------------------------------------------------ second, check some of course
1.684 raeburn 10052: my $coursereply;
1.691 raeburn 10053: if (@groups > 0) {
10054: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10055: $mapparm,$spacequalifierrest);
1.927 albertel 10056: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10057: }
1.96 www 10058:
1.684 raeburn 10059: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10060: $env{'course.'.$courseid.'.domain'},
10061: 'course',
10062: ([$seclevelr, 'resource'],
10063: [$seclevelm, 'map' ],
10064: [$seclevel, 'course' ],
10065: [$courselevelr,'resource']));
10066: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10067:
1.60 www 10068: # ------------------------------------------------------ third, check map parms
1.218 albertel 10069: my %parmhash=();
10070: my $thisparm='';
10071: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10072: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10073: &GDBM_READER(),0640)) {
1.218 albertel 10074: $thisparm=$parmhash{$symbparm};
10075: untie(%parmhash);
10076: }
1.927 albertel 10077: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10078: }
1.594 albertel 10079: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10080:
1.218 albertel 10081: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10082: my $filename;
10083: if (!$symbparm) { $symbparm=&symbread(); }
10084: if ($symbparm) {
1.409 www 10085: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10086: } else {
1.620 albertel 10087: $filename=$env{'request.filename'};
1.282 albertel 10088: }
10089: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10090: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10091: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10092: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10093:
1.927 albertel 10094: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10095: if ($symbparm && defined($courseid) &&
1.620 albertel 10096: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10097: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10098: $env{'course.'.$courseid.'.domain'},
10099: 'course',
1.927 albertel 10100: ([$courselevelm,'map' ],
10101: [$courselevel, 'course']));
10102: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10103: }
1.145 www 10104: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10105: unless ($space eq '0') {
1.336 albertel 10106: my @parts=split(/_/,$space);
10107: my $id=pop(@parts);
10108: my $part=join('_',@parts);
10109: if ($part eq '') { $part='0'; }
1.927 albertel 10110: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10111: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10112: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10113: }
1.395 albertel 10114: if ($recurse) { return undef; }
10115: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10116: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10117: # ---------------------------------------------------- Any other user namespace
10118: } elsif ($realm eq 'environment') {
10119: # ----------------------------------------------------------------- environment
1.620 albertel 10120: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10121: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10122: } else {
1.770 albertel 10123: if ($uname eq 'anonymous' && $udom eq '') {
10124: return '';
10125: }
1.219 albertel 10126: my %returnhash=&userenvironment($udom,$uname,
10127: $spacequalifierrest);
10128: return $returnhash{$spacequalifierrest};
10129: }
1.28 www 10130: } elsif ($realm eq 'system') {
1.48 www 10131: # ----------------------------------------------------------------- system.time
10132: if ($space eq 'time') {
10133: return time;
10134: }
1.696 albertel 10135: } elsif ($realm eq 'server') {
10136: # ----------------------------------------------------------------- system.time
10137: if ($space eq 'name') {
10138: return $ENV{'SERVER_NAME'};
10139: }
1.28 www 10140: }
1.48 www 10141: return '';
1.61 www 10142: }
10143:
1.927 albertel 10144: sub get_reply {
10145: my ($reply_value) = @_;
1.940 raeburn 10146: if (ref($reply_value) eq 'ARRAY') {
10147: if (wantarray) {
10148: return @$reply_value;
10149: }
10150: return $reply_value->[0];
10151: } else {
10152: return $reply_value;
1.927 albertel 10153: }
10154: }
10155:
1.691 raeburn 10156: sub check_group_parms {
10157: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10158: my @groupitems = ();
10159: my $resultitem;
1.927 albertel 10160: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10161: foreach my $group (@{$groups}) {
10162: foreach my $level (@levels) {
1.927 albertel 10163: my $item = $courseid.'.['.$group.'].'.$level->[0];
10164: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10165: }
10166: }
10167: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10168: $env{'course.'.$courseid.'.domain'},
10169: 'course',@groupitems);
10170: return $coursereply;
10171: }
10172:
10173: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10174: my ($courseid,@groups) = @_;
10175: @groups = sort(@groups);
1.691 raeburn 10176: return @groups;
10177: }
10178:
1.395 albertel 10179: sub packages_tab_default {
10180: my ($uri,$varname)=@_;
10181: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10182:
10183: my (@extension,@specifics,$do_default);
10184: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10185: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10186: if ($pack_type eq 'default') {
10187: $do_default=1;
10188: } elsif ($pack_type eq 'extension') {
10189: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10190: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10191: # only look at packages defaults for packages that this id is
1.738 albertel 10192: push(@specifics,[$package,$pack_type,$pack_part]);
10193: }
10194: }
10195: # first look for a package that matches the requested part id
10196: foreach my $package (@specifics) {
10197: my (undef,$pack_type,$pack_part)=@{$package};
10198: next if ($pack_part ne $part);
10199: if (defined($packagetab{"$pack_type&$name&default"})) {
10200: return $packagetab{"$pack_type&$name&default"};
10201: }
10202: }
10203: # look for any possible matching non extension_ package
10204: foreach my $package (@specifics) {
10205: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10206: if (defined($packagetab{"$pack_type&$name&default"})) {
10207: return $packagetab{"$pack_type&$name&default"};
10208: }
1.585 albertel 10209: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10210: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10211: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10212: }
10213: }
1.738 albertel 10214: # look for any posible extension_ match
10215: foreach my $package (@extension) {
10216: my ($package,$pack_type)=@{$package};
10217: if (defined($packagetab{"$pack_type&$name&default"})) {
10218: return $packagetab{"$pack_type&$name&default"};
10219: }
10220: if (defined($packagetab{$package."&$name&default"})) {
10221: return $packagetab{$package."&$name&default"};
10222: }
10223: }
10224: # look for a global default setting
10225: if ($do_default && defined($packagetab{"default&$name&default"})) {
10226: return $packagetab{"default&$name&default"};
10227: }
1.395 albertel 10228: return undef;
10229: }
10230:
1.334 albertel 10231: sub add_prefix_and_part {
10232: my ($prefix,$part)=@_;
10233: my $keyroot;
10234: if (defined($prefix) && $prefix !~ /^__/) {
10235: # prefix that has a part already
10236: $keyroot=$prefix;
10237: } elsif (defined($prefix)) {
10238: # prefix that is missing a part
10239: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10240: } else {
10241: # no prefix at all
10242: if (defined($part)) { $keyroot='_'.$part; }
10243: }
10244: return $keyroot;
10245: }
10246:
1.71 www 10247: # ---------------------------------------------------------------- Get metadata
10248:
1.599 albertel 10249: my %metaentry;
1.1070 www 10250: my %importedpartids;
1.71 www 10251: sub metadata {
1.176 www 10252: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10253: $uri=&declutter($uri);
1.288 albertel 10254: # if it is a non metadata possible uri return quickly
1.529 albertel 10255: if (($uri eq '') ||
10256: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10257: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10258: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10259: return undef;
10260: }
1.1140 www 10261: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10262: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10263: return undef;
1.288 albertel 10264: }
1.73 www 10265: my $filename=$uri;
10266: $uri=~s/\.meta$//;
1.172 www 10267: #
10268: # Is the metadata already cached?
1.177 www 10269: # Look at timestamp of caching
1.172 www 10270: # Everything is cached by the main uri, libraries are never directly cached
10271: #
1.428 albertel 10272: if (!defined($liburi)) {
1.599 albertel 10273: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10274: if (defined($cached)) { return $result->{':'.$what}; }
10275: }
10276: {
1.1069 www 10277: # Imported parts would go here
1.1070 www 10278: my %importedids=();
10279: my @origfileimportpartids=();
1.1069 www 10280: my $importedparts=0;
1.172 www 10281: #
10282: # Is this a recursive call for a library?
10283: #
1.599 albertel 10284: # if (! exists($metacache{$uri})) {
10285: # $metacache{$uri}={};
10286: # }
1.924 albertel 10287: my $cachetime = 60*60;
1.171 www 10288: if ($liburi) {
10289: $liburi=&declutter($liburi);
10290: $filename=$liburi;
1.401 bowersj2 10291: } else {
1.599 albertel 10292: &devalidate_cache_new('meta',$uri);
10293: undef(%metaentry);
1.401 bowersj2 10294: }
1.140 www 10295: my %metathesekeys=();
1.73 www 10296: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10297: my $metastring;
1.1140 www 10298: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10299: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10300: $metastring =
1.929 albertel 10301: &Apache::lonnet::ssi_body($which,
1.924 albertel 10302: ('grade_target' => 'meta'));
10303: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10304: } elsif (($uri !~ m -^(editupload)/-) &&
10305: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10306: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10307: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10308: $metastring=&getfile($file);
1.489 albertel 10309: }
1.208 albertel 10310: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10311: my $token;
1.140 www 10312: undef %metathesekeys;
1.71 www 10313: while ($token=$parser->get_token) {
1.339 albertel 10314: if ($token->[0] eq 'S') {
10315: if (defined($token->[2]->{'package'})) {
1.172 www 10316: #
10317: # This is a package - get package info
10318: #
1.339 albertel 10319: my $package=$token->[2]->{'package'};
10320: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10321: if (defined($token->[2]->{'id'})) {
10322: $keyroot.='_'.$token->[2]->{'id'};
10323: }
1.599 albertel 10324: if ($metaentry{':packages'}) {
10325: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10326: } else {
1.599 albertel 10327: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10328: }
1.736 albertel 10329: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10330: my $part=$keyroot;
10331: $part=~s/^\_//;
1.736 albertel 10332: if ($pack_entry=~/^\Q$package\E\&/ ||
10333: $pack_entry=~/^\Q$package\E_0\&/) {
10334: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10335: # ignore package.tab specified default values
10336: # here &package_tab_default() will fetch those
10337: if ($subp eq 'default') { next; }
1.736 albertel 10338: my $value=$packagetab{$pack_entry};
1.432 albertel 10339: my $unikey;
10340: if ($pack =~ /_0$/) {
10341: $unikey='parameter_0_'.$name;
10342: $part=0;
10343: } else {
10344: $unikey='parameter'.$keyroot.'_'.$name;
10345: }
1.339 albertel 10346: if ($subp eq 'display') {
10347: $value.=' [Part: '.$part.']';
10348: }
1.599 albertel 10349: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10350: $metathesekeys{$unikey}=1;
1.599 albertel 10351: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10352: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10353: }
1.599 albertel 10354: if (defined($metaentry{':'.$unikey.'.default'})) {
10355: $metaentry{':'.$unikey}=
10356: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10357: }
1.339 albertel 10358: }
10359: }
10360: } else {
1.172 www 10361: #
10362: # This is not a package - some other kind of start tag
1.339 albertel 10363: #
10364: my $entry=$token->[1];
1.1068 www 10365: my $unikey='';
1.175 www 10366:
1.339 albertel 10367: if ($entry eq 'import') {
1.175 www 10368: #
10369: # Importing a library here
1.339 albertel 10370: #
1.1067 www 10371: my $location=$parser->get_text('/import');
10372: my $dir=$filename;
10373: $dir=~s|[^/]*$||;
10374: $location=&filelocation($dir,$location);
1.1069 www 10375:
1.1068 www 10376: my $importmode=$token->[2]->{'importmode'};
10377: if ($importmode eq 'problem') {
1.1069 www 10378: # Import as problem/response
1.1068 www 10379: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10380: } elsif ($importmode eq 'part') {
10381: # Import as part(s)
1.1069 www 10382: $importedparts=1;
10383: # We need to get the original file and the imported file to get the part order correct
10384: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10385: # Load and inspect original file
1.1070 www 10386: if ($#origfileimportpartids<0) {
10387: undef(%importedpartids);
10388: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10389: my $origfile=&getfile($origfilelocation);
10390: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10391: }
10392:
1.1069 www 10393: # Load and inspect imported file
10394: my $impfile=&getfile($location);
10395: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10396: if ($#impfilepartids>=0) {
10397: # This problem had parts
1.1070 www 10398: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10399: } else {
10400: # Importing by turning a single problem into a problem part
10401: # It gets the import-tags ID as part-ID
10402: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10403: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10404: }
1.1068 www 10405: } else {
10406: # Normal import
10407: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10408: if (defined($token->[2]->{'id'})) {
10409: $unikey.='_'.$token->[2]->{'id'};
10410: }
1.1067 www 10411: }
10412:
1.339 albertel 10413: if ($depthcount<20) {
1.736 albertel 10414: my $metadata =
10415: &metadata($uri,'keys', $location,$unikey,
10416: $depthcount+1);
10417: foreach my $meta (split(',',$metadata)) {
10418: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10419: $metathesekeys{$meta}=1;
1.339 albertel 10420: }
1.1068 www 10421:
10422: }
1.1067 www 10423: } else {
10424: #
10425: # Not importing, some other kind of non-package, non-library start tag
10426: #
10427: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10428: if (defined($token->[2]->{'id'})) {
10429: $unikey.='_'.$token->[2]->{'id'};
10430: }
1.339 albertel 10431: if (defined($token->[2]->{'name'})) {
10432: $unikey.='_'.$token->[2]->{'name'};
10433: }
10434: $metathesekeys{$unikey}=1;
1.736 albertel 10435: foreach my $param (@{$token->[3]}) {
10436: $metaentry{':'.$unikey.'.'.$param} =
10437: $token->[2]->{$param};
1.339 albertel 10438: }
10439: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10440: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10441: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10442: # only ws inside the tag, and not in default, so use default
10443: # as value
1.599 albertel 10444: $metaentry{':'.$unikey}=$default;
1.908 albertel 10445: } elsif ( $internaltext =~ /\S/ ) {
10446: # something interesting inside the tag
10447: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10448: } else {
1.908 albertel 10449: # no interesting values, don't set a default
1.339 albertel 10450: }
1.172 www 10451: # end of not-a-package not-a-library import
1.339 albertel 10452: }
1.172 www 10453: # end of not-a-package start tag
1.339 albertel 10454: }
1.172 www 10455: # the next is the end of "start tag"
1.339 albertel 10456: }
10457: }
1.483 albertel 10458: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10459: $extension = lc($extension);
10460: if ($extension eq 'htm') { $extension='html'; }
10461:
1.737 albertel 10462: foreach my $key (keys(%packagetab)) {
1.483 albertel 10463: #no specific packages #how's our extension
10464: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10465: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10466: \%metathesekeys);
10467: }
1.883 albertel 10468:
10469: if (!exists($metaentry{':packages'})
10470: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10471: foreach my $key (keys(%packagetab)) {
1.483 albertel 10472: #no specific packages well let's get default then
10473: if ($key!~/^default&/) { next; }
1.488 albertel 10474: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10475: \%metathesekeys);
10476: }
10477: }
1.338 www 10478: # are there custom rights to evaluate
1.599 albertel 10479: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10480:
1.338 www 10481: #
10482: # Importing a rights file here
1.339 albertel 10483: #
10484: unless ($depthcount) {
1.599 albertel 10485: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10486: my $dir=$filename;
10487: $dir=~s|[^/]*$||;
10488: $location=&filelocation($dir,$location);
1.736 albertel 10489: my $rights_metadata =
10490: &metadata($uri,'keys',$location,'_rights',
10491: $depthcount+1);
10492: foreach my $rights (split(',',$rights_metadata)) {
10493: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10494: $metathesekeys{$rights}=1;
1.339 albertel 10495: }
10496: }
10497: }
1.737 albertel 10498: # uniqifiy package listing
10499: my %seen;
10500: my @uniq_packages =
10501: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10502: $metaentry{':packages'} = join(',',@uniq_packages);
10503:
1.1070 www 10504: if ($importedparts) {
10505: # We had imported parts and need to rebuild partorder
10506: $metaentry{':partorder'}='';
10507: $metathesekeys{'partorder'}=1;
10508: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10509: if ($origfileimportpartids[$index] eq 'part') {
10510: # original part, part of the problem
10511: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10512: } else {
10513: # we have imported parts at this position
10514: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10515: }
10516: }
10517: $metaentry{':partorder'}=~s/^\,//;
10518: }
10519:
1.737 albertel 10520: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10521: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10522: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10523: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10524: # this is the end of "was not already recently cached
1.71 www 10525: }
1.599 albertel 10526: return $metaentry{':'.$what};
1.261 albertel 10527: }
10528:
1.488 albertel 10529: sub metadata_create_package_def {
1.483 albertel 10530: my ($uri,$key,$package,$metathesekeys)=@_;
10531: my ($pack,$name,$subp)=split(/\&/,$key);
10532: if ($subp eq 'default') { next; }
10533:
1.599 albertel 10534: if (defined($metaentry{':packages'})) {
10535: $metaentry{':packages'}.=','.$package;
1.483 albertel 10536: } else {
1.599 albertel 10537: $metaentry{':packages'}=$package;
1.483 albertel 10538: }
10539: my $value=$packagetab{$key};
10540: my $unikey;
10541: $unikey='parameter_0_'.$name;
1.599 albertel 10542: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10543: $$metathesekeys{$unikey}=1;
1.599 albertel 10544: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10545: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10546: }
1.599 albertel 10547: if (defined($metaentry{':'.$unikey.'.default'})) {
10548: $metaentry{':'.$unikey}=
10549: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10550: }
10551: }
10552:
1.261 albertel 10553: sub metadata_generate_part0 {
10554: my ($metadata,$metacache,$uri) = @_;
10555: my %allnames;
1.737 albertel 10556: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10557: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10558: my $part=$$metacache{':'.$metakey.'.part'};
10559: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10560: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10561: $allnames{$name}=$part;
10562: }
10563: }
10564: }
10565: foreach my $name (keys(%allnames)) {
10566: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10567: my $key=":parameter_0_$name";
1.261 albertel 10568: $$metacache{"$key.part"}='0';
10569: $$metacache{"$key.name"}=$name;
1.428 albertel 10570: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10571: $allnames{$name}.'_'.$name.
10572: '.type'};
1.428 albertel 10573: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10574: '.display'};
1.644 www 10575: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10576: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10577: $$metacache{"$key.display"}=$olddis;
10578: }
1.71 www 10579: }
10580:
1.764 albertel 10581: # ------------------------------------------------------ Devalidate title cache
10582:
10583: sub devalidate_title_cache {
10584: my ($url)=@_;
10585: if (!$env{'request.course.id'}) { return; }
10586: my $symb=&symbread($url);
10587: if (!$symb) { return; }
10588: my $key=$env{'request.course.id'}."\0".$symb;
10589: &devalidate_cache_new('title',$key);
10590: }
10591:
1.1014 droeschl 10592: # ------------------------------------------------- Get the title of a course
10593:
10594: sub current_course_title {
10595: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10596: }
1.301 www 10597: # ------------------------------------------------- Get the title of a resource
10598:
10599: sub gettitle {
10600: my $urlsymb=shift;
10601: my $symb=&symbread($urlsymb);
1.534 albertel 10602: if ($symb) {
1.620 albertel 10603: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10604: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10605: if (defined($cached)) {
10606: return $result;
10607: }
1.534 albertel 10608: my ($map,$resid,$url)=&decode_symb($symb);
10609: my $title='';
1.907 albertel 10610: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10611: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10612: } else {
10613: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10614: &GDBM_READER(),0640)) {
10615: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10616: $title=$bighash{'title_'.$mapid.'.'.$resid};
10617: untie(%bighash);
10618: }
1.534 albertel 10619: }
10620: $title=~s/\&colon\;/\:/gs;
10621: if ($title) {
1.1159 www 10622: # Remember both $symb and $title for dynamic metadata
10623: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10624: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10625: # Cache this title and then return it
1.599 albertel 10626: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10627: }
10628: $urlsymb=$url;
10629: }
10630: my $title=&metadata($urlsymb,'title');
10631: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10632: return $title;
1.301 www 10633: }
1.613 albertel 10634:
1.614 albertel 10635: sub get_slot {
10636: my ($which,$cnum,$cdom)=@_;
10637: if (!$cnum || !$cdom) {
1.790 albertel 10638: (undef,my $courseid)=&whichuser();
1.620 albertel 10639: $cdom=$env{'course.'.$courseid.'.domain'};
10640: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10641: }
1.703 albertel 10642: my $key=join("\0",'slots',$cdom,$cnum,$which);
10643: my %slotinfo;
10644: if (exists($remembered{$key})) {
10645: $slotinfo{$which} = $remembered{$key};
10646: } else {
10647: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10648: &Apache::lonhomework::showhash(%slotinfo);
10649: my ($tmp)=keys(%slotinfo);
10650: if ($tmp=~/^error:/) { return (); }
10651: $remembered{$key} = $slotinfo{$which};
10652: }
1.616 albertel 10653: if (ref($slotinfo{$which}) eq 'HASH') {
10654: return %{$slotinfo{$which}};
10655: }
10656: return $slotinfo{$which};
1.614 albertel 10657: }
1.1150 raeburn 10658:
10659: sub get_reservable_slots {
10660: my ($cnum,$cdom,$uname,$udom) = @_;
10661: my $now = time;
10662: my $reservable_info;
10663: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10664: if (exists($remembered{$key})) {
10665: $reservable_info = $remembered{$key};
10666: } else {
10667: my %resv;
10668: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10669: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10670: $reservable_info = \%resv;
10671: $remembered{$key} = $reservable_info;
10672: }
10673: return $reservable_info;
10674: }
10675:
10676: sub get_course_slots {
10677: my ($cnum,$cdom) = @_;
10678: my $hashid=$cnum.':'.$cdom;
10679: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10680: if (defined($cached)) {
10681: if (ref($result) eq 'HASH') {
10682: return %{$result};
10683: }
10684: } else {
10685: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10686: my ($tmp) = keys(%slots);
10687: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10688: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10689: return %slots;
10690: }
10691: }
10692: return;
10693: }
10694:
10695: sub devalidate_slots_cache {
10696: my ($cnum,$cdom)=@_;
10697: my $hashid=$cnum.':'.$cdom;
10698: &devalidate_cache_new('allslots',$hashid);
10699: }
10700:
1.1172.2.8 raeburn 10701: sub get_coursechange {
10702: my ($cdom,$cnum) = @_;
10703: if ($cdom eq '' || $cnum eq '') {
10704: return unless ($env{'request.course.id'});
10705: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10706: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10707: }
10708: my $hashid=$cdom.'_'.$cnum;
10709: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10710: if ((defined($cached)) && ($change ne '')) {
10711: return $change;
10712: } else {
10713: my %crshash;
10714: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10715: if ($crshash{'internal.contentchange'} eq '') {
10716: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10717: if ($change eq '') {
10718: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10719: $change = $crshash{'internal.created'};
10720: }
10721: } else {
10722: $change = $crshash{'internal.contentchange'};
10723: }
10724: my $cachetime = 600;
10725: &do_cache_new('crschange',$hashid,$change,$cachetime);
10726: }
10727: return $change;
10728: }
10729:
10730: sub devalidate_coursechange_cache {
10731: my ($cnum,$cdom)=@_;
10732: my $hashid=$cnum.':'.$cdom;
10733: &devalidate_cache_new('crschange',$hashid);
10734: }
10735:
1.31 www 10736: # ------------------------------------------------- Update symbolic store links
10737:
10738: sub symblist {
10739: my ($mapname,%newhash)=@_;
1.438 www 10740: $mapname=&deversion(&declutter($mapname));
1.31 www 10741: my %hash;
1.620 albertel 10742: if (($env{'request.course.fn'}) && (%newhash)) {
10743: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10744: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10745: foreach my $url (keys(%newhash)) {
1.711 albertel 10746: next if ($url eq 'last_known'
10747: && $env{'form.no_update_last_known'});
10748: $hash{declutter($url)}=&encode_symb($mapname,
10749: $newhash{$url}->[1],
10750: $newhash{$url}->[0]);
1.191 harris41 10751: }
1.31 www 10752: if (untie(%hash)) {
10753: return 'ok';
10754: }
10755: }
10756: }
10757: return 'error';
1.212 www 10758: }
10759:
10760: # --------------------------------------------------------------- Verify a symb
10761:
10762: sub symbverify {
1.1172.2.11 raeburn 10763: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10764: my $thisfn=$thisurl;
1.439 www 10765: $thisfn=&declutter($thisfn);
1.215 www 10766: # direct jump to resource in page or to a sequence - will construct own symbs
10767: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10768: # check URL part
1.409 www 10769: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10770:
1.431 www 10771: unless ($url eq $thisfn) { return 0; }
1.213 www 10772:
1.216 www 10773: $symb=&symbclean($symb);
1.510 www 10774: $thisurl=&deversion($thisurl);
1.439 www 10775: $thisfn=&deversion($thisfn);
1.213 www 10776:
10777: my %bighash;
10778: my $okay=0;
1.431 www 10779:
1.620 albertel 10780: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10781: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10782: my $noclutter;
1.1032 raeburn 10783: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10784: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10785: if ($map =~ m{^uploaded/.+\.page$}) {
10786: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10787: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10788: $noclutter = 1;
10789: }
10790: }
10791: my $ids;
10792: if ($noclutter) {
10793: $ids=$bighash{'ids_'.$thisurl};
10794: } else {
10795: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10796: }
1.1102 raeburn 10797: unless ($ids) {
1.1172.2.13 raeburn 10798: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10799: $ids=$bighash{$idkey};
1.216 www 10800: }
10801: if ($ids) {
10802: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10803: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10804: $symb =~ s/\?.+$//;
10805: }
1.800 albertel 10806: foreach my $id (split(/\,/,$ids)) {
10807: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10808: if (
10809: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10810: eq $symb) {
1.1172.2.11 raeburn 10811: if (ref($encstate)) {
10812: $$encstate = $bighash{'encrypted_'.$id};
10813: }
1.1172.2.13 raeburn 10814: if (($env{'request.role.adv'}) ||
10815: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10816: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10817: $okay=1;
10818: last;
10819: }
10820: }
10821: }
1.216 www 10822: }
1.213 www 10823: untie(%bighash);
10824: }
10825: return $okay;
1.31 www 10826: }
10827:
1.210 www 10828: # --------------------------------------------------------------- Clean-up symb
10829:
10830: sub symbclean {
10831: my $symb=shift;
1.568 albertel 10832: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10833: # remove version from map
10834: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10835:
1.210 www 10836: # remove version from URL
10837: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10838:
1.507 www 10839: # remove wrapper
10840:
1.510 www 10841: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10842: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10843: return $symb;
1.409 www 10844: }
10845:
10846: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10847:
10848: sub encode_symb {
10849: my ($map,$resid,$url)=@_;
10850: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10851: }
1.409 www 10852:
10853: sub decode_symb {
1.568 albertel 10854: my $symb=shift;
10855: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10856: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10857: return (&fixversion($map),$resid,&fixversion($url));
10858: }
10859:
10860: sub fixversion {
10861: my $fn=shift;
1.609 banghart 10862: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10863: my %bighash;
10864: my $uri=&clutter($fn);
1.620 albertel 10865: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10866: # is this cached?
1.599 albertel 10867: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10868: if (defined($cached)) { return $result; }
10869: # unfortunately not cached, or expired
1.620 albertel 10870: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10871: &GDBM_READER(),0640)) {
10872: if ($bighash{'version_'.$uri}) {
10873: my $version=$bighash{'version_'.$uri};
1.444 www 10874: unless (($version eq 'mostrecent') ||
10875: ($version==&getversion($uri))) {
1.440 www 10876: $uri=~s/\.(\w+)$/\.$version\.$1/;
10877: }
10878: }
10879: untie %bighash;
1.413 www 10880: }
1.599 albertel 10881: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10882: }
10883:
10884: sub deversion {
10885: my $url=shift;
10886: $url=~s/\.\d+\.(\w+)$/\.$1/;
10887: return $url;
1.210 www 10888: }
10889:
1.31 www 10890: # ------------------------------------------------------ Return symb list entry
10891:
10892: sub symbread {
1.249 www 10893: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10894: my $cache_str;
10895: if ($thisfn ne '') {
10896: $cache_str='request.symbread.cached.'.$thisfn;
10897: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10898: return $env{$cache_str};
10899: }
1.1172.2.13 raeburn 10900: } else {
1.242 www 10901: # no filename provided? try from environment
1.620 albertel 10902: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10903: return $env{$cache_str}=&symbclean($env{'request.symb'});
10904: }
10905: $thisfn=$env{'request.filename'};
1.44 www 10906: }
1.569 albertel 10907: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10908: # is that filename actually a symb? Verify, clean, and return
10909: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10910: if (&symbverify($thisfn,$1)) {
1.620 albertel 10911: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10912: }
1.242 www 10913: }
1.44 www 10914: $thisfn=declutter($thisfn);
1.31 www 10915: my %hash;
1.37 www 10916: my %bighash;
10917: my $syval='';
1.620 albertel 10918: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10919: my $targetfn = $thisfn;
1.609 banghart 10920: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10921: $targetfn = 'adm/wrapper/'.$thisfn;
10922: }
1.687 albertel 10923: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10924: $targetfn=$1;
10925: }
1.620 albertel 10926: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10927: &GDBM_READER(),0640)) {
1.481 raeburn 10928: $syval=$hash{$targetfn};
1.37 www 10929: untie(%hash);
10930: }
10931: # ---------------------------------------------------------- There was an entry
10932: if ($syval) {
1.601 albertel 10933: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10934: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10935: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10936: #return $env{$cache_str}='';
1.601 albertel 10937: #}
10938: #$syval.=$1;
10939: #}
1.37 www 10940: } else {
10941: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10942: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10943: &GDBM_READER(),0640)) {
1.37 www 10944: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10945: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10946: unless ($ids) {
10947: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10948: }
10949: unless ($ids) {
10950: # alias?
10951: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10952: }
1.37 www 10953: if ($ids) {
10954: # ------------------------------------------------------------------- Has ID(s)
10955: my @possibilities=split(/\,/,$ids);
1.39 www 10956: if ($#possibilities==0) {
10957: # ----------------------------------------------- There is only one possibility
1.37 www 10958: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10959: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10960: $resid,$thisfn);
1.249 www 10961: } elsif (!$donotrecurse) {
1.39 www 10962: # ------------------------------------------ There is more than one possibility
10963: my $realpossible=0;
1.800 albertel 10964: foreach my $id (@possibilities) {
10965: my $file=$bighash{'src_'.$id};
1.39 www 10966: if (&allowed('bre',$file)) {
1.800 albertel 10967: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10968: if ($bighash{'map_type_'.$mapid} ne 'page') {
10969: $realpossible++;
1.626 albertel 10970: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10971: $resid,$thisfn);
1.39 www 10972: }
10973: }
1.191 harris41 10974: }
1.39 www 10975: if ($realpossible!=1) { $syval=''; }
1.249 www 10976: } else {
10977: $syval='';
1.37 www 10978: }
10979: }
10980: untie(%bighash)
1.481 raeburn 10981: }
1.31 www 10982: }
1.62 www 10983: if ($syval) {
1.620 albertel 10984: return $env{$cache_str}=$syval;
1.62 www 10985: }
1.31 www 10986: }
1.949 raeburn 10987: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10988: return $env{$cache_str}='';
1.31 www 10989: }
10990:
10991: # ---------------------------------------------------------- Return random seed
10992:
1.32 www 10993: sub numval {
10994: my $txt=shift;
10995: $txt=~tr/A-J/0-9/;
10996: $txt=~tr/a-j/0-9/;
10997: $txt=~tr/K-T/0-9/;
10998: $txt=~tr/k-t/0-9/;
10999: $txt=~tr/U-Z/0-5/;
11000: $txt=~tr/u-z/0-5/;
11001: $txt=~s/\D//g;
1.564 albertel 11002: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11003: return int($txt);
1.368 albertel 11004: }
11005:
1.484 albertel 11006: sub numval2 {
11007: my $txt=shift;
11008: $txt=~tr/A-J/0-9/;
11009: $txt=~tr/a-j/0-9/;
11010: $txt=~tr/K-T/0-9/;
11011: $txt=~tr/k-t/0-9/;
11012: $txt=~tr/U-Z/0-5/;
11013: $txt=~tr/u-z/0-5/;
11014: $txt=~s/\D//g;
11015: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11016: my $total;
11017: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11018: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11019: return int($total);
11020: }
11021:
1.575 albertel 11022: sub numval3 {
11023: use integer;
11024: my $txt=shift;
11025: $txt=~tr/A-J/0-9/;
11026: $txt=~tr/a-j/0-9/;
11027: $txt=~tr/K-T/0-9/;
11028: $txt=~tr/k-t/0-9/;
11029: $txt=~tr/U-Z/0-5/;
11030: $txt=~tr/u-z/0-5/;
11031: $txt=~s/\D//g;
11032: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11033: my $total;
11034: foreach my $val (@txts) { $total+=$val; }
11035: if ($_64bit) { $total=(($total<<32)>>32); }
11036: return $total;
11037: }
11038:
1.675 albertel 11039: sub digest {
11040: my ($data)=@_;
11041: my $digest=&Digest::MD5::md5($data);
11042: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11043: my ($e,$f);
11044: {
11045: use integer;
11046: $e=($a+$b);
11047: $f=($c+$d);
11048: if ($_64bit) {
11049: $e=(($e<<32)>>32);
11050: $f=(($f<<32)>>32);
11051: }
11052: }
11053: if (wantarray) {
11054: return ($e,$f);
11055: } else {
11056: my $g;
11057: {
11058: use integer;
11059: $g=($e+$f);
11060: if ($_64bit) {
11061: $g=(($g<<32)>>32);
11062: }
11063: }
11064: return $g;
11065: }
11066: }
11067:
1.368 albertel 11068: sub latest_rnd_algorithm_id {
1.675 albertel 11069: return '64bit5';
1.366 albertel 11070: }
1.32 www 11071:
1.503 albertel 11072: sub get_rand_alg {
11073: my ($courseid)=@_;
1.790 albertel 11074: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11075: if ($courseid) {
1.620 albertel 11076: return $env{"course.$courseid.rndseed"};
1.503 albertel 11077: }
11078: return &latest_rnd_algorithm_id();
11079: }
11080:
1.562 albertel 11081: sub validCODE {
11082: my ($CODE)=@_;
11083: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11084: return 0;
11085: }
11086:
1.491 albertel 11087: sub getCODE {
1.620 albertel 11088: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11089: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11090: defined($Apache::lonhomework::parsing_a_task) ) &&
11091: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11092: return $Apache::lonhomework::history{'resource.CODE'};
11093: }
11094: return undef;
11095: }
1.1133 foxr 11096: #
11097: # Determines the random seed for a specific context:
11098: #
11099: # parameters:
11100: # symb - in course context the symb for the seed.
11101: # course_id - The course id of the form domain_coursenum.
11102: # domain - Domain for the user.
11103: # course - Course for the user.
11104: # cenv - environment of the course.
11105: #
11106: # NOTE:
11107: # All parameters are picked out of the environment if missing
11108: # or not defined.
11109: # If a symb cannot be determined the current time is used instead.
11110: #
11111: # For a given well defined symb, courside, domain, username,
11112: # and course environment, the seed is reproducible.
11113: #
1.31 www 11114: sub rndseed {
1.1133 foxr 11115: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11116: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11117: if (!defined($symb)) {
1.366 albertel 11118: unless ($symb=$wsymb) { return time; }
11119: }
1.1146 foxr 11120: if (!defined $courseid) {
11121: $courseid=$wcourseid;
11122: }
11123: if (!defined $domain) { $domain=$wdomain; }
11124: if (!defined $username) { $username=$wusername }
1.1133 foxr 11125:
11126: my $which;
11127: if (defined($cenv->{'rndseed'})) {
11128: $which = $cenv->{'rndseed'};
11129: } else {
11130: $which =&get_rand_alg($courseid);
11131: }
1.491 albertel 11132: if (defined(&getCODE())) {
1.675 albertel 11133: if ($which eq '64bit5') {
11134: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11135: } elsif ($which eq '64bit4') {
1.575 albertel 11136: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11137: } else {
11138: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11139: }
1.675 albertel 11140: } elsif ($which eq '64bit5') {
11141: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11142: } elsif ($which eq '64bit4') {
11143: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11144: } elsif ($which eq '64bit3') {
11145: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11146: } elsif ($which eq '64bit2') {
11147: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11148: } elsif ($which eq '64bit') {
11149: return &rndseed_64bit($symb,$courseid,$domain,$username);
11150: }
11151: return &rndseed_32bit($symb,$courseid,$domain,$username);
11152: }
11153:
11154: sub rndseed_32bit {
11155: my ($symb,$courseid,$domain,$username)=@_;
11156: {
11157: use integer;
11158: my $symbchck=unpack("%32C*",$symb) << 27;
11159: my $symbseed=numval($symb) << 22;
11160: my $namechck=unpack("%32C*",$username) << 17;
11161: my $nameseed=numval($username) << 12;
11162: my $domainseed=unpack("%32C*",$domain) << 7;
11163: my $courseseed=unpack("%32C*",$courseid);
11164: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11165: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11166: #&logthis("rndseed :$num:$symb");
1.564 albertel 11167: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11168: return $num;
11169: }
11170: }
11171:
11172: sub rndseed_64bit {
11173: my ($symb,$courseid,$domain,$username)=@_;
11174: {
11175: use integer;
11176: my $symbchck=unpack("%32S*",$symb) << 21;
11177: my $symbseed=numval($symb) << 10;
11178: my $namechck=unpack("%32S*",$username);
11179:
11180: my $nameseed=numval($username) << 21;
11181: my $domainseed=unpack("%32S*",$domain) << 10;
11182: my $courseseed=unpack("%32S*",$courseid);
11183:
11184: my $num1=$symbchck+$symbseed+$namechck;
11185: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11186: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11187: #&logthis("rndseed :$num:$symb");
1.564 albertel 11188: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11189: return "$num1,$num2";
1.155 albertel 11190: }
1.366 albertel 11191: }
11192:
1.443 albertel 11193: sub rndseed_64bit2 {
11194: my ($symb,$courseid,$domain,$username)=@_;
11195: {
11196: use integer;
11197: # strings need to be an even # of cahracters long, it it is odd the
11198: # last characters gets thrown away
11199: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11200: my $symbseed=numval($symb) << 10;
11201: my $namechck=unpack("%32S*",$username.' ');
11202:
11203: my $nameseed=numval($username) << 21;
1.501 albertel 11204: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11205: my $courseseed=unpack("%32S*",$courseid.' ');
11206:
11207: my $num1=$symbchck+$symbseed+$namechck;
11208: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11209: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11210: #&logthis("rndseed :$num:$symb");
1.803 albertel 11211: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11212: return "$num1,$num2";
11213: }
11214: }
11215:
11216: sub rndseed_64bit3 {
11217: my ($symb,$courseid,$domain,$username)=@_;
11218: {
11219: use integer;
11220: # strings need to be an even # of cahracters long, it it is odd the
11221: # last characters gets thrown away
11222: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11223: my $symbseed=numval2($symb) << 10;
11224: my $namechck=unpack("%32S*",$username.' ');
11225:
11226: my $nameseed=numval2($username) << 21;
1.443 albertel 11227: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11228: my $courseseed=unpack("%32S*",$courseid.' ');
11229:
11230: my $num1=$symbchck+$symbseed+$namechck;
11231: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11232: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11233: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11234: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11235:
1.503 albertel 11236: return "$num1:$num2";
1.443 albertel 11237: }
11238: }
11239:
1.575 albertel 11240: sub rndseed_64bit4 {
11241: my ($symb,$courseid,$domain,$username)=@_;
11242: {
11243: use integer;
11244: # strings need to be an even # of cahracters long, it it is odd the
11245: # last characters gets thrown away
11246: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11247: my $symbseed=numval3($symb) << 10;
11248: my $namechck=unpack("%32S*",$username.' ');
11249:
11250: my $nameseed=numval3($username) << 21;
11251: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11252: my $courseseed=unpack("%32S*",$courseid.' ');
11253:
11254: my $num1=$symbchck+$symbseed+$namechck;
11255: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11256: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11257: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11258: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11259:
1.575 albertel 11260: return "$num1:$num2";
11261: }
11262: }
11263:
1.675 albertel 11264: sub rndseed_64bit5 {
11265: my ($symb,$courseid,$domain,$username)=@_;
11266: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11267: return "$num1:$num2";
11268: }
11269:
1.366 albertel 11270: sub rndseed_CODE_64bit {
11271: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11272: {
1.366 albertel 11273: use integer;
1.443 albertel 11274: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11275: my $symbseed=numval2($symb);
1.491 albertel 11276: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11277: my $CODEseed=numval(&getCODE());
1.443 albertel 11278: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11279: my $num1=$symbseed+$CODEchck;
11280: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11281: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11282: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11283: if ($_64bit) { $num1=(($num1<<32)>>32); }
11284: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11285: return "$num1:$num2";
1.366 albertel 11286: }
11287: }
11288:
1.575 albertel 11289: sub rndseed_CODE_64bit4 {
11290: my ($symb,$courseid,$domain,$username)=@_;
11291: {
11292: use integer;
11293: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11294: my $symbseed=numval3($symb);
11295: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11296: my $CODEseed=numval3(&getCODE());
11297: my $courseseed=unpack("%32S*",$courseid.' ');
11298: my $num1=$symbseed+$CODEchck;
11299: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11300: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11301: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11302: if ($_64bit) { $num1=(($num1<<32)>>32); }
11303: if ($_64bit) { $num2=(($num2<<32)>>32); }
11304: return "$num1:$num2";
11305: }
11306: }
11307:
1.675 albertel 11308: sub rndseed_CODE_64bit5 {
11309: my ($symb,$courseid,$domain,$username)=@_;
11310: my $code = &getCODE();
11311: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11312: return "$num1:$num2";
11313: }
11314:
1.366 albertel 11315: sub setup_random_from_rndseed {
11316: my ($rndseed)=@_;
1.503 albertel 11317: if ($rndseed =~/([,:])/) {
11318: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11319: &Math::Random::random_set_seed(abs($num1),abs($num2));
11320: } else {
11321: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11322: }
1.36 albertel 11323: }
11324:
1.474 albertel 11325: sub latest_receipt_algorithm_id {
1.835 albertel 11326: return 'receipt3';
1.474 albertel 11327: }
11328:
1.480 www 11329: sub recunique {
11330: my $fucourseid=shift;
11331: my $unique;
1.835 albertel 11332: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11333: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11334: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11335: } else {
11336: $unique=$perlvar{'lonReceipt'};
11337: }
11338: return unpack("%32C*",$unique);
11339: }
11340:
11341: sub recprefix {
11342: my $fucourseid=shift;
11343: my $prefix;
1.835 albertel 11344: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11345: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11346: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11347: } else {
11348: $prefix=$perlvar{'lonHostID'};
11349: }
11350: return unpack("%32C*",$prefix);
11351: }
11352:
1.76 www 11353: sub ireceipt {
1.474 albertel 11354: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11355:
11356: my $return =&recprefix($fucourseid).'-';
11357:
11358: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11359: $env{'request.state'} eq 'construct') {
11360: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11361: return $return;
11362: }
11363:
1.76 www 11364: my $cuname=unpack("%32C*",$funame);
11365: my $cudom=unpack("%32C*",$fudom);
11366: my $cucourseid=unpack("%32C*",$fucourseid);
11367: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11368: my $cunique=&recunique($fucourseid);
1.474 albertel 11369: my $cpart=unpack("%32S*",$part);
1.835 albertel 11370: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11371:
1.790 albertel 11372: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11373:
11374: $return.= ($cunique%$cuname+
11375: $cunique%$cudom+
11376: $cusymb%$cuname+
11377: $cusymb%$cudom+
11378: $cucourseid%$cuname+
11379: $cucourseid%$cudom+
11380: $cpart%$cuname+
11381: $cpart%$cudom);
11382: } else {
11383: $return.= ($cunique%$cuname+
11384: $cunique%$cudom+
11385: $cusymb%$cuname+
11386: $cusymb%$cudom+
11387: $cucourseid%$cuname+
11388: $cucourseid%$cudom);
11389: }
11390: return $return;
1.76 www 11391: }
11392:
11393: sub receipt {
1.474 albertel 11394: my ($part)=@_;
1.790 albertel 11395: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11396: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11397: }
1.260 ng 11398:
1.790 albertel 11399: sub whichuser {
11400: my ($passedsymb)=@_;
11401: my ($symb,$courseid,$domain,$name,$publicuser);
11402: if (defined($env{'form.grade_symb'})) {
11403: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11404: my $allowed=&allowed('vgr',$tmp_courseid);
11405: if (!$allowed &&
11406: exists($env{'request.course.sec'}) &&
11407: $env{'request.course.sec'} !~ /^\s*$/) {
11408: $allowed=&allowed('vgr',$tmp_courseid.
11409: '/'.$env{'request.course.sec'});
11410: }
11411: if ($allowed) {
11412: ($symb)=&get_env_multiple('form.grade_symb');
11413: $courseid=$tmp_courseid;
11414: ($domain)=&get_env_multiple('form.grade_domain');
11415: ($name)=&get_env_multiple('form.grade_username');
11416: return ($symb,$courseid,$domain,$name,$publicuser);
11417: }
11418: }
11419: if (!$passedsymb) {
11420: $symb=&symbread();
11421: } else {
11422: $symb=$passedsymb;
11423: }
11424: $courseid=$env{'request.course.id'};
11425: $domain=$env{'user.domain'};
11426: $name=$env{'user.name'};
11427: if ($name eq 'public' && $domain eq 'public') {
11428: if (!defined($env{'form.username'})) {
11429: $env{'form.username'}.=time.rand(10000000);
11430: }
11431: $name.=$env{'form.username'};
11432: }
11433: return ($symb,$courseid,$domain,$name,$publicuser);
11434:
11435: }
11436:
1.36 albertel 11437: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11438: # returns either the contents of the file or
11439: # -1 if the file doesn't exist
1.481 raeburn 11440: #
11441: # if the target is a file that was uploaded via DOCS,
11442: # a check will be made to see if a current copy exists on the local server,
11443: # if it does this will be served, otherwise a copy will be retrieved from
11444: # the home server for the course and stored in /home/httpd/html/userfiles on
11445: # the local server.
1.472 albertel 11446:
1.36 albertel 11447: sub getfile {
1.538 albertel 11448: my ($file) = @_;
1.609 banghart 11449: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11450: &repcopy($file);
11451: return &readfile($file);
11452: }
11453:
11454: sub repcopy_userfile {
11455: my ($file)=@_;
1.1142 raeburn 11456: my $londocroot = $perlvar{'lonDocRoot'};
11457: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11458: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11459: my ($cdom,$cnum,$filename) =
1.811 albertel 11460: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11461: my $uri="/uploaded/$cdom/$cnum/$filename";
11462: if (-e "$file") {
1.828 www 11463: # we already have a local copy, check it out
1.538 albertel 11464: my @fileinfo = stat($file);
1.828 www 11465: my $rtncode;
11466: my $info;
1.538 albertel 11467: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11468: if ($lwpresp ne 'ok') {
1.828 www 11469: # there is no such file anymore, even though we had a local copy
1.482 albertel 11470: if ($rtncode eq '404') {
1.538 albertel 11471: unlink($file);
1.482 albertel 11472: }
11473: return -1;
11474: }
11475: if ($info < $fileinfo[9]) {
1.828 www 11476: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11477: return 'ok';
1.828 www 11478: } else {
11479: # the file is outdated, get rid of it
11480: unlink($file);
1.482 albertel 11481: }
1.828 www 11482: }
11483: # one way or the other, at this point, we don't have the file
11484: # construct the correct path for the file
11485: my @parts = ($cdom,$cnum);
11486: if ($filename =~ m|^(.+)/[^/]+$|) {
11487: push @parts, split(/\//,$1);
11488: }
11489: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11490: foreach my $part (@parts) {
11491: $path .= '/'.$part;
11492: if (!-e $path) {
11493: mkdir($path,0770);
1.482 albertel 11494: }
11495: }
1.828 www 11496: # now the path exists for sure
11497: # get a user agent
11498: my $ua=new LWP::UserAgent;
11499: my $transferfile=$file.'.in.transfer';
11500: # FIXME: this should flock
11501: if (-e $transferfile) { return 'ok'; }
11502: my $request;
11503: $uri=~s/^\///;
1.980 raeburn 11504: my $homeserver = &homeserver($cnum,$cdom);
11505: my $protocol = $protocol{$homeserver};
11506: $protocol = 'http' if ($protocol ne 'https');
11507: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11508: my $response=$ua->request($request,$transferfile);
11509: # did it work?
11510: if ($response->is_error()) {
11511: unlink($transferfile);
11512: &logthis("Userfile repcopy failed for $uri");
11513: return -1;
11514: }
11515: # worked, rename the transfer file
11516: rename($transferfile,$file);
1.607 raeburn 11517: return 'ok';
1.481 raeburn 11518: }
11519:
1.517 albertel 11520: sub tokenwrapper {
11521: my $uri=shift;
1.980 raeburn 11522: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11523: $uri=~s|^/||;
1.620 albertel 11524: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11525: my $token=$1;
1.552 albertel 11526: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11527: if ($udom && $uname && $file) {
11528: $file=~s|(\?\.*)*$||;
1.949 raeburn 11529: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11530: my $homeserver = &homeserver($uname,$udom);
11531: my $protocol = $protocol{$homeserver};
11532: $protocol = 'http' if ($protocol ne 'https');
11533: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11534: (($uri=~/\?/)?'&':'?').'token='.$token.
11535: '&tokenissued='.$perlvar{'lonHostID'};
11536: } else {
11537: return '/adm/notfound.html';
11538: }
11539: }
11540:
1.828 www 11541: # call with reqtype HEAD: get last modification time
11542: # call with reqtype GET: get the file contents
11543: # Do not call this with reqtype GET for large files! It loads everything into memory
11544: #
1.481 raeburn 11545: sub getuploaded {
11546: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11547: $uri=~s/^\///;
1.980 raeburn 11548: my $homeserver = &homeserver($cnum,$cdom);
11549: my $protocol = $protocol{$homeserver};
11550: $protocol = 'http' if ($protocol ne 'https');
11551: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11552: my $ua=new LWP::UserAgent;
11553: my $request=new HTTP::Request($reqtype,$uri);
11554: my $response=$ua->request($request);
11555: $$rtncode = $response->code;
1.482 albertel 11556: if (! $response->is_success()) {
11557: return 'failed';
11558: }
11559: if ($reqtype eq 'HEAD') {
1.486 www 11560: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11561: } elsif ($reqtype eq 'GET') {
11562: $$info = $response->content;
1.472 albertel 11563: }
1.482 albertel 11564: return 'ok';
1.36 albertel 11565: }
11566:
1.481 raeburn 11567: sub readfile {
11568: my $file = shift;
11569: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11570: my $fh;
11571: open($fh,"<$file");
11572: my $a='';
1.800 albertel 11573: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11574: return $a;
11575: }
11576:
1.36 albertel 11577: sub filelocation {
1.590 banghart 11578: my ($dir,$file) = @_;
11579: my $location;
11580: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11581:
11582: if ($file =~ m-^/adm/-) {
11583: $file=~s-^/adm/wrapper/-/-;
11584: $file=~s-^/adm/coursedocs/showdoc/-/-;
11585: }
1.882 albertel 11586:
1.1139 www 11587: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11588: $location = $file;
1.609 banghart 11589: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11590: my ($udom,$uname,$filename)=
1.811 albertel 11591: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11592: my $home=&homeserver($uname,$udom);
11593: my $is_me=0;
11594: my @ids=¤t_machine_ids();
11595: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11596: if ($is_me) {
1.1117 foxr 11597: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11598: } else {
11599: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11600: $udom.'/'.$uname.'/'.$filename;
11601: }
1.882 albertel 11602: } elsif ($file =~ m-^/adm/-) {
11603: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11604: } else {
11605: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11606: $file=~s:^/(res|priv)/:/:;
11607: my $space=$1;
1.590 banghart 11608: if ( !( $file =~ m:^/:) ) {
11609: $location = $dir. '/'.$file;
11610: } else {
1.1142 raeburn 11611: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11612: }
1.59 albertel 11613: }
1.590 banghart 11614: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11615: while ($location=~m{/\.\./}) {
11616: if ($location =~ m{/[^/]+/\.\./}) {
11617: $location=~ s{/[^/]+/\.\./}{/}g;
11618: } else {
11619: $location=~ s{/\.\./}{/}g;
11620: }
11621: } #remove dir/..
1.590 banghart 11622: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11623: return $location;
1.46 www 11624: }
1.36 albertel 11625:
1.46 www 11626: sub hreflocation {
11627: my ($dir,$file)=@_;
1.980 raeburn 11628: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11629: $file=filelocation($dir,$file);
1.700 albertel 11630: } elsif ($file=~m-^/adm/-) {
11631: $file=~s-^/adm/wrapper/-/-;
11632: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11633: }
11634: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11635: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11636: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11637: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11638: {/uploaded/$1/$2/}x;
1.46 www 11639: }
1.913 albertel 11640: if ($file=~ m{^/userfiles/}) {
11641: $file =~ s{^/userfiles/}{/uploaded/};
11642: }
1.462 albertel 11643: return $file;
1.465 albertel 11644: }
11645:
1.1139 www 11646:
11647:
11648:
11649:
1.465 albertel 11650: sub current_machine_domains {
1.853 albertel 11651: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11652: }
11653:
11654: sub machine_domains {
11655: my ($hostname) = @_;
1.465 albertel 11656: my @domains;
1.838 albertel 11657: my %hostname = &all_hostnames();
1.465 albertel 11658: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11659: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11660: if ($hostname eq $name) {
1.844 albertel 11661: push(@domains,&host_domain($id));
1.465 albertel 11662: }
11663: }
11664: return @domains;
11665: }
11666:
11667: sub current_machine_ids {
1.853 albertel 11668: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11669: }
11670:
11671: sub machine_ids {
11672: my ($hostname) = @_;
11673: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11674: my @ids;
1.888 albertel 11675: my %name_to_host = &all_names();
1.889 albertel 11676: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11677: return @{ $name_to_host{$hostname} };
11678: }
11679: return;
1.31 www 11680: }
11681:
1.824 raeburn 11682: sub additional_machine_domains {
11683: my @domains;
11684: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11685: while( my $line = <$fh>) {
11686: $line =~ s/\s//g;
11687: push(@domains,$line);
11688: }
11689: return @domains;
11690: }
11691:
11692: sub default_login_domain {
11693: my $domain = $perlvar{'lonDefDomain'};
11694: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11695: foreach my $posdom (¤t_machine_domains(),
11696: &additional_machine_domains()) {
11697: if (lc($posdom) eq lc($testdomain)) {
11698: $domain=$posdom;
11699: last;
11700: }
11701: }
11702: return $domain;
11703: }
11704:
1.31 www 11705: # ------------------------------------------------------------- Declutters URLs
11706:
11707: sub declutter {
11708: my $thisfn=shift;
1.569 albertel 11709: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11710: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11711: $thisfn=~s/^\///;
1.697 albertel 11712: $thisfn=~s|^adm/wrapper/||;
11713: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11714: $thisfn=~s/^res\///;
1.1172 bisitz 11715: $thisfn=~s/^priv\///;
1.1032 raeburn 11716: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11717: $thisfn=~s/\?.+$//;
11718: }
1.268 www 11719: return $thisfn;
11720: }
11721:
11722: # ------------------------------------------------------------- Clutter up URLs
11723:
11724: sub clutter {
11725: my $thisfn='/'.&declutter(shift);
1.887 albertel 11726: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11727: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11728: $thisfn='/res'.$thisfn;
11729: }
1.1031 raeburn 11730: if ($thisfn !~m|^/adm|) {
11731: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11732: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11733: } else {
11734: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11735: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11736: if ($embstyle eq 'ssi'
11737: || ($embstyle eq 'hdn')
11738: || ($embstyle eq 'rat')
11739: || ($embstyle eq 'prv')
11740: || ($embstyle eq 'ign')) {
11741: #do nothing with these
11742: } elsif (($embstyle eq 'img')
1.695 albertel 11743: || ($embstyle eq 'emb')
11744: || ($embstyle eq 'wrp')) {
11745: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11746: } elsif ($embstyle eq 'unk'
11747: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11748: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11749: } else {
1.718 www 11750: # &logthis("Got a blank emb style");
1.695 albertel 11751: }
1.694 albertel 11752: }
11753: }
1.31 www 11754: return $thisfn;
1.12 www 11755: }
11756:
1.787 albertel 11757: sub clutter_with_no_wrapper {
11758: my $uri = &clutter(shift);
11759: if ($uri =~ m-^/adm/-) {
11760: $uri =~ s-^/adm/wrapper/-/-;
11761: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11762: }
11763: return $uri;
11764: }
11765:
1.557 albertel 11766: sub freeze_escape {
11767: my ($value)=@_;
11768: if (ref($value)) {
11769: $value=&nfreeze($value);
11770: return '__FROZEN__'.&escape($value);
11771: }
11772: return &escape($value);
11773: }
11774:
1.11 www 11775:
1.557 albertel 11776: sub thaw_unescape {
11777: my ($value)=@_;
11778: if ($value =~ /^__FROZEN__/) {
11779: substr($value,0,10,undef);
11780: $value=&unescape($value);
11781: return &thaw($value);
11782: }
11783: return &unescape($value);
11784: }
11785:
1.436 albertel 11786: sub correct_line_ends {
11787: my ($result)=@_;
11788: $$result =~s/\r\n/\n/mg;
11789: $$result =~s/\r/\n/mg;
1.415 albertel 11790: }
1.1 albertel 11791: # ================================================================ Main Program
11792:
1.184 www 11793: sub goodbye {
1.204 albertel 11794: &logthis("Starting Shut down");
1.443 albertel 11795: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11796: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11797: #converted
1.599 albertel 11798: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11799: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11800: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11801: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11802: #1.1 only
1.870 albertel 11803: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11804: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11805: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11806: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11807: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11808: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11809: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11810: &flushcourselogs();
11811: &logthis("Shutting down");
11812: }
11813:
1.852 albertel 11814: sub get_dns {
1.1172.2.17 raeburn 11815: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11816: if (!$ignore_cache) {
11817: my ($content,$cached)=
11818: &Apache::lonnet::is_cached_new('dns',$url);
11819: if ($cached) {
1.1172.2.17 raeburn 11820: &$func($content,$hashref);
1.869 albertel 11821: return;
11822: }
11823: }
11824:
11825: my %alldns;
1.852 albertel 11826: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11827: foreach my $dns (<$config>) {
11828: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11829: my $line = $1;
11830: my ($host,$protocol) = split(/:/,$line);
11831: if ($protocol ne 'https') {
11832: $protocol = 'http';
11833: }
11834: $alldns{$host} = $protocol;
1.869 albertel 11835: }
11836: while (%alldns) {
11837: my ($dns) = keys(%alldns);
1.852 albertel 11838: my $ua=new LWP::UserAgent;
1.1134 raeburn 11839: $ua->timeout(30);
1.979 raeburn 11840: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11841: my $response=$ua->request($request);
1.979 raeburn 11842: delete($alldns{$dns});
1.852 albertel 11843: next if ($response->is_error());
11844: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11845: unless ($nocache) {
1.1172.2.23 raeburn 11846: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11847: }
11848: &$func(\@content,$hashref);
1.869 albertel 11849: return;
1.852 albertel 11850: }
11851: close($config);
1.871 albertel 11852: my $which = (split('/',$url))[3];
11853: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11854: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11855: my @content = <$config>;
1.1172.2.17 raeburn 11856: &$func(\@content,$hashref);
11857: return;
11858: }
11859:
11860: # ------------------------------------------------------Get DNS checksums file
11861: sub parse_dns_checksums_tab {
11862: my ($lines,$hashref) = @_;
11863: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11864: my $loncaparev = &get_server_loncaparev($machine_dom);
11865: my ($release,$timestamp) = split(/\-/,$loncaparev);
11866: my (%chksum,%revnum);
11867: if (ref($lines) eq 'ARRAY') {
11868: chomp(@{$lines});
1.1172.2.34 raeburn 11869: my $version = shift(@{$lines});
11870: if ($version eq $release) {
1.1172.2.17 raeburn 11871: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11872: my ($file,$version,$shasum) = split(/,/,$line);
11873: $chksum{$file} = $shasum;
11874: $revnum{$file} = $version;
1.1172.2.17 raeburn 11875: }
11876: if (ref($hashref) eq 'HASH') {
11877: %{$hashref} = (
11878: sums => \%chksum,
11879: versions => \%revnum,
11880: );
11881: }
11882: }
11883: }
1.869 albertel 11884: return;
1.852 albertel 11885: }
1.1172.2.17 raeburn 11886:
11887: sub fetch_dns_checksums {
11888: my %checksums;
1.1172.2.34 raeburn 11889: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11890: my $loncaparev = &get_server_loncaparev($machine_dom);
11891: my ($release,$timestamp) = split(/\-/,$loncaparev);
11892: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11893: \%checksums);
11894: return \%checksums;
11895: }
11896:
1.327 albertel 11897: # ------------------------------------------------------------ Read domain file
11898: {
1.852 albertel 11899: my $loaded;
1.846 albertel 11900: my %domain;
11901:
1.852 albertel 11902: sub parse_domain_tab {
11903: my ($lines) = @_;
11904: foreach my $line (@$lines) {
11905: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11906:
1.846 albertel 11907: chomp($line);
1.852 albertel 11908: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11909: my %this_domain;
11910: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11911: 'lang_def', 'city', 'longi', 'lati',
11912: 'primary') {
11913: $this_domain{$field} = shift(@elements);
11914: }
11915: $domain{$name} = \%this_domain;
1.852 albertel 11916: }
11917: }
1.864 albertel 11918:
11919: sub reset_domain_info {
11920: undef($loaded);
11921: undef(%domain);
11922: }
11923:
1.852 albertel 11924: sub load_domain_tab {
1.869 albertel 11925: my ($ignore_cache) = @_;
11926: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11927: my $fh;
11928: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11929: my @lines = <$fh>;
11930: &parse_domain_tab(\@lines);
1.448 albertel 11931: }
1.852 albertel 11932: close($fh);
11933: $loaded = 1;
1.327 albertel 11934: }
1.846 albertel 11935:
11936: sub domain {
1.852 albertel 11937: &load_domain_tab() if (!$loaded);
11938:
1.846 albertel 11939: my ($name,$what) = @_;
11940: return if ( !exists($domain{$name}) );
11941:
11942: if (!$what) {
11943: return $domain{$name}{'description'};
11944: }
11945: return $domain{$name}{$what};
11946: }
1.974 raeburn 11947:
11948: sub domain_info {
11949: &load_domain_tab() if (!$loaded);
11950: return %domain;
11951: }
11952:
1.327 albertel 11953: }
11954:
11955:
1.1 albertel 11956: # ------------------------------------------------------------- Read hosts file
11957: {
1.838 albertel 11958: my %hostname;
1.844 albertel 11959: my %hostdom;
1.845 albertel 11960: my %libserv;
1.852 albertel 11961: my $loaded;
1.888 albertel 11962: my %name_to_host;
1.1074 raeburn 11963: my %internetdom;
1.1107 raeburn 11964: my %LC_dns_serv;
1.852 albertel 11965:
11966: sub parse_hosts_tab {
11967: my ($file) = @_;
11968: foreach my $configline (@$file) {
11969: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11970: chomp($configline);
11971: if ($configline =~ /^\^/) {
11972: if ($configline =~ /^\^([\w.\-]+)/) {
11973: $LC_dns_serv{$1} = 1;
11974: }
11975: next;
11976: }
1.1074 raeburn 11977: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11978: $name=~s/\s//g;
11979: if ($id && $domain && $role && $name) {
11980: $hostname{$id}=$name;
1.888 albertel 11981: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11982: $hostdom{$id}=$domain;
11983: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11984: if (defined($protocol)) {
11985: if ($protocol eq 'https') {
11986: $protocol{$id} = $protocol;
11987: } else {
11988: $protocol{$id} = 'http';
11989: }
1.968 raeburn 11990: } else {
1.969 raeburn 11991: $protocol{$id} = 'http';
1.968 raeburn 11992: }
1.1074 raeburn 11993: if (defined($intdom)) {
11994: $internetdom{$id} = $intdom;
11995: }
1.852 albertel 11996: }
11997: }
11998: }
1.864 albertel 11999:
12000: sub reset_hosts_info {
1.897 albertel 12001: &purge_remembered();
1.864 albertel 12002: &reset_domain_info();
12003: &reset_hosts_ip_info();
1.892 albertel 12004: undef(%name_to_host);
1.864 albertel 12005: undef(%hostname);
12006: undef(%hostdom);
12007: undef(%libserv);
12008: undef($loaded);
12009: }
1.1 albertel 12010:
1.852 albertel 12011: sub load_hosts_tab {
1.869 albertel 12012: my ($ignore_cache) = @_;
12013: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12014: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12015: my @config = <$config>;
12016: &parse_hosts_tab(\@config);
12017: close($config);
12018: $loaded=1;
1.1 albertel 12019: }
1.852 albertel 12020:
1.838 albertel 12021: sub hostname {
1.852 albertel 12022: &load_hosts_tab() if (!$loaded);
12023:
1.838 albertel 12024: my ($lonid) = @_;
12025: return $hostname{$lonid};
12026: }
1.845 albertel 12027:
1.838 albertel 12028: sub all_hostnames {
1.852 albertel 12029: &load_hosts_tab() if (!$loaded);
12030:
1.838 albertel 12031: return %hostname;
12032: }
1.845 albertel 12033:
1.888 albertel 12034: sub all_names {
12035: &load_hosts_tab() if (!$loaded);
12036:
12037: return %name_to_host;
12038: }
12039:
1.974 raeburn 12040: sub all_host_domain {
12041: &load_hosts_tab() if (!$loaded);
12042: return %hostdom;
12043: }
12044:
1.845 albertel 12045: sub is_library {
1.852 albertel 12046: &load_hosts_tab() if (!$loaded);
12047:
1.845 albertel 12048: return exists($libserv{$_[0]});
12049: }
12050:
12051: sub all_library {
1.852 albertel 12052: &load_hosts_tab() if (!$loaded);
12053:
1.845 albertel 12054: return %libserv;
12055: }
12056:
1.1062 droeschl 12057: sub unique_library {
12058: #2x reverse removes all hostnames that appear more than once
12059: my %unique = reverse &all_library();
12060: return reverse %unique;
12061: }
12062:
1.841 albertel 12063: sub get_servers {
1.852 albertel 12064: &load_hosts_tab() if (!$loaded);
12065:
1.841 albertel 12066: my ($domain,$type) = @_;
12067: my %possible_hosts = ($type eq 'library') ? %libserv
12068: : %hostname;
12069: my %result;
1.842 albertel 12070: if (ref($domain) eq 'ARRAY') {
12071: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12072: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12073: $result{$host} = $hostname;
12074: }
12075: }
12076: } else {
12077: while ( my ($host,$hostname) = each(%possible_hosts)) {
12078: if ($hostdom{$host} eq $domain) {
12079: $result{$host} = $hostname;
12080: }
1.841 albertel 12081: }
12082: }
12083: return %result;
12084: }
1.845 albertel 12085:
1.1062 droeschl 12086: sub get_unique_servers {
12087: my %unique = reverse &get_servers(@_);
12088: return reverse %unique;
12089: }
12090:
1.844 albertel 12091: sub host_domain {
1.852 albertel 12092: &load_hosts_tab() if (!$loaded);
12093:
1.844 albertel 12094: my ($lonid) = @_;
12095: return $hostdom{$lonid};
12096: }
12097:
1.841 albertel 12098: sub all_domains {
1.852 albertel 12099: &load_hosts_tab() if (!$loaded);
12100:
1.841 albertel 12101: my %seen;
12102: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12103: return @uniq;
12104: }
1.1074 raeburn 12105:
12106: sub internet_dom {
12107: &load_hosts_tab() if (!$loaded);
12108:
12109: my ($lonid) = @_;
12110: return $internetdom{$lonid};
12111: }
1.1107 raeburn 12112:
12113: sub is_LC_dns {
12114: &load_hosts_tab() if (!$loaded);
12115:
12116: my ($hostname) = @_;
12117: return exists($LC_dns_serv{$hostname});
12118: }
12119:
1.1 albertel 12120: }
12121:
1.847 albertel 12122: {
12123: my %iphost;
1.856 albertel 12124: my %name_to_ip;
12125: my %lonid_to_ip;
1.869 albertel 12126:
1.847 albertel 12127: sub get_hosts_from_ip {
12128: my ($ip) = @_;
12129: my %iphosts = &get_iphost();
12130: if (ref($iphosts{$ip})) {
12131: return @{$iphosts{$ip}};
12132: }
12133: return;
1.839 albertel 12134: }
1.864 albertel 12135:
12136: sub reset_hosts_ip_info {
12137: undef(%iphost);
12138: undef(%name_to_ip);
12139: undef(%lonid_to_ip);
12140: }
1.856 albertel 12141:
12142: sub get_host_ip {
12143: my ($lonid) = @_;
12144: if (exists($lonid_to_ip{$lonid})) {
12145: return $lonid_to_ip{$lonid};
12146: }
12147: my $name=&hostname($lonid);
12148: my $ip = gethostbyname($name);
12149: return if (!$ip || length($ip) ne 4);
12150: $ip=inet_ntoa($ip);
12151: $name_to_ip{$name} = $ip;
12152: $lonid_to_ip{$lonid} = $ip;
12153: return $ip;
12154: }
1.847 albertel 12155:
12156: sub get_iphost {
1.869 albertel 12157: my ($ignore_cache) = @_;
1.894 albertel 12158:
1.869 albertel 12159: if (!$ignore_cache) {
12160: if (%iphost) {
12161: return %iphost;
12162: }
12163: my ($ip_info,$cached)=
12164: &Apache::lonnet::is_cached_new('iphost','iphost');
12165: if ($cached) {
12166: %iphost = %{$ip_info->[0]};
12167: %name_to_ip = %{$ip_info->[1]};
12168: %lonid_to_ip = %{$ip_info->[2]};
12169: return %iphost;
12170: }
12171: }
1.894 albertel 12172:
12173: # get yesterday's info for fallback
12174: my %old_name_to_ip;
12175: my ($ip_info,$cached)=
12176: &Apache::lonnet::is_cached_new('iphost','iphost');
12177: if ($cached) {
12178: %old_name_to_ip = %{$ip_info->[1]};
12179: }
12180:
1.888 albertel 12181: my %name_to_host = &all_names();
12182: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12183: my $ip;
12184: if (!exists($name_to_ip{$name})) {
12185: $ip = gethostbyname($name);
12186: if (!$ip || length($ip) ne 4) {
1.894 albertel 12187: if (defined($old_name_to_ip{$name})) {
12188: $ip = $old_name_to_ip{$name};
12189: &logthis("Can't find $name defaulting to old $ip");
12190: } else {
12191: &logthis("Name $name no IP found");
12192: next;
12193: }
12194: } else {
12195: $ip=inet_ntoa($ip);
1.847 albertel 12196: }
12197: $name_to_ip{$name} = $ip;
12198: } else {
12199: $ip = $name_to_ip{$name};
1.653 albertel 12200: }
1.888 albertel 12201: foreach my $id (@{ $name_to_host{$name} }) {
12202: $lonid_to_ip{$id} = $ip;
12203: }
12204: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12205: }
1.1172.2.23 raeburn 12206: &do_cache_new('iphost','iphost',
12207: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12208: 48*60*60);
1.869 albertel 12209:
1.847 albertel 12210: return %iphost;
1.598 albertel 12211: }
12212:
1.992 raeburn 12213: #
12214: # Given a DNS returns the loncapa host name for that DNS
12215: #
12216: sub host_from_dns {
12217: my ($dns) = @_;
12218: my @hosts;
12219: my $ip;
12220:
1.993 raeburn 12221: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12222: $ip = $name_to_ip{$dns};
12223: }
12224: if (!$ip) {
12225: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12226: if (length($ip) == 4) {
12227: $ip = &IO::Socket::inet_ntoa($ip);
12228: }
12229: }
12230: if ($ip) {
12231: @hosts = get_hosts_from_ip($ip);
12232: return $hosts[0];
12233: }
12234: return undef;
1.986 foxr 12235: }
1.992 raeburn 12236:
1.1074 raeburn 12237: sub get_internet_names {
12238: my ($lonid) = @_;
12239: return if ($lonid eq '');
12240: my ($idnref,$cached)=
12241: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12242: if ($cached) {
12243: return $idnref;
12244: }
12245: my $ip = &get_host_ip($lonid);
12246: my @hosts = &get_hosts_from_ip($ip);
12247: my %iphost = &get_iphost();
12248: my (@idns,%seen);
12249: foreach my $id (@hosts) {
12250: my $dom = &host_domain($id);
12251: my $prim_id = &domain($dom,'primary');
12252: my $prim_ip = &get_host_ip($prim_id);
12253: next if ($seen{$prim_ip});
12254: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12255: foreach my $id (@{$iphost{$prim_ip}}) {
12256: my $intdom = &internet_dom($id);
12257: unless (grep(/^\Q$intdom\E$/,@idns)) {
12258: push(@idns,$intdom);
12259: }
12260: }
12261: }
12262: $seen{$prim_ip} = 1;
12263: }
1.1172.2.23 raeburn 12264: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12265: }
12266:
1.986 foxr 12267: }
12268:
1.1079 raeburn 12269: sub all_loncaparevs {
1.1172.2.39 raeburn 12270: 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 12271: }
12272:
1.1172.2.27 raeburn 12273: # ------------------------------------------------------- Read loncaparev table
12274: {
12275: sub load_loncaparevs {
12276: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12277: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12278: while (my $configline=<$config>) {
12279: chomp($configline);
12280: my ($hostid,$loncaparev)=split(/:/,$configline);
12281: $loncaparevs{$hostid}=$loncaparev;
12282: }
12283: close($config);
12284: }
12285: }
12286: }
12287: }
12288:
12289: # ----------------------------------------------------- Read serverhostID table
12290: {
12291: sub load_serverhomeIDs {
12292: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12293: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12294: while (my $configline=<$config>) {
12295: chomp($configline);
12296: my ($name,$id)=split(/:/,$configline);
12297: $serverhomeIDs{$name}=$id;
12298: }
12299: close($config);
12300: }
12301: }
12302: }
12303: }
12304:
12305:
1.862 albertel 12306: BEGIN {
12307:
12308: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12309: unless ($readit) {
12310: {
12311: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12312: %perlvar = (%perlvar,%{$configvars});
12313: }
12314:
12315:
1.1 albertel 12316: # ------------------------------------------------------ Read spare server file
12317: {
1.448 albertel 12318: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12319:
12320: while (my $configline=<$config>) {
12321: chomp($configline);
1.284 matthew 12322: if ($configline) {
1.784 albertel 12323: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12324: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12325: push(@{ $spareid{$type} }, $host);
1.1 albertel 12326: }
12327: }
1.448 albertel 12328: close($config);
1.1 albertel 12329: }
1.11 www 12330: # ------------------------------------------------------------ Read permissions
12331: {
1.448 albertel 12332: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12333:
12334: while (my $configline=<$config>) {
1.448 albertel 12335: chomp($configline);
12336: if ($configline) {
12337: my ($role,$perm)=split(/ /,$configline);
12338: if ($perm ne '') { $pr{$role}=$perm; }
12339: }
1.11 www 12340: }
1.448 albertel 12341: close($config);
1.11 www 12342: }
12343:
12344: # -------------------------------------------- Read plain texts for permissions
12345: {
1.448 albertel 12346: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12347:
12348: while (my $configline=<$config>) {
1.448 albertel 12349: chomp($configline);
12350: if ($configline) {
1.742 raeburn 12351: my ($short,@plain)=split(/:/,$configline);
12352: %{$prp{$short}} = ();
12353: if (@plain > 0) {
12354: $prp{$short}{'std'} = $plain[0];
12355: for (my $i=1; $i<@plain; $i++) {
12356: $prp{$short}{'alt'.$i} = $plain[$i];
12357: }
12358: }
1.448 albertel 12359: }
1.135 www 12360: }
1.448 albertel 12361: close($config);
1.135 www 12362: }
12363:
12364: # ---------------------------------------------------------- Read package table
12365: {
1.448 albertel 12366: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12367:
12368: while (my $configline=<$config>) {
1.483 albertel 12369: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12370: chomp($configline);
12371: my ($short,$plain)=split(/:/,$configline);
12372: my ($pack,$name)=split(/\&/,$short);
12373: if ($plain ne '') {
12374: $packagetab{$pack.'&'.$name.'&name'}=$name;
12375: $packagetab{$short}=$plain;
12376: }
1.11 www 12377: }
1.448 albertel 12378: close($config);
1.329 matthew 12379: }
12380:
1.1172.2.27 raeburn 12381: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12382:
1.1172.2.27 raeburn 12383: &load_loncaparevs();
12384:
12385: # ------------------------------------------------------- Read serverhostID table
12386:
12387: &load_serverhomeIDs();
1.1074 raeburn 12388:
1.1172.2.27 raeburn 12389: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12390: {
12391: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12392: if (-e $file) {
12393: my $parser = HTML::LCParser->new($file);
12394: while (my $token = $parser->get_token()) {
12395: if ($token->[0] eq 'S') {
12396: my $item = $token->[1];
12397: my $name = $token->[2]{'name'};
12398: my $value = $token->[2]{'value'};
12399: if ($item ne '' && $name ne '' && $value ne '') {
12400: my $release = $parser->get_text();
12401: $release =~ s/(^\s*|\s*$ )//gx;
12402: $needsrelease{$item.':'.$name.':'.$value} = $release;
12403: }
12404: }
12405: }
12406: }
1.1073 raeburn 12407: }
12408:
1.1138 raeburn 12409: # ---------------------------------------------------------- Read managers table
12410: {
12411: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12412: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12413: while (my $configline=<$config>) {
12414: chomp($configline);
12415: next if ($configline =~ /^\#/);
12416: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12417: $managerstab{$configline} = 1;
12418: }
12419: }
12420: close($config);
12421: }
12422: }
12423: }
12424:
1.329 matthew 12425: # ------------- set up temporary directory
12426: {
1.1117 foxr 12427: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12428:
1.11 www 12429: }
12430:
1.794 albertel 12431: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12432: 'compress_threshold'=> 20_000,
12433: });
1.185 www 12434:
1.281 www 12435: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12436: $dumpcount=0;
1.958 www 12437: $locknum=0;
1.22 www 12438:
1.163 harris41 12439: &logtouch();
1.672 albertel 12440: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12441: $readit=1;
1.564 albertel 12442: {
12443: use integer;
12444: my $test=(2**32)+1;
1.568 albertel 12445: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12446: &logthis(" Detected 64bit platform ($_64bit)");
12447: }
1.195 www 12448: }
1.1 albertel 12449: }
1.179 www 12450:
1.1 albertel 12451: 1;
1.191 harris41 12452: __END__
12453:
1.243 albertel 12454: =pod
12455:
1.191 harris41 12456: =head1 NAME
12457:
1.243 albertel 12458: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12459:
12460: =head1 SYNOPSIS
12461:
1.243 albertel 12462: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12463:
12464: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12465:
1.243 albertel 12466: Common parameters:
12467:
12468: =over 4
12469:
12470: =item *
12471:
12472: $uname : an internal username (if $cname expecting a course Id specifically)
12473:
12474: =item *
12475:
12476: $udom : a domain (if $cdom expecting a course's domain specifically)
12477:
12478: =item *
12479:
12480: $symb : a resource instance identifier
12481:
12482: =item *
12483:
12484: $namespace : the name of a .db file that contains the data needed or
12485: being set.
12486:
12487: =back
12488:
1.394 bowersj2 12489: =head1 OVERVIEW
1.191 harris41 12490:
1.394 bowersj2 12491: lonnet provides subroutines which interact with the
12492: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12493: about classes, users, and resources.
1.243 albertel 12494:
12495: For many of these objects you can also use this to store data about
12496: them or modify them in various ways.
1.191 harris41 12497:
1.394 bowersj2 12498: =head2 Symbs
1.191 harris41 12499:
1.394 bowersj2 12500: To identify a specific instance of a resource, LON-CAPA uses symbols
12501: or "symbs"X<symb>. These identifiers are built from the URL of the
12502: map, the resource number of the resource in the map, and the URL of
12503: the resource itself. The latter is somewhat redundant, but might help
12504: if maps change.
12505:
12506: An example is
12507:
12508: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12509:
12510: The respective map entry is
12511:
12512: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12513: title="Problem 2">
12514: </resource>
12515:
12516: Symbs are used by the random number generator, as well as to store and
12517: restore data specific to a certain instance of for example a problem.
12518:
12519: =head2 Storing And Retrieving Data
12520:
12521: X<store()>X<cstore()>X<restore()>Three of the most important functions
12522: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12523: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12524: is is the non-critical message twin of cstore. These functions are for
12525: handlers to store a perl hash to a user's permanent data space in an
12526: easy manner, and to retrieve it again on another call. It is expected
12527: that a handler would use this once at the beginning to retrieve data,
12528: and then again once at the end to send only the new data back.
12529:
12530: The data is stored in the user's data directory on the user's
12531: homeserver under the ID of the course.
12532:
12533: The hash that is returned by restore will have all of the previous
12534: value for all of the elements of the hash.
12535:
12536: Example:
12537:
12538: #creating a hash
12539: my %hash;
12540: $hash{'foo'}='bar';
12541:
12542: #storing it
12543: &Apache::lonnet::cstore(\%hash);
12544:
12545: #changing a value
12546: $hash{'foo'}='notbar';
12547:
12548: #adding a new value
12549: $hash{'bar'}='foo';
12550: &Apache::lonnet::cstore(\%hash);
12551:
12552: #retrieving the hash
12553: my %history=&Apache::lonnet::restore();
12554:
12555: #print the hash
12556: foreach my $key (sort(keys(%history))) {
12557: print("\%history{$key} = $history{$key}");
12558: }
12559:
12560: Will print out:
1.191 harris41 12561:
1.394 bowersj2 12562: %history{1:foo} = bar
12563: %history{1:keys} = foo:timestamp
12564: %history{1:timestamp} = 990455579
12565: %history{2:bar} = foo
12566: %history{2:foo} = notbar
12567: %history{2:keys} = foo:bar:timestamp
12568: %history{2:timestamp} = 990455580
12569: %history{bar} = foo
12570: %history{foo} = notbar
12571: %history{timestamp} = 990455580
12572: %history{version} = 2
12573:
12574: Note that the special hash entries C<keys>, C<version> and
12575: C<timestamp> were added to the hash. C<version> will be equal to the
12576: total number of versions of the data that have been stored. The
12577: C<timestamp> attribute will be the UNIX time the hash was
12578: stored. C<keys> is available in every historical section to list which
12579: keys were added or changed at a specific historical revision of a
12580: hash.
12581:
12582: B<Warning>: do not store the hash that restore returns directly. This
12583: will cause a mess since it will restore the historical keys as if the
12584: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12585:
1.394 bowersj2 12586: Calling convention:
1.191 harris41 12587:
1.1172.2.27 raeburn 12588: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12589: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12590:
1.394 bowersj2 12591: For more detailed information, see lonnet specific documentation.
1.191 harris41 12592:
1.394 bowersj2 12593: =head1 RETURN MESSAGES
1.191 harris41 12594:
1.394 bowersj2 12595: =over 4
1.191 harris41 12596:
1.394 bowersj2 12597: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12598:
1.394 bowersj2 12599: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12600: when the connection is brought back up
1.191 harris41 12601:
1.394 bowersj2 12602: =item * B<con_failed>: unable to contact remote host and unable to save message
12603: for later delivery
1.191 harris41 12604:
1.967 bisitz 12605: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12606:
1.394 bowersj2 12607: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12608: that was requested
1.191 harris41 12609:
1.243 albertel 12610: =back
1.191 harris41 12611:
1.243 albertel 12612: =head1 PUBLIC SUBROUTINES
1.191 harris41 12613:
1.243 albertel 12614: =head2 Session Environment Functions
1.191 harris41 12615:
1.243 albertel 12616: =over 4
1.191 harris41 12617:
1.394 bowersj2 12618: =item *
12619: X<appenv()>
1.949 raeburn 12620: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12621: the user envirnoment file, and will be restored for each access this
1.620 albertel 12622: user makes during this session, also modifies the %env for the current
1.949 raeburn 12623: process. Optional rolesarrayref - if defined contains a reference to an array
12624: of roles which are exempt from the restriction on modifying user.role entries
12625: in the user's environment.db and in %env.
1.191 harris41 12626:
12627: =item *
1.394 bowersj2 12628: X<delenv()>
1.987 raeburn 12629: B<delenv($delthis,$regexp)>: removes all items from the session
12630: environment file that begin with $delthis. If the
12631: optional second arg - $regexp - is true, $delthis is treated as a
12632: regular expression, otherwise \Q$delthis\E is used.
12633: The values are also deleted from the current processes %env.
1.191 harris41 12634:
1.795 albertel 12635: =item * get_env_multiple($name)
12636:
12637: gets $name from the %env hash, it seemlessly handles the cases where multiple
12638: values may be defined and end up as an array ref.
12639:
12640: returns an array of values
12641:
1.243 albertel 12642: =back
12643:
12644: =head2 User Information
1.191 harris41 12645:
1.243 albertel 12646: =over 4
1.191 harris41 12647:
12648: =item *
1.394 bowersj2 12649: X<queryauthenticate()>
12650: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12651: authentication scheme
12652:
12653: =item *
1.394 bowersj2 12654: X<authenticate()>
1.1073 raeburn 12655: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12656: authenticate user from domain's lib servers (first use the current
12657: one). C<$upass> should be the users password.
1.1073 raeburn 12658: $checkdefauth is optional (value is 1 if a check should be made to
12659: authenticate user using default authentication method, and allow
12660: account creation if username does not have account in the domain).
12661: $clientcancheckhost is optional (value is 1 if checking whether the
12662: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12663:
12664: =item *
1.394 bowersj2 12665: X<homeserver()>
12666: B<homeserver($uname,$udom)>: find the server which has
12667: the user's directory and files (there must be only one), this caches
12668: the answer, and also caches if there is a borken connection.
1.191 harris41 12669:
12670: =item *
1.394 bowersj2 12671: X<idget()>
12672: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12673: (IDs are a unique resource in a domain, there must be only 1 ID per
12674: username, and only 1 username per ID in a specific domain) (returns
12675: hash: id=>name,id=>name)
1.191 harris41 12676:
12677: =item *
1.394 bowersj2 12678: X<idrget()>
12679: B<idrget($udom,@unames)>: find the IDs behind a list of
12680: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12681:
12682: =item *
1.394 bowersj2 12683: X<idput()>
12684: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12685:
12686: =item *
1.394 bowersj2 12687: X<rolesinit()>
1.1169 droeschl 12688: B<rolesinit($udom,$username)>: get user privileges.
12689: returns user role, first access and timer interval hashes
1.243 albertel 12690:
12691: =item *
1.1171 droeschl 12692: X<privileged()>
12693: B<privileged($username,$domain)>: returns a true if user has a
12694: privileged and active role (i.e. su or dc), false otherwise.
12695:
12696: =item *
1.551 albertel 12697: X<getsection()>
12698: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12699: course $cname, return section name/number or '' for "not in course"
12700: and '-1' for "no section"
12701:
12702: =item *
1.394 bowersj2 12703: X<userenvironment()>
12704: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12705: passed in @what from the requested user's environment, returns a hash
12706:
1.858 raeburn 12707: =item *
12708: X<userlog_query()>
1.859 albertel 12709: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12710: activity.log file. %filters defines filters applied when parsing the
12711: log file. These can be start or end timestamps, or the type of action
12712: - log to look for Login or Logout events, check for Checkin or
12713: Checkout, role for role selection. The response is in the form
12714: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12715: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12716:
1.243 albertel 12717: =back
12718:
12719: =head2 User Roles
12720:
12721: =over 4
12722:
12723: =item *
12724:
1.810 raeburn 12725: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12726: F: full access
12727: U,I,K: authentication modes (cxx only)
12728: '': forbidden
12729: 1: user needs to choose course
12730: 2: browse allowed
1.766 albertel 12731: A: passphrase authentication needed
1.243 albertel 12732:
12733: =item *
12734:
1.1172.2.13 raeburn 12735: constructaccess($url,$setpriv) : check for access to construction space URL
12736:
12737: See if the owner domain and name in the URL match those in the
12738: expected environment. If so, return three element list
12739: ($ownername,$ownerdomain,$ownerhome).
12740:
12741: Otherwise return the null string.
12742:
12743: If second argument 'setpriv' is true, it assigns the privileges,
12744: and returns the same three element list, unless the owner has
12745: blocked "ad hoc" Domain Coordinator access to the Author Space,
12746: in which case the null string is returned.
12747:
12748: =item *
12749:
1.243 albertel 12750: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12751: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12752: and course level
12753:
12754: =item *
12755:
1.988 raeburn 12756: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12757: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12758: $type is Course (default) or Community.
1.988 raeburn 12759: If $forcedefault evaluates to true, text returned will be default
12760: text for $type. Otherwise, if this is a course, the text returned
12761: will be a custom name for the role (if defined in the course's
12762: environment). If no custom name is defined the default is returned.
12763:
1.832 raeburn 12764: =item *
12765:
1.1172.2.23 raeburn 12766: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12767: All arguments are optional. Returns a hash of a roles, either for
12768: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12769: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12770: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12771: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12772: For each key, value is set to colon-separated start and end times for
12773: the role. If no username and domain are specified, will default to
1.934 raeburn 12774: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12775: of role statuses (active, future or previous), roles
12776: (e.g., cc,in, st etc.) and domains of the roles which can be used
12777: to restrict the list of roles reported. If no array ref is
12778: provided for types, will default to return only active roles.
1.834 albertel 12779:
1.1172.2.13 raeburn 12780: =item *
12781:
12782: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12783: user: $uname:$udom has a role in the course: $cdom_$cnum.
12784:
12785: Additional optional arguments are: $type (if role checking is to be restricted
12786: to certain user status types -- previous (expired roles), active (currently
12787: available roles) or future (roles available in the future), and
12788: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12789: have active Domain Coordinator role in course's domain or in additional
12790: domains (specified in 'Domains to check for privileged users' in course
12791: environment -- set via: Course Settings -> Classlists and staff listing).
12792:
12793: =item *
12794:
12795: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12796: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12797: $possdomains and $possroles are optional array refs -- to domains to check and
12798: roles to check. If $possdomains is not specified, a dump will be done of the
12799: users' roles.db to check for a dc or su role in any domain. This can be
12800: time consuming if &privileged is called repeatedly (e.g., when displaying a
12801: classlist), so in such cases, supplying a $possdomains array is preferred, as
12802: this then allows &privileged_by_domain() to be used, which caches the identity
12803: of privileged users, eliminating the need for repeated calls to &dump().
12804:
12805: =item *
12806:
12807: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12808: where the outer hash keys are domains specified in the $possdomains array ref,
12809: next inner hash keys are privileged roles specified in the $roles array ref,
12810: and the innermost hash contains key = value pairs for username:domain = end:start
12811: for active or future "privileged" users with that role in that domain. To avoid
12812: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12813: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12814:
1.243 albertel 12815: =back
12816:
12817: =head2 User Modification
12818:
12819: =over 4
12820:
12821: =item *
12822:
1.957 raeburn 12823: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12824: user for the level given by URL. Optional start and end dates (leave empty
12825: string or zero for "no date")
1.191 harris41 12826:
12827: =item *
12828:
1.243 albertel 12829: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12830: change a users, password, possible return values are: ok,
12831: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12832: refused
1.191 harris41 12833:
12834: =item *
12835:
1.243 albertel 12836: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12837:
12838: =item *
12839:
1.1058 raeburn 12840: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12841: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12842:
12843: will update user information (firstname,middlename,lastname,generation,
12844: permanentemail), and if forceid is true, student/employee ID also.
12845: A user's institutional affiliation(s) can also be updated.
12846: User information fields will not be overwritten with empty entries
12847: unless the field is included in the $candelete array reference.
12848: This array is included when a single user is modified via "Manage Users",
12849: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12850:
12851: =item *
12852:
1.286 matthew 12853: modifystudent
12854:
1.957 raeburn 12855: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12856: The course id is resolved based on the current user's environment.
12857: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12858: associated with a course.
12859:
1.297 matthew 12860: This call is essentially a wrapper for lonnet::modifyuser and
12861: lonnet::modify_student_enrollment
1.286 matthew 12862:
12863: Inputs:
12864:
12865: =over 4
12866:
1.957 raeburn 12867: =item B<$udom> Student's loncapa domain
1.286 matthew 12868:
1.957 raeburn 12869: =item B<$uname> Student's loncapa login name
1.286 matthew 12870:
1.964 bisitz 12871: =item B<$uid> Student/Employee ID
1.286 matthew 12872:
1.957 raeburn 12873: =item B<$umode> Student's authentication mode
1.286 matthew 12874:
1.957 raeburn 12875: =item B<$upass> Student's password
1.286 matthew 12876:
1.957 raeburn 12877: =item B<$first> Student's first name
1.286 matthew 12878:
1.957 raeburn 12879: =item B<$middle> Student's middle name
1.286 matthew 12880:
1.957 raeburn 12881: =item B<$last> Student's last name
1.286 matthew 12882:
1.957 raeburn 12883: =item B<$gene> Student's generation
1.286 matthew 12884:
1.957 raeburn 12885: =item B<$usec> Student's section in course
1.286 matthew 12886:
12887: =item B<$end> Unix time of the roles expiration
12888:
12889: =item B<$start> Unix time of the roles start date
12890:
12891: =item B<$forceid> If defined, allow $uid to be changed
12892:
12893: =item B<$desiredhome> server to use as home server for student
12894:
1.957 raeburn 12895: =item B<$email> Student's permanent e-mail address
12896:
12897: =item B<$type> Type of enrollment (auto or manual)
12898:
1.963 raeburn 12899: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12900:
12901: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12902:
1.963 raeburn 12903: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12904:
1.963 raeburn 12905: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12906:
1.1172.2.19 raeburn 12907: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12908:
12909: =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 12910:
1.286 matthew 12911: =back
1.297 matthew 12912:
12913: =item *
12914:
12915: modify_student_enrollment
12916:
1.1172.2.31 raeburn 12917: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12918: 'role.request.course' must be defined for this function to proceed.
12919:
12920: Inputs:
12921:
12922: =over 4
12923:
1.1172.2.31 raeburn 12924: =item $udom, student's domain
1.297 matthew 12925:
1.1172.2.31 raeburn 12926: =item $uname, student's name
1.297 matthew 12927:
1.1172.2.31 raeburn 12928: =item $uid, student's user id
1.297 matthew 12929:
1.1172.2.31 raeburn 12930: =item $first, student's first name
1.297 matthew 12931:
12932: =item $middle
12933:
12934: =item $last
12935:
12936: =item $gene
12937:
12938: =item $usec
12939:
12940: =item $end
12941:
12942: =item $start
12943:
1.957 raeburn 12944: =item $type
12945:
12946: =item $locktype
12947:
12948: =item $cid
12949:
12950: =item $selfenroll
12951:
12952: =item $context
12953:
1.1172.2.19 raeburn 12954: =item $credits, number of credits student will earn from this class
12955:
1.297 matthew 12956: =back
12957:
1.191 harris41 12958:
12959: =item *
12960:
1.243 albertel 12961: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12962: custom role; give a custom role to a user for the level given by URL. Specify
12963: name and domain of role author, and role name
1.191 harris41 12964:
12965: =item *
12966:
1.243 albertel 12967: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12968:
12969: =item *
12970:
1.243 albertel 12971: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12972:
12973: =back
12974:
12975: =head2 Course Infomation
12976:
12977: =over 4
1.191 harris41 12978:
12979: =item *
12980:
1.1118 foxr 12981: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12982: specified course id, including all environment settings for the
12983: course, the description of the course will be in the hash under the
12984: key 'description'
1.191 harris41 12985:
1.1118 foxr 12986: $options is an optional parameter that if supplied is a hash reference that controls
12987: what how this function works. It has the following key/values:
12988:
12989: =over 4
12990:
12991: =item freshen_cache
12992:
12993: If defined, and the environment cache for the course is valid, it is
12994: returned in the returned hash.
12995:
12996: =item one_time
12997:
12998: If defined, the last cache time is set to _now_
12999:
13000: =item user
13001:
13002: If defined, the supplied username is used instead of the current user.
13003:
13004:
13005: =back
13006:
1.191 harris41 13007: =item *
13008:
1.624 albertel 13009: resdata($name,$domain,$type,@which) : request for current parameter
13010: setting for a specific $type, where $type is either 'course' or 'user',
13011: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13012: answers for 10 minutes.
1.243 albertel 13013:
1.877 foxr 13014: =item *
13015:
13016: get_courseresdata($courseid, $domain) : dump the entire course resource
13017: data base, returning a hash that is keyed by the resource name and has
13018: values that are the resource value. I believe that the timestamps and
13019: versions are also returned.
13020:
1.1172.2.31 raeburn 13021: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13022: supplemental content area. This routine caches the number of files for
13023: 10 minutes.
13024:
1.243 albertel 13025: =back
13026:
13027: =head2 Course Modification
13028:
13029: =over 4
1.191 harris41 13030:
13031: =item *
13032:
1.243 albertel 13033: writecoursepref($courseid,%prefs) : write preferences (environment
13034: database) for a course
1.191 harris41 13035:
13036: =item *
13037:
1.1011 raeburn 13038: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13039:
13040: =item *
13041:
1.1038 raeburn 13042: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13043:
1.1167 droeschl 13044: =item *
13045:
13046: is_course($courseid), is_course($cdom, $cnum)
13047:
13048: Accepts either a combined $courseid (in the form of domain_courseid) or the
13049: two component version $cdom, $cnum. It checks if the specified course exists.
13050:
13051: Returns:
13052: undef if the course doesn't exist, otherwise
13053: in scalar context the combined courseid.
13054: in list context the two components of the course identifier, domain and
13055: courseid.
13056:
1.243 albertel 13057: =back
13058:
13059: =head2 Resource Subroutines
13060:
13061: =over 4
1.191 harris41 13062:
13063: =item *
13064:
1.243 albertel 13065: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13066:
13067: =item *
13068:
1.243 albertel 13069: repcopy($filename) : subscribes to the requested file, and attempts to
13070: replicate from the owning library server, Might return
1.607 raeburn 13071: 'unavailable', 'not_found', 'forbidden', 'ok', or
13072: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13073: resource. Expects the local filesystem pathname
13074: (/home/httpd/html/res/....)
13075:
13076: =back
13077:
13078: =head2 Resource Information
13079:
13080: =over 4
1.191 harris41 13081:
13082: =item *
13083:
1.1172.2.28 raeburn 13084: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13085: and returns the value of a variety of different possible values,
13086: $varname should be a request string, and the other parameters can be
13087: used to specify who and what one is asking about. Ordinarily, $cid
13088: does not need to be specified, as it is retrived from
13089: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13090: within lonuserstate::loadmap() when initializing a course, before
13091: $env{'request.course.id'} has been set, so it needs to be provided
13092: in that one case.
1.243 albertel 13093:
13094: Possible values for $varname are environment.lastname (or other item
13095: from the envirnment hash), user.name (or someother aspect about the
13096: user), resource.0.maxtries (or some other part and parameter of a
13097: resource)
1.204 albertel 13098:
13099: =item *
13100:
1.243 albertel 13101: directcondval($number) : get current value of a condition; reads from a state
13102: string
1.204 albertel 13103:
13104: =item *
13105:
1.243 albertel 13106: condval($condidx) : value of condition index based on state
1.204 albertel 13107:
13108: =item *
13109:
1.243 albertel 13110: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13111: resource's metadata, $what should be either a specific key, or either
13112: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13113: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13114:
13115: this function automatically caches all requests
1.191 harris41 13116:
13117: =item *
13118:
1.243 albertel 13119: metadata_query($query,$custom,$customshow) : make a metadata query against the
13120: network of library servers; returns file handle of where SQL and regex results
13121: will be stored for query
1.191 harris41 13122:
13123: =item *
13124:
1.243 albertel 13125: symbread($filename) : return symbolic list entry (filename argument optional);
13126: returns the data handle
1.191 harris41 13127:
13128: =item *
13129:
1.1172.2.17 raeburn 13130: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13131: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13132: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13133: on failure, user must be in a course, as it assumes the existence of
13134: the course initial hash, and uses $env('request.course.id'}. The third
13135: arg is an optional reference to a scalar. If this arg is passed in the
13136: call to symbverify, it will be set to 1 if the symb has been set to be
13137: encrypted; otherwise it will be null.
1.243 albertel 13138:
1.191 harris41 13139: =item *
13140:
1.243 albertel 13141: symbclean($symb) : removes versions numbers from a symb, returns the
13142: cleaned symb
1.191 harris41 13143:
13144: =item *
13145:
1.243 albertel 13146: is_on_map($uri) : checks if the $uri is somewhere on the current
13147: course map, user must be in a course for it to work.
1.191 harris41 13148:
13149: =item *
13150:
1.243 albertel 13151: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13152:
13153: =item *
13154:
1.243 albertel 13155: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13156: a random seed, all arguments are optional, if they aren't sent it uses the
13157: environment to derive them. Note: if symb isn't sent and it can't get one
13158: from &symbread it will use the current time as its return value
1.191 harris41 13159:
13160: =item *
13161:
1.243 albertel 13162: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13163: unfakeable, receipt
1.191 harris41 13164:
13165: =item *
13166:
1.620 albertel 13167: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13168:
13169: =item *
13170:
1.243 albertel 13171: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13172:
13173: =item *
13174:
1.243 albertel 13175: 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 13176:
13177: =item *
13178:
1.243 albertel 13179: 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 13180:
13181: =item *
13182:
1.243 albertel 13183: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13184:
13185: =item *
13186:
1.243 albertel 13187: devalidate($symb) : devalidate temporary spreadsheet calculations,
13188: forcing spreadsheet to reevaluate the resource scores next time.
13189:
1.1172.2.13 raeburn 13190: =item *
13191:
13192: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13193: when viewing in course context.
13194:
13195: input: six args -- filename (decluttered), course number, course domain,
13196: url, symb (if registered) and group (if this is a
13197: group item -- e.g., bulletin board, group page etc.).
13198:
13199: output: array of five scalars --
13200: $cfile -- url for file editing if editable on current server
13201: $home -- homeserver of resource (i.e., for author if published,
13202: or course if uploaded.).
13203: $switchserver -- 1 if server switch will be needed.
13204: $forceedit -- 1 if icon/link should be to go to edit mode
13205: $forceview -- 1 if icon/link should be to go to view mode
13206:
13207: =item *
13208:
13209: is_course_upload($file,$cnum,$cdom)
13210:
13211: Used in course context to determine if current file was uploaded to
13212: the course (i.e., would be found in /userfiles/docs on the course's
13213: homeserver.
13214:
13215: input: 3 args -- filename (decluttered), course number and course domain.
13216: output: boolean -- 1 if file was uploaded.
13217:
1.243 albertel 13218: =back
13219:
13220: =head2 Storing/Retreiving Data
13221:
13222: =over 4
1.191 harris41 13223:
13224: =item *
13225:
1.243 albertel 13226: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13227: for this url; hashref needs to be given and should be a \%hashname; the
13228: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13229: be derived from the env
1.191 harris41 13230:
13231: =item *
13232:
1.243 albertel 13233: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13234: uses critical subroutine
1.191 harris41 13235:
13236: =item *
13237:
1.243 albertel 13238: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13239: all args are optional
1.191 harris41 13240:
13241: =item *
13242:
1.717 albertel 13243: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13244: dumps the complete (or key matching regexp) namespace into a hash
13245: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13246: normally &store()ed into
13247:
13248: $range should be either an integer '100' (give me the first 100
13249: matching records)
13250: or be two integers sperated by a - with no spaces
13251: '30-50' (give me the 30th through the 50th matching
13252: records)
13253:
13254:
13255: =item *
13256:
13257: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13258: replaces a &store() version of data with a replacement set of data
13259: for a particular resource in a namespace passed in the $storehash hash
13260: reference
13261:
13262: =item *
13263:
1.243 albertel 13264: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13265: works very similar to store/cstore, but all data is stored in a
13266: temporary location and can be reset using tmpreset, $storehash should
13267: be a hash reference, returns nothing on success
1.191 harris41 13268:
13269: =item *
13270:
1.243 albertel 13271: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13272: similar to restore, but all data is stored in a temporary location and
13273: can be reset using tmpreset. Returns a hash of values on success,
13274: error string otherwise.
1.191 harris41 13275:
13276: =item *
13277:
1.243 albertel 13278: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13279: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13280:
13281: =item *
13282:
1.243 albertel 13283: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13284: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13285:
13286: =item *
13287:
1.243 albertel 13288: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13289: namesp ($udom and $uname are optional)
1.191 harris41 13290:
13291: =item *
13292:
1.702 albertel 13293: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13294: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13295: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13296:
1.702 albertel 13297: $range should be either an integer '100' (give me the first 100
13298: matching records)
13299: or be two integers sperated by a - with no spaces
13300: '30-50' (give me the 30th through the 50th matching
13301: records)
1.449 matthew 13302: =item *
13303:
13304: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13305: $store can be a scalar, an array reference, or if the amount to be
13306: incremented is > 1, a hash reference.
13307:
13308: ($udom and $uname are optional)
1.191 harris41 13309:
13310: =item *
13311:
1.243 albertel 13312: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13313: ($udom and $uname are optional)
1.191 harris41 13314:
13315: =item *
13316:
1.243 albertel 13317: cput($namespace,$storehash,$udom,$uname) : critical put
13318: ($udom and $uname are optional)
1.191 harris41 13319:
13320: =item *
13321:
1.748 albertel 13322: newput($namespace,$storehash,$udom,$uname) :
13323:
13324: Attempts to store the items in the $storehash, but only if they don't
13325: currently exist, if this succeeds you can be certain that you have
13326: successfully created a new key value pair in the $namespace db.
13327:
13328:
13329: Args:
13330: $namespace: name of database to store values to
13331: $storehash: hashref to store to the db
13332: $udom: (optional) domain of user containing the db
13333: $uname: (optional) name of user caontaining the db
13334:
13335: Returns:
13336: 'ok' -> succeeded in storing all keys of $storehash
13337: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13338: least <key> already existed in the db (other
13339: requested keys may also already exist)
1.967 bisitz 13340: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13341: 'con_lost' -> unable to contact request server
13342: 'refused' -> action was not allowed by remote machine
13343:
13344:
13345: =item *
13346:
1.243 albertel 13347: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13348: reference filled in from namesp (encrypts the return communication)
13349: ($udom and $uname are optional)
1.191 harris41 13350:
13351: =item *
13352:
1.243 albertel 13353: log($udom,$name,$home,$message) : write to permanent log for user; use
13354: critical subroutine
13355:
1.806 raeburn 13356: =item *
13357:
1.860 raeburn 13358: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13359: array reference filled in from namespace found in domain level on either
13360: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13361:
13362: =item *
13363:
1.860 raeburn 13364: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13365: domain level either on specified domain server ($uhome) or primary domain
13366: server ($udom and $uhome are optional)
1.806 raeburn 13367:
1.943 raeburn 13368: =item *
13369:
1.1172.2.35 raeburn 13370: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13371: for: authentication, language, quotas, timezone, date locale, and portal URL in
13372: the target domain.
13373:
13374: May also include additional key => value pairs for the following groups:
13375:
13376: =over
13377:
13378: =item
13379: disk quotas (MB allocated by default to portfolios and authoring spaces).
13380:
13381: =over
13382:
13383: =item defaultquota, authorquota
13384:
13385: =back
13386:
13387: =item
13388: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13389: portfolio for users).
13390:
13391: =over
13392:
13393: =item
13394: aboutme, blog, webdav, portfolio
13395:
13396: =back
13397:
13398: =item
13399: requestcourses: ability to request courses, and how requests are processed.
13400:
13401: =over
13402:
13403: =item
1.1172.2.37 raeburn 13404: official, unofficial, community, textbook
1.1172.2.35 raeburn 13405:
13406: =back
13407:
13408: =item
13409: inststatus: types of institutional affiliation, and order in which they are displayed.
13410:
13411: =over
13412:
13413: =item
13414: inststatustypes, inststatusorder
13415:
13416: =back
13417:
13418: =item
13419: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13420: for course's uploaded content.
13421:
13422: =over
13423:
13424: =item
1.1172.2.37 raeburn 13425: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13426:
13427: =back
13428:
13429: =item
13430: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13431: on your servers.
13432:
13433: =over
13434:
13435: =item
13436: remotesessions, hostedsessions
13437:
13438: =back
13439:
13440: =back
13441:
13442: In cases where a domain coordinator has never used the "Set Domain Configuration"
13443: utility to create a configuration.db file on a domain's primary library server
13444: only the following domain defaults: auth_def, auth_arg_def, lang_def
13445: -- corresponding values are authentication type (internal, krb4, krb5,
13446: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13447: will be available. Values are retrieved from cache (if current), unless the
13448: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13449: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13450:
13451: Typical usage:
1.943 raeburn 13452:
1.1172.2.35 raeburn 13453: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13454:
1.243 albertel 13455: =back
13456:
13457: =head2 Network Status Functions
13458:
13459: =over 4
1.191 harris41 13460:
13461: =item *
13462:
1.1137 raeburn 13463: dirlist() : return directory list based on URI (first arg).
13464:
13465: Inputs: 1 required, 5 optional.
13466:
13467: =over
13468:
13469: =item
13470: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13471:
13472: =item
13473: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13474:
13475: =item
13476: $username - username of user/course to be listed. Extracted from $uri if absent.
13477:
13478: =item
13479: $getpropath - boolean: 1 if prepend path using &propath().
13480:
13481: =item
13482: $getuserdir - boolean: 1 if prepend path for "userfiles".
13483:
13484: =item
13485: $alternateRoot - path to prepend in place of path from $uri.
13486:
13487: =back
13488:
13489: Returns: Array of up to two items.
13490:
13491: =over
13492:
13493: a reference to an array of files/subdirectories
13494:
13495: =over
13496:
13497: Each element in the array of files/subdirectories is a & separated list of
13498: item name and the result of running stat on the item. If dirlist was requested
13499: for a file instead of a directory, the item name will be ''. For a directory
13500: listing, if the item is a metadata file, the element will end &N&M
13501: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13502: default copyright set (1).
13503:
13504: =back
13505:
13506: a scalar containing error condition (if encountered).
13507:
13508: =over
13509:
13510: =item
13511: no_host (no homeserver identified for $username:$domain).
13512:
13513: =item
13514: no_such_host (server contacted for listing not identified as valid host).
13515:
13516: =item
13517: con_lost (connection to remote server failed).
13518:
13519: =item
13520: refused (invalid $username:$domain received on lond side).
13521:
13522: =item
13523: no_such_dir (directory at specified path on lond side does not exist).
13524:
13525: =item
13526: empty (directory at specified path on lond side is empty).
13527:
13528: =over
13529:
13530: This is currently not encountered because the &ls3, &ls2,
13531: &ls (_handler) routines on the lond side do not filter out
13532: . and .. from a directory listing.
13533:
13534: =back
13535:
13536: =back
13537:
13538: =back
1.191 harris41 13539:
13540: =item *
13541:
1.243 albertel 13542: spareserver() : find server with least workload from spare.tab
13543:
1.986 foxr 13544:
13545: =item *
13546:
13547: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13548: if there is no corresponding loncapa host.
13549:
1.243 albertel 13550: =back
13551:
1.986 foxr 13552:
1.243 albertel 13553: =head2 Apache Request
13554:
13555: =over 4
1.191 harris41 13556:
13557: =item *
13558:
1.243 albertel 13559: ssi($url,%hash) : server side include, does a complete request cycle on url to
13560: localhost, posts hash
13561:
13562: =back
13563:
13564: =head2 Data to String to Data
13565:
13566: =over 4
1.191 harris41 13567:
13568: =item *
13569:
1.243 albertel 13570: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13571: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13572:
13573: =item *
13574:
1.243 albertel 13575: hashref2str($hashref) : convert a hashref into a string complete with
13576: escaping and '=' and '&' separators, supports elements that are
13577: arrayrefs and hashrefs
1.191 harris41 13578:
13579: =item *
13580:
1.243 albertel 13581: arrayref2str($arrayref) : convert an arrayref into a string complete
13582: with escaping and '&' separators, supports elements that are arrayrefs
13583: and hashrefs
1.191 harris41 13584:
13585: =item *
13586:
1.243 albertel 13587: str2hash($string) : convert string to hash using unescaping and
13588: splitting on '=' and '&', supports elements that are arrayrefs and
13589: hashrefs
1.191 harris41 13590:
13591: =item *
13592:
1.243 albertel 13593: str2array($string) : convert string to hash using unescaping and
13594: splitting on '&', supports elements that are arrayrefs and hashrefs
13595:
13596: =back
13597:
13598: =head2 Logging Routines
13599:
13600:
13601: These routines allow one to make log messages in the lonnet.log and
13602: lonnet.perm logfiles.
1.191 harris41 13603:
1.1119 foxr 13604: =over 4
13605:
1.191 harris41 13606: =item *
13607:
1.243 albertel 13608: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13609:
13610: =item *
13611:
1.243 albertel 13612: logthis() : append message to the normal lonnet.log file, it gets
13613: preiodically rolled over and deleted.
1.191 harris41 13614:
13615: =item *
13616:
1.243 albertel 13617: logperm() : append a permanent message to lonnet.perm.log, this log
13618: file never gets deleted by any automated portion of the system, only
13619: messages of critical importance should go in here.
13620:
1.1119 foxr 13621:
1.243 albertel 13622: =back
13623:
13624: =head2 General File Helper Routines
13625:
13626: =over 4
1.191 harris41 13627:
13628: =item *
13629:
1.481 raeburn 13630: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13631: (a) files in /uploaded
13632: (i) If a local copy of the file exists -
13633: compares modification date of local copy with last-modified date for
13634: definitive version stored on home server for course. If local copy is
13635: stale, requests a new version from the home server and stores it.
13636: If the original has been removed from the home server, then local copy
13637: is unlinked.
13638: (ii) If local copy does not exist -
13639: requests the file from the home server and stores it.
13640:
13641: If $caller is 'uploadrep':
13642: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13643: for request for files originally uploaded via DOCS.
13644: - returns 'ok' if fresh local copy now available, -1 otherwise.
13645:
13646: Otherwise:
13647: This indicates a call from the content generation phase of the request.
13648: - returns the entire contents of the file or -1.
13649:
13650: (b) files in /res
13651: - returns the entire contents of a file or -1;
13652: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13653:
1.712 albertel 13654:
13655: =item *
13656:
13657: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13658: reference
13659:
13660: returns either a stat() list of data about the file or an empty list
13661: if the file doesn't exist or couldn't find out about it (connection
13662: problems or user unknown)
13663:
1.191 harris41 13664: =item *
13665:
1.243 albertel 13666: filelocation($dir,$file) : returns file system location of a file
13667: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13668: directory that relative $file lookups are to looked in ($dir of /a/dir
13669: and a file of ../bob will become /a/bob)
1.191 harris41 13670:
13671: =item *
13672:
13673: hreflocation($dir,$file) : returns file system location or a URL; same as
13674: filelocation except for hrefs
13675:
13676: =item *
13677:
13678: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13679:
1.243 albertel 13680: =back
13681:
1.608 albertel 13682: =head2 Usererfile file routines (/uploaded*)
13683:
13684: =over 4
13685:
13686: =item *
13687:
13688: userfileupload(): main rotine for putting a file in a user or course's
13689: filespace, arguments are,
13690:
1.620 albertel 13691: formname - required - this is the name of the element in $env where the
1.608 albertel 13692: filename, and the contents of the file to create/modifed exist
1.620 albertel 13693: the filename is in $env{'form.'.$formname.'.filename'} and the
13694: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13695: context - if coursedoc, store the file in the course of the active role
13696: of the current user;
13697: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13698: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13699: subdir - required - subdirectory to put the file in under ../userfiles/
13700: if undefined, it will be placed in "unknown"
13701:
13702: (This routine calls clean_filename() to remove any dangerous
13703: characters from the filename, and then calls finuserfileupload() to
13704: complete the transaction)
13705:
13706: returns either the url of the uploaded file (/uploaded/....) if successful
13707: and /adm/notfound.html if unsuccessful
13708:
13709: =item *
13710:
13711: clean_filename(): routine for cleaing a filename up for storage in
13712: userfile space, argument is:
13713:
13714: filename - proposed filename
13715:
13716: returns: the new clean filename
13717:
13718: =item *
13719:
1.1090 raeburn 13720: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13721: userspace, probably shouldn't be called directly
13722:
13723: docuname: username or courseid of destination for the file
13724: docudom: domain of user/course of destination for the file
13725: formname: same as for userfileupload()
1.1090 raeburn 13726: fname: filename (including subdirectories) for the file
13727: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13728: allfiles: reference to hash used to store objects found by parser
13729: codebase: reference to hash used for codebases of java objects found by parser
13730: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13731: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13732: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13733: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13734: context: if 'overwrite', will move the uploaded file from its temporary location to
13735: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13736: mimetype: reference to scalar to accommodate mime type determined
13737: from File::MMagic if $parser = parse.
1.608 albertel 13738:
13739: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13740: and /adm/notfound.html if unsuccessful (or an error message if context
13741: was 'overwrite').
13742:
1.608 albertel 13743:
13744: =item *
13745:
13746: renameuserfile(): renames an existing userfile to a new name
13747:
13748: Args:
13749: docuname: username or courseid of destination for the file
13750: docudom: domain of user/course of destination for the file
13751: old: current file name (including any subdirs under userfiles)
13752: new: desired file name (including any subdirs under userfiles)
13753:
13754: =item *
13755:
13756: mkdiruserfile(): creates a directory is a userfiles dir
13757:
13758: Args:
13759: docuname: username or courseid of destination for the file
13760: docudom: domain of user/course of destination for the file
13761: dir: dir to create (including any subdirs under userfiles)
13762:
13763: =item *
13764:
13765: removeuserfile(): removes a file that exists in userfiles
13766:
13767: Args:
13768: docuname: username or courseid of destination for the file
13769: docudom: domain of user/course of destination for the file
13770: fname: filname to delete (including any subdirs under userfiles)
13771:
13772: =item *
13773:
13774: removeuploadedurl(): convience function for removeuserfile()
13775:
13776: Args:
13777: url: a full /uploaded/... url to delete
13778:
1.747 albertel 13779: =item *
13780:
13781: get_portfile_permissions():
13782: Args:
13783: domain: domain of user or course contain the portfolio files
13784: user: name of user or num of course contain the portfolio files
13785: Returns:
13786: hashref of a dump of the proper file_permissions.db
13787:
13788:
13789: =item *
13790:
13791: get_access_controls():
13792:
13793: Args:
13794: current_permissions: the hash ref returned from get_portfile_permissions()
13795: group: (optional) the group you want the files associated with
13796: file: (optional) the file you want access info on
13797:
13798: Returns:
1.749 raeburn 13799: a hash (keys are file names) of hashes containing
13800: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13801: values are XML containing access control settings (see below)
1.747 albertel 13802:
13803: Internal notes:
13804:
1.749 raeburn 13805: access controls are stored in file_permissions.db as key=value pairs.
13806: key -> path to file/file_name\0uniqueID:scope_end_start
13807: where scope -> public,guest,course,group,domains or users.
13808: end -> UNIX time for end of access (0 -> no end date)
13809: start -> UNIX time for start of access
13810:
13811: value -> XML description of access control
13812: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13813: <start></start>
13814: <end></end>
13815:
13816: <password></password> for scope type = guest
13817:
13818: <domain></domain> for scope type = course or group
13819: <number></number>
13820: <roles id="">
13821: <role></role>
13822: <access></access>
13823: <section></section>
13824: <group></group>
13825: </roles>
13826:
13827: <dom></dom> for scope type = domains
13828:
13829: <users> for scope type = users
13830: <user>
13831: <uname></uname>
13832: <udom></udom>
13833: </user>
13834: </users>
13835: </scope>
13836:
13837: Access data is also aggregated for each file in an additional key=value pair:
13838: key -> path to file/file_name\0accesscontrol
13839: value -> reference to hash
13840: hash contains key = value pairs
13841: where key = uniqueID:scope_end_start
13842: value = UNIX time record was last updated
13843:
13844: Used to improve speed of look-ups of access controls for each file.
13845:
13846: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13847:
1.1172.2.13 raeburn 13848: =item *
13849:
1.749 raeburn 13850: modify_access_controls():
13851:
13852: Modifies access controls for a portfolio file
13853: Args
13854: 1. file name
13855: 2. reference to hash of required changes,
13856: 3. domain
13857: 4. username
13858: where domain,username are the domain of the portfolio owner
13859: (either a user or a course)
13860:
13861: Returns:
13862: 1. result of additions or updates ('ok' or 'error', with error message).
13863: 2. result of deletions ('ok' or 'error', with error message).
13864: 3. reference to hash of any new or updated access controls.
13865: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13866: key = integer (inbound ID)
1.1172.2.13 raeburn 13867: value = uniqueID
13868:
13869: =item *
13870:
13871: get_timebased_id():
13872:
13873: Attempts to get a unique timestamp-based suffix for use with items added to a
13874: course via the Course Editor (e.g., folders, composite pages,
13875: group bulletin boards).
13876:
13877: Args: (first three required; six others optional)
13878:
13879: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13880: docssequence, or name of group
13881:
13882: 2. keyid (alphanumeric): name of temporary locking key in hash,
13883: e.g., num, boardids
13884:
13885: 3. namespace: name of gdbm file used to store suffixes already assigned;
13886: file will be named nohist_namespace.db
13887:
13888: 4. cdom: domain of course; default is current course domain from %env
13889:
13890: 5. cnum: course number; default is current course number from %env
13891:
13892: 6. idtype: set to concat if an additional digit is to be appended to the
13893: unix timestamp to form the suffix, if the plain timestamp is already
13894: in use. Default is to not do this, but simply increment the unix
13895: timestamp by 1 until a unique key is obtained.
13896:
13897: 7. who: holder of locking key; defaults to user:domain for user.
13898:
13899: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13900: retrying); default is 3.
13901:
13902: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13903:
13904: Returns:
13905:
13906: 1. suffix obtained (numeric)
13907:
13908: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13909:
13910: 3. error: contains (localized) error message if an error occurred.
13911:
1.747 albertel 13912:
1.608 albertel 13913: =back
13914:
1.243 albertel 13915: =head2 HTTP Helper Routines
13916:
13917: =over 4
13918:
1.191 harris41 13919: =item *
13920:
13921: escape() : unpack non-word characters into CGI-compatible hex codes
13922:
13923: =item *
13924:
13925: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13926:
1.243 albertel 13927: =back
13928:
13929: =head1 PRIVATE SUBROUTINES
13930:
13931: =head2 Underlying communication routines (Shouldn't call)
13932:
13933: =over 4
13934:
13935: =item *
13936:
13937: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13938:
13939: =item *
13940:
13941: reply() : uses subreply to send a message to remote machine, logs all failures
13942:
13943: =item *
13944:
13945: critical() : passes a critical message to another server; if cannot
13946: get through then place message in connection buffer directory and
13947: returns con_delayed, if incapable of saving message, returns
13948: con_failed
13949:
13950: =item *
13951:
13952: reconlonc() : tries to reconnect lonc client processes.
13953:
13954: =back
13955:
13956: =head2 Resource Access Logging
13957:
13958: =over 4
13959:
13960: =item *
13961:
13962: flushcourselogs() : flush (save) buffer logs and access logs
13963:
13964: =item *
13965:
13966: courselog($what) : save message for course in hash
13967:
13968: =item *
13969:
13970: courseacclog($what) : save message for course using &courselog(). Perform
13971: special processing for specific resource types (problems, exams, quizzes, etc).
13972:
1.191 harris41 13973: =item *
13974:
13975: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13976: as a PerlChildExitHandler
1.243 albertel 13977:
13978: =back
13979:
13980: =head2 Other
13981:
13982: =over 4
13983:
13984: =item *
13985:
13986: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13987:
13988: =back
13989:
13990: =cut
1.877 foxr 13991:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>